text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*通过计算两个矩形在x轴或y轴的投影是否均有重合判断重叠矩形,利用两两对比迭代求出全部重叠矩形
*/
//创建矩形结构
[System.Serializable]
public struct Rectangle
{
public Vector2 v1;
public Vector2 v2;
public Vector2 v3;
public Vector2 v4;
}
public class T02 : MonoBehaviour
{
public Rectangle[] rectangles;
public int rectCount; //矩形个数
public int rect_over_Sum; //重叠矩形个数
public int pointRange; //矩形的点坐标给个随机范围,0 —— vaule
//初始化
void Init()
{
rect_over_Sum = 0;
rectangles = new Rectangle[rectCount];
for (int i = 0; i < rectangles.Length; i++) //按设定矩形数量创建矩形
{
rectangles[i] = CreateRectangles();
}
}
Rectangle CreateRectangles() //依据pointRange创建随机坐标,创建矩形
{
Rectangle rectangle = new Rectangle();
rectangle.v1 = new Vector2(Random.Range(0, pointRange), Random.Range(0, pointRange));
rectangle.v3 = new Vector2(Random.Range(0, pointRange), Random.Range(0, pointRange));
rectangle.v2 = new Vector2((rectangle.v1.x - rectangle.v1.y + rectangle.v3.x + rectangle.v3.y) / 2,
(rectangle.v1.x + rectangle.v1.y - rectangle.v3.x + rectangle.v3.y) / 2);
rectangle.v4 = new Vector2((rectangle.v1.x + rectangle.v1.y + rectangle.v3.x - rectangle.v3.y) / 2,
(-rectangle.v1.x + rectangle.v1.y + rectangle.v3.x + rectangle.v3.y) / 2);
return rectangle;
}
private void Start()
{
Init();
//分别计算投影大小,判断重叠矩形个数
for (int i = 0; i < rectCount; i++)
{
for(int j = i+1;j <rectCount;j++)
{
Vector2 rect01PX = CalProjectionInterval(rectangles[i].v1.x, rectangles[i].v2.x, rectangles[i].v3.x, rectangles[i].v4.x);
Vector2 rect02PX = CalProjectionInterval(rectangles[j].v1.x, rectangles[j].v2.x, rectangles[j].v3.x, rectangles[j].v4.x);
Vector2 rect01PY = CalProjectionInterval(rectangles[i].v1.y, rectangles[i].v2.y, rectangles[i].v3.y, rectangles[i].v4.y);
Vector2 rect02PY = CalProjectionInterval(rectangles[j].v1.y, rectangles[j].v2.y, rectangles[j].v3.y, rectangles[j].v4.y);
if (isRectangleOver(rect01PX,rect02PX,rect01PY,rect02PY))
{
rect_over_Sum++;
break;
}
}
}
Debug.Log("共有" + rectCount +"个矩形,有" + rect_over_Sum+"个重叠矩形。");
}
//计算投影大小,返回值vector2(轴向最小值,轴向最大值)表示一个区间
Vector2 CalProjectionInterval(float f1,float f2,float f3,float f4)
{
float max = f1;
float min = 0;
if (f2 > max)
{
max = f2;
min = f1;
}
else
min = f2;
if (f3 > max)
max = f3;
else
if(min > f3)
{
min = f3;
}
if (f4 > max)
max = f4;
else
if (min > f4)
{
min = f4;
}
return new Vector2(min, max);
}
//判断两矩形投影是否重叠
public bool isRectangleOver(Vector2 rect01X,Vector2 rect02X, Vector2 rect01Y, Vector2 rect02Y)
{
bool x_over = !(rect01X.y <= rect02X.x || rect02X.y <= rect01X.x);
bool y_over = !(rect01Y.y <= rect02Y.x || rect02Y.y <= rect01Y.x);
return x_over && y_over;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Sind.BLL;
using Sind.Model;
using Sind.Web.Publico.Controles;
using Sind.Web.Publico.Helpers;
namespace Sind.Web.Cadastros
{
public partial class FilialDetalhe : System.Web.UI.Page
{
#region[ PROPRIEDADES ]
private int IdFilial
{
get { return (int)ViewState["ID_FILIAL"]; }
set { ViewState["ID_FILIAL"] = value; }
}
private IList<Usuario> listaUsuarios
{
get { return SessionHelper.ListUsuarios; }
set { SessionHelper.ListUsuarios = value; }
}
private IList<Usuario> listaUsuariosAdd { get; set; }
#endregion
#region [ EVENTOS ]
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
CarregarPrimeiroAcesso();
AssociadorDeListas1.FindControl("txtFiltroNome").Focus();
}
catch (Exception ex)
{
ExceptionHelper.PresentationErrorTreatment(ex);
}
}
protected void btSalvar_Click(object sender, EventArgs e)
{
try
{
Salvar();
}
catch (Exception ex)
{
ExceptionHelper.PresentationErrorTreatment(ex);
}
Response.Redirect("FilialLista.aspx");
}
protected void btCancelar_Click(object sender, EventArgs e)
{
Response.Redirect("FilialLista.aspx");
}
#endregion
#region [ MÉTODOS ]
private void CarregarPrimeiroAcesso()
{
GetId();
Filial filial = new ManterFilial().FindById(this.IdFilial);
Set(filial);
this.listaUsuarios = new ManterUsuario().GetAtivos();
ListBox listaOrigem = new ListBox();
foreach (Usuario usuario in listaUsuarios)
listaOrigem.Items.Add(new ListItem(usuario.UserName, usuario.Id.ToString()));
ListBox listaDestino = new ListBox();
if (listaUsuariosAdd != null)
{
foreach (Usuario usuario in listaUsuariosAdd)
listaDestino.Items.Add(new ListItem(usuario.UserName, usuario.Id.ToString()));
}
AssociadorDeListas1.CarregarListas(listaOrigem, listaDestino);
}
private void GetId()
{
this.IdFilial = Request.QueryString["Id"] != null
? Convert.ToInt32(Request.QueryString["Id"])
: 0;
}
private void Set(Filial filial)
{
txtNome.Text = filial.Nome;
if (filial.Usuarios != null)
listaUsuariosAdd = filial.Usuarios;
hidSigla.Value = filial.Sigla;
hidCodigoCusto.Value = filial.CodigoCusto;
}
private void Salvar()
{
Filial filial = Get();
ManterFilial manterFilial = new ManterFilial();
var msgSucesso = "";
manterFilial.Update(filial);
msgSucesso = String.Format("Associação de usuário(s) à filial '{0}' realizada com sucesso", filial.Nome);
GerenciadorMensagens.IncluirMensagemSucesso(msgSucesso);
}
private Filial Get()
{
Filial filial = new Filial();
filial.Id = this.IdFilial;
filial.Nome = txtNome.Text;
filial.Sigla = hidSigla.Value;
filial.CodigoCusto = hidCodigoCusto.Value;
if (filial.Usuarios == null)
filial.Usuarios = new List<Usuario>();
ListBox itensAdicionados = (ListBox)AssociadorDeListas1.FindControl("lstListaAdicionados");
var listaGeralUsuarios = new ManterUsuario().GetAll();
foreach (ListItem item in itensAdicionados.Items)
{
var usuario = listaGeralUsuarios.First(v => v.Id == Convert.ToInt32(item.Value));
filial.Usuarios.Add(usuario);
}
return filial;
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IngredientPanel : MonoBehaviour {
public void Zoomasaurus(bool isZoom)
{
if (isZoom)
gameObject.transform.localScale *= 3;
else
gameObject.transform.localScale = new Vector3(1, 1, 1);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BELCORP.GestorDocumental.BE.Comun
{
[Serializable]
public class PerfilesBE
{
public string Correo { get; set; }
public string CentroCostos { get; set; }
public bool Notificado { get; set; }
public string Pais { get; set; }
public string NombreColaborador { get; set; }
public string GrupoFuncional { get; set; }
public string NivelJerarquico { get; set; }
public string Vicepresidencia { get; set; }
public string Compania { get; set; }
public string Genero { get; set; }
public string Sede { get; set; }
public int IDCentroCostos { get; set; }
public int IDPais { get; set; }
public int IDGrupoFuncional { get; set; }
public int IDNivelJerarquico { get; set; }
public int IDVicepresidencia { get; set; }
public int IDCompania { get; set; }
public int IDGenero { get; set; }
public int IDSede { get; set; }
public string NombreColaboradorCorreo
{
get
{
return string.Format("{0} ({1})", this.NombreColaborador, this.Correo);
}
}
public string CodigoCentroCostos{ get; set; }
public string DescripcionCentroCostos { get; set; }
public string CodigoDescripcionCentroCostos
{
get
{
return string.Format(@"{0}\{1}", this.CodigoCentroCostos, this.DescripcionCentroCostos);
}
}
public string CodigoUsuario { get; set; }
//public string LoginName { get; set; }
}
}
|
using System.Collections.Generic;
using WebsiteManagerPanel.Data.Entities.Base;
using WebsiteManagerPanel.Data.Entities.Enums;
namespace WebsiteManagerPanel.Data.Entities
{
public class Field : AuditEntity
{
public Definition Definition { get; protected set; }
public string Name { get; protected set; }
public FieldType Type { get; protected set; }
public string ? Description { get; set; }
public ICollection<FieldValue>? FieldValues { get; set; }
protected Field()
{
FieldValues = new List<FieldValue>();
}
public Field(Definition definition, string name) : this()
{
Definition = definition;
Name = name;
}
public Field(string name, string description, FieldType fieldType)
{
Name = name;
Description = description;
Type = fieldType;
}
public void Update(string name, string description)
{
Name = name;
Description = description;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SpaceHosting.Index.Sparnn.Helpers;
namespace SpaceHosting.Index.Tests.Sparnn.Helpers.ListExtensionsTests
{
public class HStackTests
{
[Test]
public void SuccessfulCase()
{
var matrix1 = (IEnumerable<int[]>)new[]
{
new[] {11, 12, 13},
new[] {21, 22, 23},
};
var matrix2 = (IEnumerable<int[]>)new[]
{
new[] {14, 15, 16},
new[] {24, 25},
};
var result = new[] {matrix1, matrix2}.HStack().ToArray();
Assert.That(result[0], Is.EquivalentTo(new[] {11, 12, 13, 14, 15, 16}));
Assert.That(result[1], Is.EquivalentTo(new[] {21, 22, 23, 24, 25}));
}
[Test]
public void DifferentRowsNumber_Throws()
{
var matrix1 = (IEnumerable<int[]>)new[]
{
new[] {11, 12, 13},
new[] {21, 22, 23},
};
var matrix2 = (IEnumerable<int[]>)new[]
{
new[] {14, 15, 16},
new[] {24, 25},
new[] {34, 35},
};
Assert.Throws<InvalidOperationException>(() => new[] {matrix1, matrix2}.HStack().ToArray());
}
[Test]
public void Success_if_rows_more_than_columns()
{
var matrix1 = (IEnumerable<int[]>)new[]
{
new[] {11, 12},
new[] {21, 22},
new[] {31, 32},
new[] {41, 42},
};
var matrix2 = (IEnumerable<int[]>)new[]
{
new[] {13, 14},
new[] {23, 24},
new[] {33, 34},
new[] {43, 44},
};
var result = new[] {matrix1, matrix2}.HStack().ToArray();
Assert.That(result[0], Is.EquivalentTo(new[] {11, 12, 13, 14}));
Assert.That(result[1], Is.EquivalentTo(new[] {21, 22, 23, 24}));
Assert.That(result[2], Is.EquivalentTo(new[] {31, 32, 33, 34}));
Assert.That(result[3], Is.EquivalentTo(new[] {41, 42, 43, 44}));
}
[Test]
public void Returns_requested_count_of_rows()
{
var matrix1 = (IEnumerable<int[]>)new[]
{
new[] {11, 12},
new[] {21, 22},
new[] {31, 32},
new[] {41, 42},
};
var matrix2 = (IEnumerable<int[]>)new[]
{
new[] {13, 14},
new[] {23, 24},
new[] {33, 34},
new[] {43, 44},
};
var result = new[] {matrix1, matrix2}.HStack().ToArray();
Assert.That(result.Length, Is.EqualTo(4));
}
}
}
|
using System;
namespace SymbolicMath {
class MathUtil {
static public double degreeToRadian(double degree) {
return degree * Math.PI / 180;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Net.Mail;
using System.Net;
using Property_cls;
using Property_Cryptography;
namespace Property
{
public partial class Testimonials : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
cls_Property clsobj = new cls_Property();
protected void Page_Load(object sender, EventArgs e)
{
}
//protected void btnSend_Click(object sender, EventArgs e)
//{
// try
// {
// SqlCommand cmd = new SqlCommand();
// cmd.CommandType = CommandType.StoredProcedure;
// cmd.CommandText = "ups_AddTestimonial";
// cmd.Connection = conn;
// cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
// cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
// cmd.Parameters.AddWithValue("@Comments", txtcomments.Text);
// cmd.Parameters.AddWithValue("@Date", txtDate.Text);
// if (conn.State == ConnectionState.Closed)
// {
// conn.Open();
// }
// cmd.Connection = conn;
// cmd.ExecuteNonQuery();
// conn.Close();
// clear();
// //Response.Redirect("~/Admin/AdminDashboard.aspx", false);
// }
// catch (Exception ex)
// {
// //throw ex;
// }
//}
//public void clear()
//{
// //txtFirstName.Text = string.Empty;
// //txtLastName.Text = string.Empty;
// //txtcomments.Text= string.Empty;
// //txtDate.Text = DateTime.Now.ToString();
//}
}
} |
namespace Ejercicio2
{
public class prueba
{
}
} |
using System;
using System.Threading.Tasks;
using Altinn.Platform.Events.Functions.Models;
using AltinnIntegrator.Functions.Services.Interface;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace AltinnIntegrator
{
public class EventsConfirmation
{
private readonly IAltinnApp _altinnApp;
public EventsConfirmation(IAltinnApp altinnApp)
{
_altinnApp = altinnApp;
}
[FunctionName("EventsConfirmation")]
public async Task Run([QueueTrigger("events-confirmation", Connection = "QueueStorage")]string item, ILogger log)
{
CloudEvent cloudEvent = System.Text.Json.JsonSerializer.Deserialize<CloudEvent>(item);
await _altinnApp.AddCompleteConfirmation(cloudEvent.Source.AbsoluteUri);
log.LogInformation($"C# Queue trigger function processed: {item}");
}
}
}
|
using System;
namespace Core
{
public class Kit
{
public int KitID { get; }
public string KitName { get; }
///public bool IsSelected { get; set; }
/// <summary>
/// конструктор
/// </summary>
/// <param name="id">ID комплектации</param>
/// <param name="name">название комплектации</param>
public Kit(int id, string name)
{
KitID = id;
KitName = name;
}
/// <summary>
/// переопределение Equals
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj is Kit)
{
Kit kit = obj as Kit;
return ((this.KitID == kit.KitID) &&
(String.Equals(this.KitName, kit.KitName))
// && this.IsSelected == kit.IsSelected
);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return KitName;
}
}
}
|
using System;
using EngageNet.Api;
using NUnit.Framework;
using Rhino.Mocks;
namespace EngageNet.Tests
{
[TestFixture]
public class ServiceActivityTests
{
#region Setup/Teardown
[SetUp]
public void TestSetup()
{
_mockApiWrapper = MockRepository.GenerateMock<IApiWrapper>();
_engageNet = new EngageNet(_mockApiWrapper);
}
#endregion
private EngageNet _engageNet;
private IApiWrapper _mockApiWrapper;
//[Test]
//public void AddActivity_CallsApiWrapperWithCorrectDetails()
//{
// mockApiWrapper.Expect(
// w => w.Call(
// Arg<string>.Matches(s => s.Equals("activity")),
// Arg<IDictionary<string, string>>.Matches(
// d => d["identifier"].Equals("id")
// ))).Return(null);
// rpxService.AddActivity("id", null);
// mockApiWrapper.VerifyAllExpectations();
//}
[Test]
[ExpectedException(typeof (NotImplementedException))]
public void AddActivity_ThrowsNotImplementedException()
{
_engageNet.AddActivity("", null);
}
}
} |
// Copyright 2016-2020 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Core.Sinks;
class AggregateSink : ILogEventSink
{
readonly ILogEventSink[] _sinks;
public AggregateSink(IEnumerable<ILogEventSink> sinks)
{
Guard.AgainstNull(sinks);
_sinks = sinks.ToArray();
}
public void Emit(LogEvent logEvent)
{
List<Exception>? exceptions = null;
foreach (var sink in _sinks)
{
try
{
sink.Emit(logEvent);
}
catch (Exception ex)
{
SelfLog.WriteLine("Caught exception while emitting to sink {0}: {1}", sink, ex);
exceptions ??= new();
exceptions.Add(ex);
}
}
if (exceptions != null)
throw new AggregateException("Failed to emit a log event.", exceptions);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Target), typeof(MoveToTarget), typeof(Collision))]
[RequireComponent(typeof(SpriteRenderer))]
public class Chaser : MonoBehaviour
{
private void Start()
{
GetComponent<SpriteRenderer>().color = Color.red;
}
// Update is called once per frame
void Update()
{
var player = GameObject.FindWithTag("Player");
var target = GetComponent<Target>();
Debug.Assert(target != null);
target.Position = player.transform.position;
target.Tag = player.tag;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FiiiCoin.Models
{
public class Message : BaseModel
{
private string signature;
public string Signature
{
get { return signature; }
set
{
signature = value;
OnChanged("Signature");
}
}
private string publicKey;
public string PublicKey
{
get { return publicKey; }
set
{
publicKey = value;
OnChanged("PublicKey");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace ISE.SecurityLogin
{
public static class Encryption
{
private const string MyKey = "$95*#Hwl5679";
private static string AlgorithmName = "TripleDES";
private static Rfc2898DeriveBytes GetKey()
{
byte[] salt = StrToByteArray("01234567");
var key = new Rfc2898DeriveBytes(MyKey, salt);
return key;
}
private static Rfc2898DeriveBytes GetKey(string key)
{
byte[] salt = StrToByteArray("01234567");
var rkey = new Rfc2898DeriveBytes(key, salt);
return rkey;
}
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
public static string EncryptData(string ClearData)
{
// Convert string ClearData to byte array
byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = GetKey().GetBytes(Algorithm.KeySize / 8);
// Encrypt information
MemoryStream Target = new MemoryStream();
// Append IV
Algorithm.GenerateIV();
Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);
// Encrypt Clear Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Convert.ToBase64String(Target_byte_Array);
string target_url_string = HttpUtility.UrlEncode(Target_string);
return target_url_string;
}
public static string DecryptData(string EncryptedData)
{
string target_encoded_string = HttpUtility.UrlDecode(EncryptedData);
byte[] EncryptedData_byte_Array = Convert.FromBase64String(target_encoded_string);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = Algorithm.Key = GetKey().GetBytes(Algorithm.KeySize / 8);
// Decrypt information
MemoryStream Target = new MemoryStream();
// Read IV
int ReadPos = 0;
byte[] IV = new byte[Algorithm.IV.Length];
Array.Copy(EncryptedData_byte_Array, IV, IV.Length);
Algorithm.IV = IV;
ReadPos += Algorithm.IV.Length;
// Decrypt Encrypted Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(EncryptedData_byte_Array, ReadPos, EncryptedData_byte_Array.Length - ReadPos);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Encoding.UTF8.GetString(Target_byte_Array);
return Target_string;
}
public static string EncryptData(string ClearData, string key)
{
// Convert string ClearData to byte array
byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = GetKey(key).GetBytes(Algorithm.KeySize / 8);
// Encrypt information
MemoryStream Target = new MemoryStream();
// Append IV
Algorithm.GenerateIV();
Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);
// Encrypt Clear Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Convert.ToBase64String(Target_byte_Array);
return Target_string;
}
public static string DecryptData(string EncryptedData, string key)
{
byte[] EncryptedData_byte_Array = Convert.FromBase64String(EncryptedData);
// Now Create The Algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = Algorithm.Key = GetKey(key).GetBytes(Algorithm.KeySize / 8);
// Decrypt information
MemoryStream Target = new MemoryStream();
// Read IV
int ReadPos = 0;
byte[] IV = new byte[Algorithm.IV.Length];
Array.Copy(EncryptedData_byte_Array, IV, IV.Length);
Algorithm.IV = IV;
ReadPos += Algorithm.IV.Length;
// Decrypt Encrypted Data
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(EncryptedData_byte_Array, ReadPos, EncryptedData_byte_Array.Length - ReadPos);
cs.FlushFinalBlock();
// Output
byte[] Target_byte_Array = Target.ToArray();
string Target_string = Encoding.UTF8.GetString(Target_byte_Array);
return Target_string;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Users.Mapeamentos;
using Welic.Dominio.Patterns.Pattern.Ef6;
namespace Welic.Dominio.Models.Marketplaces.Entityes
{
public partial class MessageParticipant : Entity
{
public int ID { get; set; }
public int MessageThreadID { get; set; }
public string UserID { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual MessageThread MessageThread { get; set; }
}
}
|
using System;
using System.Linq;
namespace _05_seminar
{
class Program
{
static void Delete(ref int[] dataArray)
{
int[] newArray = new int[dataArray.Length - (Array.FindIndex(dataArray, i => i % 5 == 0) + 1)];
for (int i = newArray.Length - 1, j = 1; i >= 0; i--, j++)
{
newArray[i] = dataArray[dataArray.Length - j];
}
dataArray = newArray;
}
static void NewElement(ref int[] dataArray, int newElement)
{
int[] newArray = new int[dataArray.Length + 1];
for (int i = 0; i < dataArray.Length; i++)
{
newArray[i] = dataArray[i];
}
newArray[newArray.Length - 1] = newElement;
dataArray = newArray;
}
static void Main(string[] args)
{
string check;
int[] dataArray = { };
do
{
check = Console.ReadLine();
if (!int.TryParse(check, out int newElement) && check != "!")
{
Console.WriteLine("Incorrect input");
return;
}
NewElement(ref dataArray, newElement);
} while (check != "!");
int result = 0;
while (dataArray.Length != 0)
{
result += Array.Find(dataArray, i => i % 5 == 0);
Delete(ref dataArray);
}
Console.WriteLine(result);
}
}
}
|
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 VJBatangas.LomiHouse.Business;
using VJBatangas.LomiHouse.Entity;
using VJBatangas.LomiHouse.Common;
namespace VJBatangas.LomiHouse.Administration
{
public partial class frmAddEditBranch : Form
{
public InventoryItem item = new InventoryItem();
public Boolean isEdit;
public frmAddEditBranch()
{
InitializeComponent();
this.ControlBox = false;
}
private void frmAddEditBranch_Load(object sender, EventArgs e)
{
//if (isEdit)
//{
// //Edit Mode
// this.Text = VJConstants.MESSAGEBOX_TITLE + "Edit Inventory Item";
// //LoadInventoryItem(this.item.ItemId);
//}
//else
//{
// //Add Mode
// this.Text = VJConstants.MESSAGEBOX_TITLE + "Add Inventory Item";
//}
}
private Boolean ValidateForm()
{
Boolean isvalid = true;
if (String.IsNullOrEmpty(txtBranchName.Text.Trim()))
{
MessageBox.Show(VJConstants.REQUIRED_BRANCH_NAME, VJConstants.MESSAGEBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
isvalid = false;
}
else if (String.IsNullOrEmpty(txtStreet.Text.Trim()))
{
MessageBox.Show(VJConstants.REQUIRED_STREET, VJConstants.MESSAGEBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
isvalid = false;
}
else if (cmbTown.SelectedIndex == 0)
{
MessageBox.Show(VJConstants.REQUIRED_TOWN, VJConstants.MESSAGEBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
isvalid = false;
}
else if (cmbProvince.SelectedIndex == 0)
{
MessageBox.Show(VJConstants.REQUIRED_PROVINCE, VJConstants.MESSAGEBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
isvalid = false;
}
return isvalid;
}
}
}
|
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;
namespace Kingdee.CAPP.UI.ProcessDataManagement
{
/// <summary>
/// 类型说明:焊接符号选择界面
/// 作 者:jason.tang
/// 完成时间:2013-03-07
/// </summary>
public partial class WeldingSymbolChooseFrm : Form
{
#region 变量和属性声明
/// <summary>
/// 焊接符号
/// </summary>
private Image weldingimage;
public Image WeldingImage
{
get
{
return weldingimage;
}
}
#endregion
public WeldingSymbolChooseFrm()
{
InitializeComponent();
}
private void WeldingSymbolChooseFrm_Load(object sender, EventArgs e)
{
this.Width = 92;
this.Height = 520;
}
private void WeldingSymbolChooseFrm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
private void SymbolButton_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
weldingimage = button.Image;
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
private void Form_MouseDown(object sender, MouseEventArgs e)
{
//调用移动无窗体控件函数
Kingdee.CAPP.Common.CommonHelper.MoveNoneBorderForm(this);
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClose_MouseHover(object sender, EventArgs e)
{
btnClose.BackgroundImage = Kingdee.CAPP.UI.Properties.Resources.close_hover;
}
private void btnClose_MouseLeave(object sender, EventArgs e)
{
btnClose.BackgroundImage = Kingdee.CAPP.UI.Properties.Resources.close_d;
}
}
}
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Text;
namespace TeamCss__Registration.Utilities
{
public class Wait
{
public IWebElement WaitForElement(IWebDriver driver, IWebElement element)
{
DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver);
fluentWait.Timeout = TimeSpan.FromSeconds(40);
fluentWait.PollingInterval = TimeSpan.FromMilliseconds(500);
fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
if (fluentWait.Until(XPathLookupException => element.Displayed))
return element;
else
return null;
}
}
}
|
namespace SGCFT.Dados.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class _01_Treinamento_Modulo : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Modulo",
c => new
{
Id = c.Int(nullable: false, identity: true),
IdTreinamento = c.Int(nullable: false),
Titulo = c.String(maxLength: 200, unicode: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Treinamento", t => t.IdTreinamento, cascadeDelete: true)
.Index(t => t.IdTreinamento);
CreateTable(
"dbo.Treinamento",
c => new
{
Id = c.Int(nullable: false, identity: true),
Tema = c.String(maxLength: 200, unicode: false),
IdAutor = c.Int(nullable: false),
TipoTreinamento = c.Int(nullable: false),
Senha = c.String(maxLength: 500, unicode: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Usuario", t => t.IdAutor, cascadeDelete: true)
.Index(t => t.IdAutor);
}
public override void Down()
{
DropForeignKey("dbo.Modulo", "IdTreinamento", "dbo.Treinamento");
DropForeignKey("dbo.Treinamento", "IdAutor", "dbo.Usuario");
DropIndex("dbo.Treinamento", new[] { "IdAutor" });
DropIndex("dbo.Modulo", new[] { "IdTreinamento" });
DropTable("dbo.Treinamento");
DropTable("dbo.Modulo");
}
}
}
|
using System.Linq;
using System.Web.Mvc;
using Centroid.Models;
namespace Centroid.Controllers
{
public class AboutController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Abouts
public ActionResult Index()
{
return View(db.Abouts.FirstOrDefault());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GDS.Entity;
namespace GDS.WebApi.Models
{
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ChatBot.Models
{
public class Professors
{
public int id { get; set; }
[Display(Name ="First Name")]
public string fname { get; set; }
[Display(Name = "Last Name")]
public string lname { get; set; }
[Display(Name = "Email Id")]
public string email { get; set; }
[Display(Name = "Phone No")]
public string phone { get; set; }
[Display(Name = "Office Hours")]
public string officeHours { get; set; }
[Display(Name = "Office Location")]
public string location { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp9.Domain
{
public class Employee
{
public Guid? EmployeeID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Title { get; set; }
public string TitleOfCourtesy { get; set; }
public DateTime BirthDate { get; set; }
public DateTime? HireDate { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string HomePhone { get; set; }
public string Extension { get; set; }
public string Photo { get; set; }
public string Notes { get; set; }
public string PhotoPath { get; set; }
public byte[] RowVersion { get; set; }
public Guid? ReportsTo { get; set; }
public virtual Employee ReportsToEmployee { get; set; }
public virtual ICollection<Employee> Slaves { get; set; }
public virtual ICollection<Order> Orders { get; set; }
public virtual ICollection<Territory> Territories { get; set; }
public Employee()
{
Slaves = new List<Employee>();
Orders = new List<Order>();
Territories = new List<Territory>();
}
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
HasKey(p => p.EmployeeID);
Property(p => p.EmployeeID).
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.LastName).HasMaxLength(20).IsRequired();
Property(p => p.FirstName).HasMaxLength(20).IsRequired();
Property(p => p.Title).HasMaxLength(20).IsRequired();
Property(p => p.TitleOfCourtesy).HasMaxLength(20).IsRequired();
Property(p => p.BirthDate).IsRequired();
Property(p => p.HireDate).IsOptional();
Property(p => p.Address).HasMaxLength(20).IsRequired();
Property(p => p.City).HasMaxLength(20).IsRequired();
Property(p => p.Region).HasMaxLength(20).IsRequired();
Property(p => p.PostalCode).HasMaxLength(20).IsRequired();
Property(p => p.Country).HasMaxLength(20).IsRequired();
Property(p => p.HomePhone).HasMaxLength(20).IsRequired();
Property(p => p.Extension).HasMaxLength(20).IsRequired();
Property(p => p.Photo).HasMaxLength(20).IsRequired();
Property(p => p.Notes).HasMaxLength(20).IsRequired();
Property(p => p.PhotoPath).HasMaxLength(20).IsRequired();
HasMany(p => p.Orders)
.WithOptional(p => p.Employee)
.HasForeignKey(p => p.EmployeeID);
HasMany(p => p.Slaves)
.WithOptional(p => p.ReportsToEmployee)
.HasForeignKey(p => p.ReportsTo);
Property(p => p.RowVersion).IsRowVersion();
HasMany(p => p.Territories).WithMany(p => p.Employeis).Map(m =>
{
m.MapLeftKey("EmployeeID");
m.MapRightKey("TerritoryID");
m.ToTable("EmployeeTerritoryTable");
});
}
}
} |
namespace Assets.Scripts.Models.Clothes
{
public class Clothes : BaseObject
{
public Clothes()
{
IsStackable = false;
Description = "clothe_descr";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Menu_ChangePassword : MonoBehaviour
{
private Database_Utils databaseUtils = null;
public GameObject passwordInputField;
public GameObject rePasswordInputField;
public GameObject dialogText;
public GameObject playerNameTextTMP;
private string m_password = "";
private string m_rePassword = "";
private string m_dialogText = "";
private string playerName = "";
// Start is called before the first frame update
void Start()
{
if (databaseUtils == null)
{
databaseUtils = new Database_Utils();
}
}
// Update is called once per frame
void Update()
{
}
void OnEnable()
{
dialogText.SetActive(false);
UpdatePlayerName();
}
void UpdatePlayerName()
{
// Update player name
playerName = PlayerPrefs.GetString("playerName");
playerNameTextTMP.GetComponent<TMP_Text>().text = "Player: " + playerName;
}
void getCredentialsFromForm()
{
m_password = passwordInputField.GetComponent<InputField>().text;
m_rePassword = rePasswordInputField.GetComponent<InputField>().text;
}
void clearCredentialsForm()
{
m_password = "";
m_rePassword = "";
}
void clearDialogText()
{
dialogText.GetComponent<Text>().text = "";
}
void updateCredentialsInForm()
{
passwordInputField.GetComponent<InputField>().text = m_password;
rePasswordInputField.GetComponent<InputField>().text = m_rePassword;
}
void updateDialogText()
{
dialogText.GetComponent<Text>().text = m_dialogText;
}
public void backButtonClicked()
{
clearDialogText();
updateDialogText();
}
public void changePasswordButtonClicked()
{
dialogText.SetActive(false);
getCredentialsFromForm();
StartCoroutine(resetPassword(PlayerPrefs.GetString("playerName"), m_password, m_rePassword));
}
private IEnumerator resetPassword(string login, string password, string repeatedPassword)
{
string playerName = PlayerPrefs.GetString("playerName");
if (!playerName.Equals("Guest"))
{
CoroutineWithData cd = new CoroutineWithData(this, databaseUtils.ChangePassword(login, password, repeatedPassword));
yield return cd.coroutine;
string receivedMessage = (string)cd.result;
if ("0".Equals(receivedMessage))
{
m_dialogText = "Password has been changed";
clearCredentialsForm();
updateCredentialsInForm();
}
else
{
m_dialogText = receivedMessage;
}
updateDialogText();
dialogText.SetActive(true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HPYL.Model
{
public class Members
{
/// <summary>
///
/// </summary>
#region Model
/// auto_increment
/// </summary>
public long Id { get; set; }
/// <summary>
///
/// </summary>
public string UserName { get; set; }
/// <summary>
///
/// </summary>
public string Password { get; set; }
/// <summary>
///
/// </summary>
public string PasswordSalt { get; set; }
/// <summary>
///
/// </summary>
public string Nick { get; set; }
/// <summary>
///
/// </summary>
public int Sex { get; set; }
/// <summary>
///
/// </summary>
public string Email { get; set; }
/// <summary>
///
/// </summary>
public DateTime CreateDate { get; set; }
/// <summary>
///
/// </summary>
public int TopRegionId { get; set; }
/// <summary>
///
/// </summary>
public int RegionId { get; set; }
/// <summary>
///
/// </summary>
public string RealName { get; set; }
/// <summary>
///
/// </summary>
public string CellPhone { get; set; }
/// <summary>
///
/// </summary>
public string QQ { get; set; }
/// <summary>
///
/// </summary>
public string Address { get; set; }
/// <summary>
///
/// </summary>
public int Disabled { get; set; }
/// <summary>
///
/// </summary>
public DateTime LastLoginDate { get; set; }
/// <summary>
///
/// </summary>
public int OrderNumber { get; set; }
/// <summary>
///
/// </summary>
public decimal TotalAmount { get; set; }
/// <summary>
///
/// </summary>
public decimal Expenditure { get; set; }
/// <summary>
///
/// </summary>
public int Points { get; set; }
/// <summary>
///
/// </summary>
public string Photo { get; set; }
/// <summary>
///
/// </summary>
public long ParentSellerId { get; set; }
/// <summary>
///
/// </summary>
public string Remark { get; set; }
/// <summary>
///
/// </summary>
public string PayPwd { get; set; }
/// <summary>
///
/// </summary>
public string PayPwdSalt { get; set; }
/// <summary>
///
/// </summary>
public long InviteUserId { get; set; }
/// <summary>
///
/// </summary>
public long ShareUserId { get; set; }
/// <summary>
///
/// </summary>
public DateTime BirthDay { get; set; }
/// <summary>
///
/// </summary>
public string Occupation { get; set; }
/// <summary>
///
/// </summary>
public decimal NetAmount { get; set; }
/// <summary>
///
/// </summary>
public DateTime LastConsumptionTime { get; set; }
#endregion Model
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Water : MonoBehaviour {
public GameControl gamectrl;
public GameObject gameOver;
void Start () {
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
gameOver.SetActive(true);
gamectrl.savePoints();
}
else { }
}
}
|
using System;
using System.Net.Mail;
using System.Text.RegularExpressions;
using Boxofon.Web.Mailgun;
namespace Boxofon.Web.Helpers
{
public static class MailgunRequestExtensions
{
public static string BoxofonNumber(this MailgunRequest request)
{
var from = new MailAddress(request.From);
if (from.User.IsPossiblyValidPhoneNumber())
{
return from.User.ToE164();
}
return null;
}
}
} |
using BDTest.Attributes;
using NUnit.Framework;
namespace BDTest.Example;
[Story(AsA = "BDTest Developer",
IWant = "to show how different states show in a test report",
SoThat = "users can see what a report would look like")]
public class DifferentReportScenarioTests : MyTestBase
{
[SetUp]
public void Setup()
{
WriteStartupOutput("This is some startup custom text");
}
[TearDown]
public void TearDown()
{
WriteTearDownOutput("This is some custom teardown text");
}
[Test]
[ScenarioText("An ignored test")]
public async Task TestIgnored()
{
await When(() => Ignore())
.Then(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("An inconclusive given test")]
public async Task TestGivenInconclusive()
{
await Given(() => Inconclusive())
.When(() => Pass())
.Then(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("An inconclusive when test")]
public async Task TestWhenInconclusive()
{
await When(() => Inconclusive())
.Then(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("An inconclusive then test")]
public async Task TestThenInconclusive()
{
await When(() => Pass())
.Then(() => Inconclusive())
.BDTestAsync();
}
[Test]
[ScenarioText("The given step failed")]
public async Task GivenFailed()
{
await Given(() => Fail())
.When(() => Pass())
.Then(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("The and given step failed")]
public async Task AndGivenFailed()
{
await Given(() => Pass())
.And(() => Fail())
.When(() => Pass())
.Then(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("The when step failed")]
public async Task WhenFailed()
{
await When(() => Fail())
.Then(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("The then step failed")]
public async Task ThenFailed()
{
await When(() => Pass())
.Then(() => Fail())
.BDTestAsync();
}
[Test]
[ScenarioText("The and then step failed")]
public async Task AndThenFailed()
{
await When(() => Pass())
.Then(() => Pass())
.And(() => Fail())
.BDTestAsync();
}
[Test]
[ScenarioText("A test that passes")]
public async Task EverythingPasses()
{
await Given(() => Pass())
.And(() => Pass())
.When(() => Pass())
.Then(() => Pass())
.And(() => Pass())
.BDTestAsync();
}
[Test]
[ScenarioText("A custom link to attach to the report server")]
public async Task CustomHtml()
{
await Given(() => Pass())
.And(() => Pass())
.When(() => Pass())
.Then(() => Pass())
.And(() => Pass())
.BDTestAsync();
ScenarioHtmlWriter.Link("BDTest Wiki!", "https://github.com/thomhurst/BDTest");
}
[StepText("the step passes")]
private void Pass()
{
Assert.That(1, Is.EqualTo(1));
}
[StepText("I fail the step")]
private void Fail()
{
throw new ArithmeticException();
}
private void Ignore()
{
Assert.Ignore();
}
private void Inconclusive()
{
Assert.Inconclusive();
}
} |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FIVIL.Litentity
{
public class LitentityContext : DbContext
{
public LitentityContext(DbContextOptions options)
: base(options)
{
}
public DbSet<LitentityUsers> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LitentityUsers>(e =>
e.HasIndex(p => p.UserName).IsUnique());
modelBuilder.Entity<LitentityUsers>(e =>
e.HasIndex(p => p.EmailAddress).IsUnique());
modelBuilder.Entity<LitentityUsers>(e =>
e.HasIndex(p => p.PhoneNumber).IsUnique());
base.OnModelCreating(modelBuilder);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Points : MonoBehaviour
{
public int currentPoints;
public int totalPoints;
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using HotelManagerWithNET_F.Models;
namespace HotelManagerWithNET_F.Controllers
{
public class DichVuRiengsController : ApiController
{
private HotelEntities db = new HotelEntities();
// GET: api/DichVuRiengs
public IQueryable<DichVuRieng> GetDichVuRieng()
{
return db.DichVuRieng;
}
// GET: api/DichVuRiengs/5
[ResponseType(typeof(DichVuRieng))]
public IHttpActionResult GetDichVuRieng(int id)
{
DichVuRieng dichVuRieng = db.DichVuRieng.Find(id);
if (dichVuRieng == null)
{
return NotFound();
}
return Ok(dichVuRieng);
}
// PUT: api/DichVuRiengs/5
[ResponseType(typeof(void))]
public IHttpActionResult PutDichVuRieng(int id, DichVuRieng dichVuRieng)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != dichVuRieng.MaDichVu)
{
return BadRequest();
}
db.Entry(dichVuRieng).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!DichVuRiengExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/DichVuRiengs
[ResponseType(typeof(DichVuRieng))]
public IHttpActionResult PostDichVuRieng(DichVuRieng dichVuRieng)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.DichVuRieng.Add(dichVuRieng);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = dichVuRieng.MaDichVu }, dichVuRieng);
}
// DELETE: api/DichVuRiengs/5
[ResponseType(typeof(DichVuRieng))]
public IHttpActionResult DeleteDichVuRieng(int id)
{
DichVuRieng dichVuRieng = db.DichVuRieng.Find(id);
if (dichVuRieng == null)
{
return NotFound();
}
db.DichVuRieng.Remove(dichVuRieng);
db.SaveChanges();
return Ok(dichVuRieng);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool DichVuRiengExists(int id)
{
return db.DichVuRieng.Count(e => e.MaDichVu == id) > 0;
}
}
} |
using Compent.Shared.Extensions.Bcl;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Uintra.Infrastructure.ApplicationSettings.Models;
using static System.Configuration.ConfigurationManager;
namespace Uintra.Infrastructure.ApplicationSettings
{
public class ApplicationSettings : ConfigurationSection, IApplicationSettings
{
private GoogleOAuth _googleOAuth;
private const string DefaultAvatarPathKey = "DefaultAvatarPath";
private const string MonthlyEmailJobDayKey = "MonthlyEmailJobDay";
private const string VideoFileTypesKey = "VideoFileTypes";
private const string QaKeyKey = "QaKey";
private const string MemberApiAuthenticationEmailKey = "MemberApiAuthentificationEmail";
private const string GoogleClientIdKey = "Google.OAuth.ClientId";
private const string GoogleDomainKey = "Google.OAuth.Domain";
private const string GoogleEnabledKey = "Google.OAuth.Enabled";
private const string UmbracoUseSSLKey = "umbracoUseSSL";
private const string AdminSecretKey = "AdminControllerSecretKey";
private const string UintraDocumentationLinkTemplateKey = "UintraDocumentationLinkTemplate";
public const string MailNotificationNoReplyEmailKey = "Notifications.Mail.NoReplyEmail";
public const string MailNotificationNoReplyNameKey = "Notifications.Mail.NoReplyName";
public const string UintraSuperUsersKey = "UintraSuperUsers";
public const string DaytimeSavingOffsetKey = "DaytimeSavingOffset";
public string MailNotificationNoReplyEmail => AppSettings[MailNotificationNoReplyEmailKey];
public string MailNotificationNoReplyName => AppSettings[MailNotificationNoReplyNameKey];
public string AdminControllerSecretKey => AppSettings["AdminSecretKey"];
public IEnumerable<string> VideoFileTypes => AppSettings[VideoFileTypesKey]
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(el => el.Trim());
public bool DaytimeSavingOffset => bool.Parse(AppSettings[DaytimeSavingOffsetKey]);
public Guid QaKey => Guid.Parse(AppSettings[QaKeyKey]);
public int MonthlyEmailJobDay => Convert.ToInt32(AppSettings[MonthlyEmailJobDayKey]);
public string MemberApiAuthenticationEmail => AppSettings[MemberApiAuthenticationEmailKey];
public string UintraDocumentationLinkTemplate => AppSettings[UintraDocumentationLinkTemplateKey];
public GoogleOAuth GoogleOAuth
{
get
{
if (_googleOAuth != null)
return _googleOAuth;
_googleOAuth = new GoogleOAuth
{
ClientId = string.Empty
};
if (!bool.TryParse(AppSettings[GoogleEnabledKey], out var enabled) || !enabled)
return _googleOAuth;
var clientId = AppSettings[GoogleClientIdKey];
if (!clientId.HasValue())
throw new ArgumentNullException("Google client id");
_googleOAuth.ClientId = clientId;
_googleOAuth.Domain = AppSettings[GoogleDomainKey];
_googleOAuth.Enabled = true;
return _googleOAuth;
}
}
public bool UmbracoUseSsl => bool.TryParse(AppSettings[UmbracoUseSSLKey], out var enabled) && enabled;
public IEnumerable<string> UintraSuperUsers
{
get
{
var value = AppSettings[UintraSuperUsersKey];
return string.IsNullOrEmpty(value) ? Enumerable.Empty<string>() : value.Split(',');
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MenuControlls : MonoBehaviour
{
public GameObject aboutPage;
public GameObject levelSelect;
public GameObject settings;
public Text musicText;
public Text colorText;
public AudioSource audio;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void NewGame()
{
PlayerPrefs.SetInt("NewGame", 1);
SceneManager.LoadSceneAsync("SampleScene");
}
public void QuitGame()
{
Application.Quit();
}
public void EnableAboutPage()
{
aboutPage.SetActive(true);
}
public void CloseAboutPage()
{
aboutPage.SetActive(false);
}
public void EnableLevelSelect()
{
levelSelect.SetActive(true);
}
public void CloseLevelSelect()
{
levelSelect.SetActive(false);
}
public void EnableSettings()
{
settings.SetActive(true);
}
public void CloseSettings()
{
settings.SetActive(false);
}
public void LoadLevel1()
{
SceneManager.LoadSceneAsync("SampleScene");
}
public void LoadLevel2()
{
SceneManager.LoadSceneAsync("BossLevel");
}
public void ToggleMusic()
{
int musicToggle = 1;
if (musicText.text == "ON")
{
musicToggle = 0;
musicText.text = "OFF";
audio.Stop();
}
else
{
musicToggle = 1;
musicText.text = "ON";
audio.Play();
}
PlayerPrefs.SetInt("MusicToggle", musicToggle);
Debug.Log("Music set to " + musicToggle.ToString());
}
public void ToggleColor()
{
int colorToggle = 1;
if (colorText.text == "ON")
{
colorToggle = 0;
colorText.text = "OFF";
}
else
{
colorToggle = 1;
colorText.text = "ON";
}
PlayerPrefs.SetInt("ColorToggle", colorToggle);
Debug.Log("Color set to " + colorToggle.ToString());
}
}
|
using DAL;
using MVVM_Core;
using MVVM_Core.Validation;
using System;
using System.Linq;
using System.Windows.Controls;
using BL;
namespace Main.ViewModels
{
public class UserRegViewModel : BasePageViewModel
{
private readonly UserRegisterService registerService;
private readonly EventBus eventBus;
private readonly Validator validator;
public string Phone { get; set; }
public PasswordBox PasswordBox { get; set; } = new PasswordBox();
public PasswordBox PasswordBoxConf { get; set; } = new PasswordBox();
public UserRegViewModel(PageService pageservice,
UserRegisterService registerService,
EventBus eventBus,
Validator validator)
: base(pageservice)
{
this.registerService = registerService;
this.eventBus = eventBus;
this.validator = validator;
Init();
}
private void Init()
{
validator.ForProperty(() => Phone, "Номер телефона").
NotEmpty().
Predicate(s => s.All(char.IsDigit), "Должны быть только цифры");
validator.ForProperty(() => PasswordBox.Password, "Пароль").
LengthMoreThan(1).
Predicate(s => s.Any(char.IsDigit) && s.Any(char.IsLetter) , "Пароль должен содержать цифры и буквы");
validator.ForProperty(() => PasswordBoxConf.Password, "Потверждение").
Predicate(s => s == PasswordBox.Password , "Пароли должны совпадать");
}
public string Msg { get; set; }
public bool MsgVis { get; set; }
public bool IsSplashVisible { get; set; }
protected override async void Next(object param)
{
MsgVis = false;
if (validator.IsCorrect)
{
IsSplashVisible = true;
registerService.SetupPass(Phone, PasswordBox.Password);
int id = await registerService.RegisterAsync();
IsSplashVisible = false;
if (id > -1)
{
registerService.Clear();
pageservice.Next();
}
else
{
MsgVis = true;
Msg = registerService.ErrorMessage;
}
}
else
{
MsgVis = true;
Msg = validator.ErrorMessage;
}
}
public override int PoolIndex => Rules.Pages.SecPool;
}
} |
using System.Collections.Generic;
using System.Reflection;
namespace CompiledValidators
{
/// <summary>
/// Provides validators for types and their members.
/// </summary>
public interface IValidatorProvider
{
/// <summary>
/// Gets the validators for a type or a member.
/// </summary>
/// <param name="member">The construct to get validators for.</param>
/// <returns>A list of validators.</returns>
/// <remarks>
/// The list of possible types passed to <paramref name="member"/> are:
/// <list type="disc">
/// <item><see cref="System.Type"/></item>
/// <itm><see cref="FieldInfo"/></itm>
/// <item><see cref="PropertyInfo"/></item>
/// </list>
/// </remarks>
IEnumerable<ValidatorInfo> GetValidators(MemberInfo member);
}
}
|
using System;
namespace Screenmedia.IFTTT.JazzHands
{
public class JazzHands
{
public JazzHands ()
{
}
}
}
|
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assig_1.GUI
{
class GUIText
{
/// <summary>
/// The position of the text on the screen. Top left is 0,0
/// </summary>
public Vector2 Position { get; set; }
/// <summary>
/// The scale of the text
/// </summary>
public float Scale { get; set; }
/// <summary>
/// The color of the text
/// </summary>
public Color Color { get; set; }
/// <summary>
/// The text message
/// </summary>
public string Text;
/// <summary>
/// Constructor
/// </summary>
/// <param name="text"></param>
public GUIText(string text)
{
Text = text;
Position = new Vector2(0, 0);
Scale = 1.0f;
Color = Color.Black;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="text">The text message</param>
/// <param name="x">The X position on the screen</param>
/// <param name="y">The Y position on the screen</param>
/// <param name="c">The text color</param>
public GUIText(string text, float x, float y, Color c)
{
Text = text;
Position = new Vector2(x, y);
Scale = 1.0f;
Color = c;
}
}
}
|
using Microsoft.AspNetCore.Identity;
using Voluntariat.Models;
namespace Voluntariat.Data
{
public static class ApplicationDbInitializer
{
public static void SeedUsers(UserManager<ApplicationUser> userManager)
{
var username = "a@a.a";
var password = "Test.123";
if (userManager.FindByEmailAsync(username).Result == null)
{
ApplicationUser user = new ApplicationUser
{
UserName = username,
Email = username,
EmailConfirmed = true
};
IdentityResult result = userManager.CreateAsync(user, password).Result;
userManager.AddToRoleAsync(user, Framework.Identity.CustomIdentityRole.Admin).Wait();
}
}
}
} |
using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using OrchardCore.ContentManagement;
namespace DFC.ServiceTaxonomy.UnpublishLater.ViewModels
{
public class UnpublishLaterPartViewModel
{
[BindNever]
public ContentItem? ContentItem { get; set; }
public DateTime? ScheduledUnpublishUtc { get; set; }
public DateTime? ScheduledUnpublishLocalDateTime { get; set; }
}
}
|
using System;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using ODL.ApplicationServices.DTOModel.Load;
using ODL.DataAccess;
using ODL.DataAccess.Repositories;
using ODL.DomainModel;
using ODL.DomainModel.Person;
namespace ODL.ApplicationServices.Test.Mock
{
[TestFixture]
public class PersonServiceTests
{
private PersonInputDTO person;
private Mock<IPersonRepository> personRepositoryMock;
private Mock<IContext> dbContextMock;
private Mock<ILogger<PersonService>> loggerMock;
private PersonService service;
[Test]
public void SparaPerson_WhenNew_ThenAdded()
{
service.SparaPerson(person);
personRepositoryMock.Verify(m => m.Add(It.IsAny<Person>()));
}
//[Test]
//public void SparaPerson_WhenExisting_ThenUpdated()
//{
// personRepositoryMock.Setup(m => m.GetByPersonnummer(It.IsAny<string>())).Returns(new Person {Id = 1}); // Mocka en existerande person, så vi får Update istället för Add.
// service.SparaPerson(person);
// personRepositoryMock.Verify(m => m.Update());
//}
[Test]
public void SparaPerson_MissingFirstName_ValidationError()
{
person.Fornamn = null;
Expect<BusinessLogicException>(() => service.SparaPerson(person),
$"Valideringsfel inträffade vid validering av Person med Id: {person.Personnummer}.");
}
[Test]
public void SparaPerson_ValidationError_MissingPersNr()
{
person.Personnummer = null;
Expect<BusinessLogicException>(() => service.SparaPerson(person),
$"Valideringsfel inträffade vid validering av Person med Id: {person.Personnummer}.");
}
[Test]
public void SparaAvtal_MissingKstnr_Fail()
{
//var avtal = new AvtalInputDTO()
//{
// Kostnadsstallen = new List<OrganisationAvtalInputDTO>() { new OrganisationAvtalInputDTO(){KostnadsstalleNr = 12345} },
// AnstalldPersonnummer = "198002254543",
// SkapadAv = "MEH",
// SkapadDatum = "2005-01-02 12:00",
// UppdateradAv = "MEH",
// UppdateradDatum = "2017-02-01 12:00"
//};
//// Verifiera service.SparaAvtal
}
[SetUp]
public void Initiera()
{
person = new PersonInputDTO
{
SystemId = "435345",
Fornamn = "Anna",
Efternamn = "Nilsson",
Personnummer = "198002254543",
SkapadAv = "MEH",
SkapadDatum = "2005-01-02 12:00",
UppdateradAv = "MEH",
UppdateradDatum = "2017-02-01 12:00"
};
personRepositoryMock = new Mock<IPersonRepository>();
dbContextMock = new Mock<IContext>();
loggerMock = new Mock<ILogger<PersonService>>();
service = new PersonService(personRepositoryMock.Object, dbContextMock.Object, loggerMock.Object);
}
/// <summary>
/// En liten hjälpmetod för att hjälpa till att verifiera fel och felmeddelanden.
/// </summary>
public static void Expect<TException>(TestDelegate action, string message = null) where TException : Exception
{
var exception = Assert.Throws<TException>(action);
if (message != null)
Assert.That(exception.Message, Is.EqualTo(message));
}
}
}
|
using UnityEngine;
public class Flamethrower : MonoBehaviour
{
public float rotateSpeed;
private bool clockwise;
public int flameTimeOff;
public int flameTimeOn;
private int initialFlameTime;
ParticleSystem system;
private void Start()
{
initialFlameTime = flameTimeOn;
system = gameObject.GetComponent<ParticleSystem>();
}
/*private void OnTriggerStay(Collider col)
{
if (col.gameObject.CompareTag("Player") &&
Input.GetButtonDown("Submit"))
{
Debug.Log("Rotating flamethrower.");
}
}*/
private void Update()
{
if (flameTimeOn > 0)
{
flameTimeOn --;
if (flameTimeOn <= 0)
{
system.Stop();
flameTimeOff = initialFlameTime;
}
}
if (flameTimeOff > 0)
{
flameTimeOff--;
if (flameTimeOff <=0)
{
system.Play();
flameTimeOn = initialFlameTime;
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Nailhang.Display.Models
{
public class InterfacesModel
{
public string Contains { get; set; }
public InterfaceMD5KV[] Interfaces { get; set; }
}
} |
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem276 : ProblemBase {
private PrimeSieve _primes;
public override string ProblemName {
get { return "276: Primitive Triangles"; }
}
private ulong _total;
public override string GetAnswer() {
int maxP = 100;
//int maxP = 10000000;
BuildPrimeFactors((ulong)maxP);
//return BruteForce(100).ToString();
return "";
}
private int _count;
private void IncludeExclude(bool add, int startPrime, IEnumerable<int> primes, int prod, int start, int end) {
for (int index = startPrime; index < primes.Count(); index++) {
var prime = primes.ElementAt(index);
var nextProd = prod * prime;
if (nextProd <= end) {
if (add) {
_count += (end - start + 1) / nextProd;
} else {
_count -= (end - start + 1) / nextProd;
}
IncludeExclude(!add, index + 1, primes, nextProd, start, end);
}
}
}
private Dictionary<int, List<int>> _factors = new Dictionary<int, List<int>>();
private void BuildPrimeFactors(ulong maxP) {
_primes = new PrimeSieve(maxP / 3);
foreach (var prime in _primes.Enumerate) {
for (ulong num = prime; num <= maxP / 3; num += prime) {
if (!_factors.ContainsKey((int)num)) {
_factors.Add((int)num, new List<int>());
}
_factors[(int)num].Add((int)prime);
}
}
}
private List<string> _answers = new List<string>();
private ulong BruteForce(ulong maxP) {
ulong count = 0;
for (ulong a = 1; a <= maxP; a++) {
for (ulong b = a; b <= maxP; b++) {
var gcd = GCD.GetGCD(a, b);
for (ulong c = b; c <= maxP; c++) {
if (a + b + c <= maxP && (a + b) > c && GCD.GetGCD(gcd, c) == 1) {
count++;
_answers.Add(a + "," + b + "," + c);
}
}
}
}
return count;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace XH.APIs.WebAPI.Models.Tenants
{
[DataContract]
public class CreateOrUpdateTenantRequest
{
[DataMember]
[Required]
public string TenantName { get; set; }
[DataMember]
public bool IsActive { get; set; }
[DataMember]
public string Host { get; set; }
[DataMember]
public string Name { get; set; }
}
} |
using System.Threading;
using System.Threading.Tasks;
using Ardalis.ApiEndpoints;
using AutoMapper;
using BlazorShared.Models.Client;
using ClinicManagement.Core.Aggregates;
using Microsoft.AspNetCore.Mvc;
using PluralsightDdd.SharedKernel.Interfaces;
using Swashbuckle.AspNetCore.Annotations;
namespace ClinicManagement.Api.ClientEndpoints
{
public class GetById : BaseAsyncEndpoint
.WithRequest<GetByIdClientRequest>
.WithResponse<GetByIdClientResponse>
{
private readonly IRepository _repository;
private readonly IMapper _mapper;
public GetById(IRepository repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
[HttpGet("api/clients/{ClientId}")]
[SwaggerOperation(
Summary = "Get a Client by Id",
Description = "Gets a Client by Id",
OperationId = "clients.GetById",
Tags = new[] { "ClientEndpoints" })
]
public override async Task<ActionResult<GetByIdClientResponse>> HandleAsync([FromRoute] GetByIdClientRequest request, CancellationToken cancellationToken)
{
var response = new GetByIdClientResponse(request.CorrelationId());
var client = await _repository.GetByIdAsync<Client, int>(request.ClientId);
if (client is null) return NotFound();
response.Client = _mapper.Map<ClientDto>(client);
return Ok(response);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TestBrokenApp.Services
{
public interface IDataConnection
{
SQLite.SQLiteConnection DataConnection();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class aspx_MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] != null && Convert.ToString(Session["username"]) != "")
{
this.HyperLink1.Text = Convert.ToString(Session["username"]);
this.HyperLink1.NavigateUrl = "~/aspx/ChangeInf.aspx";
this.HyperLink2.Text = Convert.ToString("修改密码");
this.HyperLink2.NavigateUrl = "~/aspx/ChangePwd.aspx";
this.HyperLink3.Text = Convert.ToString("退出");
this.HyperLink3.NavigateUrl = "~/aspx/exit.aspx";
}
}
}
|
using UnityEngine;
using System.Collections;
using DG.Tweening;
using UnityEngine.SceneManagement;
public class SpringBroke : StateMachineBehaviour
{
private Vector3 normal_Rotation;
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Transform spring = animator.transform;
normal_Rotation = spring.eulerAngles;
RandonVelocity(spring);
}
void RandonVelocity(Transform spring)
{
if (spring.tag.Contains(MyTags.Right_Tag))
{
float x_A = Random.Range(1, 3);
float y_A = Random.Range(2, 5);
Vector3 target_A = Vector3.right * (-x_A) + Vector3.up * (y_A);
spring.DOBlendableMoveBy(target_A, 1f).SetEase(Ease.OutExpo);
spring.DOBlendableMoveBy(Vector3.up * (-30f), 1f).SetEase(Ease.InExpo);
spring.DOLocalRotate(new Vector3(0, 0, 90), 0.4f).SetLoops(-1, LoopType.Incremental).SetEase(Ease.Linear);
spring.DOPlay();
}
else
{
float x_B = Random.Range(1, 3);
float y_B = Random.Range(2, 5);
Vector3 target = Vector3.right * (x_B) + Vector3.up * (y_B);
spring.DOBlendableMoveBy(target, 1f).SetEase(Ease.OutExpo);
spring.DOBlendableMoveBy(Vector3.up * (-30f), 1f).SetEase(Ease.InExpo);
spring.DORotate(new Vector3(0, 0, 270), 0.4f).SetLoops(-1, LoopType.Incremental).SetEase(Ease.Linear);
spring.DOPlay();
}
if (SceneManager.GetActiveScene().name.Contains("EndlessMode"))
{
HumanManager.Nature.HumanManager_Script.StartCoroutine(Wait(spring));
}
}
IEnumerator Wait(Transform spring)
{
yield return new WaitForSeconds(1);
spring.DOKill();
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
//override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
//
//}
// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
// OnStateMove is called right after Animator.OnAnimatorMove(). Code that processes and affects root motion should be implemented here
//override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
//
//}
// OnStateIK is called right after Animator.OnAnimatorIK(). Code that sets up animation IK (inverse kinematics) should be implemented here.
//override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
//
//}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// Represents a piece of data - either a variable name or a literal
public class Data : NodeBase
{
public FunctionParameter descriptor;
public override void InitialiseNode()
{
base.InitialiseNode();
if (descriptor == null)
descriptor = new FunctionParameter();
transform.Find("Text").GetComponent<Text>().text = descriptor.IsReference ? descriptor.Name : descriptor.Value;
}
public override string Serialize()
{
return descriptor.IsReference ? descriptor.Name : descriptor.Value;
}
}
|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Reference Listener of type `Collision`. Inherits from `AtomEventReferenceListener<Collision, CollisionEvent, CollisionEventReference, CollisionUnityEvent>`.
/// </summary>
[EditorIcon("atom-icon-orange")]
[AddComponentMenu("Unity Atoms/Listeners/Collision Event Reference Listener")]
public sealed class CollisionEventReferenceListener : AtomEventReferenceListener<
Collision,
CollisionEvent,
CollisionEventReference,
CollisionUnityEvent>
{ }
}
|
namespace CourseVoiliers.Classes
{
public class Sponsor
{
}
} |
namespace TripDestination.Web.MVC.ViewModels.Shared
{
using TripDestination.Common.Infrastructure.Mapping;
using TripDestination.Data.Models;
public class PageViewModel : IMapFrom<Page>
{
public int Id { get; set; }
public string Heading { get; set; }
public string SubHeading { get; set; }
public string Slug { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace com.Sconit.Entity
{
public static class ISIConstants
{
#region ISI
public static readonly string CODE_PREFIX_ISI = "ISI";
public static readonly string CODE_PREFIX_PLAN = "PLN";
public static readonly string CODE_PREFIX_ISSUE = "ISS";
public static readonly string CODE_PREFIX_IMPROVE = "IMP";
public static readonly string CODE_PREFIX_CHANGE = "CHG";
public static readonly string CODE_PREFIX_PRIVACY = "PRY";
public static readonly string CODE_PREFIX_AUDIT = "ADT";
public static readonly string CODE_PREFIX_RESPONSE = "REP";
public static readonly string CODE_PREFIX_PROJECT = "PRJ";
public static readonly string CODE_PREFIX_PROJECT_ISSUE = "PIS";
/// <summary>
/// 工程更改
/// </summary>
public static readonly string CODE_PREFIX_ENGINEERING_CHANGE = "ENC";
public static readonly string CODE_PREFIX_ENGINEERING_WORKFLOW = "WFS";
public static readonly string CODE_MASTER_ISI_TYPE = "ISIType";
public static readonly string ISI_TASK_TYPE_GENERAL = "General";
public static readonly string ISI_TASK_TYPE_PLAN = "Plan";
public static readonly string ISI_TASK_TYPE_WORKFLOW = "WFS";
public static readonly string ISI_TASK_TYPE_ISSUE = "Issue";
public static readonly string ISI_TASK_TYPE_IMPROVE = "Improve";
public static readonly string ISI_TASK_TYPE_CHANGE = "Change";
public static readonly string ISI_TASK_TYPE_PRIVACY = "Privacy";
public static readonly string ISI_TASK_TYPE_RESPONSE = "Response";
public static readonly string ISI_TASK_TYPE_PROJECT = "Project";
public static readonly string ISI_TASK_TYPE_AUDIT = "Audit";
public static readonly string ISI_TASK_TYPE_PROJECT_ISSUE = "PrjIss";
/// <summary>
/// 工程更改
/// </summary>
public static readonly string ISI_TASK_TYPE_ENGINEERING_CHANGE = "Enc";
public static readonly IList<string> TaskTypeList = new List<string>() { ISIConstants.ISI_TASK_TYPE_PLAN, ISIConstants.ISI_TASK_TYPE_ISSUE, ISIConstants.ISI_TASK_TYPE_IMPROVE,
ISIConstants.ISI_TASK_TYPE_CHANGE,ISIConstants.ISI_TASK_TYPE_PRIVACY,ISIConstants.ISI_TASK_TYPE_RESPONSE,
ISIConstants.ISI_TASK_TYPE_PROJECT,ISIConstants.ISI_TASK_TYPE_AUDIT,ISIConstants.ISI_TASK_TYPE_PROJECT_ISSUE,
ISIConstants.ISI_TASK_TYPE_ENGINEERING_CHANGE,ISIConstants.ISI_TASK_TYPE_WORKFLOW};
public static readonly IDictionary<string, string> TaskTypeDic
= new Dictionary<string, string>() { { CODE_PREFIX_PLAN, ISI_TASK_TYPE_PLAN },
{ CODE_PREFIX_ISSUE, ISI_TASK_TYPE_ISSUE },
{ CODE_PREFIX_IMPROVE, ISI_TASK_TYPE_IMPROVE },
{ CODE_PREFIX_CHANGE, ISI_TASK_TYPE_CHANGE },
{ CODE_PREFIX_PRIVACY, ISI_TASK_TYPE_PRIVACY },
{ CODE_PREFIX_AUDIT, ISI_TASK_TYPE_AUDIT },
{ CODE_PREFIX_RESPONSE, ISI_TASK_TYPE_RESPONSE },
{ CODE_PREFIX_PROJECT, ISI_TASK_TYPE_PROJECT },
{ CODE_PREFIX_PROJECT_ISSUE, ISI_TASK_TYPE_PROJECT_ISSUE },
{ CODE_PREFIX_ENGINEERING_CHANGE, ISI_TASK_TYPE_ENGINEERING_CHANGE},
{ CODE_PREFIX_ENGINEERING_WORKFLOW,ISIConstants.ISI_TASK_TYPE_WORKFLOW}};
public static readonly string ISI_LEVEL_SEPRATOR = "|";
public static readonly string ISI_USER_SEPRATOR = ",";
public static readonly string ISI_USER_SEPRATOR_VIEW = ", ";
public static readonly string[] ISI_USERNAME_SEPRATOR = new string[] { ", ", "," };
public static readonly char[] ISI_SEPRATOR = new char[] { '|', ';', ';', ',', ',', ' ' };
public static readonly char[] ISI_FILE_SEPRATOR = new char[] { '*', '.', ' ', ';' };
public static readonly string ISI_FILEEXTENSION = "ISI_FileExtension";
public static readonly string ISI_CONTENTLENGTH = "ISI_ContentLength ";
public static readonly string ISI_LEVEL_BASE = "0";
public static readonly string ISI_LEVEL_COMMENT = "Comment";
public static readonly string ISI_LEVEL_STATUS = "Status";
public static readonly string ISI_LEVEL_APPROVE = "Approve";
public static readonly string ISI_LEVEL_HELP = "Help";
public static readonly string ISI_LEVEL_STARTPERCENT = "StartPercent";
public static readonly string ISI_LEVEL_OPEN = "Open";
public static readonly string ISI_LEVEL_COMPLETE = "Complete";
public static readonly string SMS_SEPRATOR = "\r\n";
public static readonly string TEXT_SEPRATOR2 = "\n";
public static readonly string TEXT_SEPRATOR = "\r\n";
public static readonly string EMAIL_SEPRATOR = "<br />";
public static readonly string SCHEDULINGTYPE_SPECIAL = "Special";
public static readonly string SCHEDULINGTYPE_GENERAL = "General";
public static readonly string SCHEDULINGTYPE_TASKSUBTYPE = "TaskSubType";
public static readonly string CODE_MASTER_PERMISSION_CATEGORY_TYPE_VALUE_ISI = "ISI";
public static readonly string CODE_MASTER_ISI_TYPE_VALUE_TASKSUBTYPE = "TaskSubType";
public static readonly string CODE_MASTER_ISI_TYPE_VALUE_TASKADMIN = "TaskAdmin";
public static readonly string CODE_MASTER_ISI_TASK_VALUE_ISIADMIN = "ISIAdmin";
public static readonly string CODE_MASTER_ISI_TASK_VALUE_TASKFLOWADMIN = "TaskFlowAdmin";
public static readonly string CODE_MASTER_ISI_TASK_VALUE_VIEW = "ISIViewer";
public static readonly string CODE_MASTER_ISI_TASK_VALUE_ASSIGN = "ISIAssign";
public static readonly string CODE_MASTER_ISI_TASK_VALUE_CLOSE = "ISIClose";
public static readonly string CODE_MASTER_WF_TASK_VALUE_WFADMIN = "WFAdmin";
public static readonly string PERMISSION_PAGE_ISI_VALUE_ADDATTACHMENT = "AddAttachment";
public static readonly string PERMISSION_PAGE_ISI_VALUE_DELETEATTACHMENT = "DeleteAttachment";
public static readonly string PERMISSION_PAGE_ISI_VALUE_PLANREMIND = "PlanRemind";
public static readonly string PERMISSION_PAGE_ISI_VALUE_5SREMIND = "5SRemind";
public static readonly string PERMISSION_PAGE_ISI_VALUE_TASKREPORT = "TaskReport";
public static readonly string PERMISSION_PAGE_ISI_VALUE_ISCADRE = "IsCadre";
public static readonly string PERMISSION_PAGE_ISI_VALUE_DELETETASKSTATUS = "DeleteTaskStatus";
public static readonly string ENTITY_PREFERENCE_CODE_EMPPRUN = "EMPPRun";
public static readonly string ENTITY_PREFERENCE_WEBADDRESS = "WebAddress";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_CLIENT_ROWS = "ISIClientRefresh";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_ASSIGN_UP_TIME = "ISI_AssignUpTime";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_START_UP_TIME = "ISI_StartUpTime";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_CLOSE_UP_TIME = "ISI_CloseUpTime";
public static readonly string ENTITY_PREFERENCE_ISI_MAC = "ISI_MAC";
public static readonly string ENTITY_PREFERENCE_ISI_IP = "ISI_IP";
public static readonly string ENTITY_PREFERENCE_ISI_PCNAME = "ISI_PCName";
public static readonly string ENTITY_PREFERENCE_ISI_RESSUBSCRIBE = "ISI_ResSubscribe";
//public static readonly string ENTITY_PREFERENCE_ISI_PCLOGINNAME = "ISI_PCLoginName";
public static readonly string CODE_MASTER_ISI_SMS_EVENTHANDLER = "ISI_SMSEventHeadler";
public static readonly string CODE_MASTER_ISI_SMS_EVENTHANDLER_MESSAGERECEIVEDINTERFACE = "MessageReceivedInterface";
public static readonly string CODE_MASTER_ISI_SMS_EVENTHANDLER_STATUSRECEIVEDINTERFACE = "StatusReceivedInterface";
public static readonly string CODE_MASTER_ISI_SMS_EVENTHANDLER_SUBMITRESPINTERFACE = "SubmitRespInterface";
public static readonly string CODE_MASTER_ISI_PRIORITY = "ISIPriority";
public static readonly string CODE_MASTER_ISI_PRIORITY_NORMAL = "Normal";
public static readonly string CODE_MASTER_ISI_PRIORITY_URGENT = "Urgent";
public static readonly string CODE_MASTER_ISI_PRIORITY_HIGH = "High";
public static readonly string CODE_MASTER_ISI_PRIORITY_LOW = "Low";
public static readonly string CODE_MASTER_ISI_PRIORITY_MAJOR = "Major";
public static readonly string CODE_MASTER_BTD_FLOW_CATEGORY = "FlowCategory";
/// <summary>
/// 工业废弃物
/// </summary>
public static readonly string CODE_MASTER_BTD_FLOW_CATEGORY_SC = "SC";
/// <summary>
/// 备件
/// </summary>
public static readonly string CODE_MASTER_BTD_FLOW_CATEGORY_SP = "SP";
public static readonly string CODE_MASTER_ISI_SEND_STATUS = "ISISendStatus";
public static readonly string CODE_MASTER_ISI_SEND_STATUS_SUCCESS = "Success";
public static readonly string CODE_MASTER_ISI_SEND_STATUS_FAIL = "Fail";
public static readonly string CODE_MASTER_ISI_SEND_STATUS_NOTSEND = "NotSend";
public static readonly string CODE_MASTER_ISI_FLAG = "ISIFlag";
public static readonly string CODE_MASTER_ISI_FLAG_DI1 = "DI1";
public static readonly string CODE_MASTER_ISI_FLAG_DI2 = "DI2";
public static readonly string CODE_MASTER_ISI_FLAG_DI3 = "DI3";
public static readonly string CODE_MASTER_ISI_FLAG_DI4 = "DI4";
public static readonly string CODE_MASTER_ISI_FLAG_DI5 = "DI5";
public static readonly string CODE_MASTER_ISI_COLOR = "ISIColor";
public static readonly string CODE_MASTER_ISI_FLAG_RED = "red";
public static readonly string CODE_MASTER_ISI_FLAG_GREEN = "green";
public static readonly string CODE_MASTER_ISI_FLAG_YELLOW = "yellow";
public static readonly string CODE_MASTER_ISI_STATUS = "ISIStatus";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_CREATE = "Create";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_DELETE = "Delete";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_SUBMIT = "Submit";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_INAPPROVE = "In-Approve";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_APPROVE = "Approve";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_RETURN = "Return";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_REFUSE = "Refuse";
//public static readonly string CODE_MASTER_ISI_STATUS_VALUE_SUSPEND = "Suspend";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_INDISPUTE = "In-Dispute";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_CANCEL = "Cancel";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_INPROCESS = "In-Process";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_ASSIGN = "Assign";
//public static readonly string CODE_MASTER_ISI_STATUS_VALUE_REASSIGN = "ReAssign";
//public static readonly string CODE_MASTER_ISI_STATUS_VALUE_PAUSE = "Pause";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_COMPLETE = "Complete";
public static readonly string CODE_MASTER_ISI_STATUS_VALUE_CLOSE = "Close";
public static readonly string CODE_MASTER_WFS_STATUS = "WFSStatus";
public static readonly string CODE_MASTER_WFS_STATUS_VALUE_UNAPPROVED = "Unapproved";
public static readonly string CODE_MASTER_ISI_ORG = "ISIDepartment";
//考核状态
public static readonly string CODE_MASTER_ISI_CHECKUP_STATUS = "ISICheckupStatus";
public static readonly string CODE_MASTER_ISI_CHECKUP_STATUS_CREATE = "Create";
public static readonly string CODE_MASTER_ISI_CHECKUP_STATUS_SUBMIT = "Submit";
public static readonly string CODE_MASTER_ISI_CHECKUP_STATUS_APPROVAL = "Approval";
public static readonly string CODE_MASTER_ISI_CHECKUP_STATUS_CLOSE = "Close";
public static readonly string CODE_MASTER_ISI_CHECKUP_STATUS_CANCEL = "Cancel";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECT_TYPE = "ISICheckupProjectType";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECT_TYPE_GENERAL = "General";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECT_TYPE_EMPLOYEE = "Employee";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECT_TYPE_CADRE = "Cadre";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECTTYPE = "ISICheckupProjectType";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECTTYPE_VALUE_GENERAL = "General";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECTTYPE_VALUE_EMPLOYEE = "Employee";
public static readonly string CODE_MASTER_ISI_CHECKUPPROJECTTYPE_VALUE_CADRE = "Cadre";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_AMOUNTLIMIT_CADRE = "ISIAmountLimitCadre";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_AMOUNTLIMIT_EMPLOYEE = "ISIAmountLimitEmployee";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_CHECKUPSUBMITREMIND = "ISICheckupSubmitRemind";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_CADRECHECKUPCC = "CadreCheckupCC";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_EMPLOYEECHECKUPCC = "EmployeeCheckupCC";
public static readonly string ENTITY_PREFERENCE_CODE_ISI_TASKSTATUSUPDATEDAY = "ISITaskStatusUpdateDay";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_CREATECHECKUP = "CreateCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_APPROVECHECKUP = "ApproveCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_CLOSECHECKUP = "CloseCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_EXPORTCHECKUP = "ExportCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_APPROVEREMINDCHECKUP = "ApproveRemindCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_REMINDCHECKUP = "RemindCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_RECEIVEPUBLISHCHECKUP = "ReceivePublishCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_PUBLISHCHECKUP = "PublishCheckup";
public static readonly string PERMISSION_PAGE_ISI_CHECKUP_VALUE_RECEIVECLOSEREMINDCHECKUP = "ReceiveCloseRemindCheckup";
// 项目管理
public static readonly string CODE_MASTER_ISI_PROJECT_PHASE = "ISIPhase";
public static readonly string CODE_MASTER_ISI_PROJECTSUBTYPE_QUOTE = "Quote";//报价
public static readonly string CODE_MASTER_ISI_PROJECTSUBTYPE_INITIATION = "Initiation";//开发
#endregion
public static readonly string CODE_MASTER_PERMISSION_FILTER_VALUE_FILTERADMIN = "FilterAdmin";
#region 月度自评
public static readonly string CODE_MASTER_SUMMARY_CHECKUPPROJECT = "Summary";
public static readonly string CODE_MASTER_SUMMARY_VALUE_SUMMARYADMIN = "SummaryAdmin";
public static readonly string CODE_MASTER_SUMMARY_VALUE_SUMMARYAPPROVE = "SummaryApprove";
public static readonly string CODE_MASTER_SUMMARY_TYPE = "ISISummaryType";
public static readonly string CODE_MASTER_SUMMARY_TYPE_EXCELLENT = "Excellent";
public static readonly string CODE_MASTER_SUMMARY_TYPE_MODERATE = "Moderate";
public static readonly string CODE_MASTER_SUMMARY_TYPE_POOR = "Poor";
public static readonly string CODE_MASTER_SUMMARY_STATUS = "ISISummaryStatus";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_CREATE = "Create";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_DELETE = "Delete";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_SUBMIT = "Submit";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_CANCEL = "Cancel";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_INAPPROVE = "In-Approve";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_APPROVAL = "Approval";
public static readonly string CODE_MASTER_SUMMARY_STATUS_VALUE_CLOSE = "Close";
#endregion
#region 工作流
public static readonly string STRING_EMPTY = "空";
public static readonly string TASKAPPLY_GEN_EMAIL = "Email";
public static readonly string TASKAPPLY_GEN_PRINT = "Print";
public static readonly string TASKAPPLY_GEN_HTML = "Html";
public static readonly string CODE_MASTER_ISI_MSG_TYPE = "ISIMsgType";
public static readonly string CODE_MASTER_ISI_MSG_TYPE_STATUS = "Status";
public static readonly string CODE_MASTER_ISI_MSG_TYPE_APPROVE = "Approve";
public static readonly string CODE_MASTER_ISI_MSG_TYPE_COMMENT = "Comment";
public static readonly string CODE_MASTER_WFS_TYPE = "WFSType";
public static readonly string CODE_MASTER_WFS_TYPE_QTY = "Qty";
public static readonly string CODE_MASTER_WFS_TYPE_TEXTBOX = "TextBox";
public static readonly string CODE_MASTER_WFS_TYPE_TEXTAREA = "TextArea";
public static readonly string CODE_MASTER_WFS_TYPE_CHECKBOX = "CheckBox";
public static readonly string CODE_MASTER_WFS_TYPE_DATE = "Date";
public static readonly string CODE_MASTER_WFS_TYPE_DATETIME = "DateTime";
public static readonly string CODE_MASTER_WFS_TYPE_RADIO = "Radio";
public static readonly string CODE_MASTER_WFS_TYPE_LABEL = "Label";
public static readonly string CODE_MASTER_WFS_TYPE_BLANK = "Blank";
public static readonly string APPLY_AMOUNT = "Amount";
public static readonly string APPLY_DATE = "Date";
public static readonly string APPLY_DATETIME = "DateTime";
public static readonly string APPLY_AMOUNT2 = "Amount2";
public static readonly string APPLY_SHIPFROM = "ShipFrom";
public static readonly string APPLY_SHIPTO = "ShipTo";
/// <summary>
/// 默认间隔
/// </summary>
public static readonly int CODE_MASTER_WFS_LEVEL_INTERVAL = 10000;
/// <summary>
/// 会签默认间隔
/// </summary>
public static readonly int CODE_MASTER_WF_COUNTERSIGN_LEVEL_INTERVAL = 100;
public static readonly int? CODE_MASTER_WFS_LEVEL_DEFAULT = null;
public static readonly int CODE_MASTER_WF_PRELEVEL = -1;
public static readonly int CODE_MASTER_WFS_LEVEL1 = 10000;
public static readonly int CODE_MASTER_WFS_LEVEL2 = 20000;
public static readonly int CODE_MASTER_WFS_LEVEL3 = 30000;
public static readonly int CODE_MASTER_WFS_LEVEL4 = 40000;
public static readonly int CODE_MASTER_WFS_LEVEL5 = 50000;
public static readonly int CODE_MASTER_WFS_LEVEL6 = 60000;
public static readonly int CODE_MASTER_WFS_LEVEL7 = 70000;
public static readonly int CODE_MASTER_WFS_LEVEL8 = 80000;
public static readonly int CODE_MASTER_WFS_LEVEL9 = 90000;
public static readonly int CODE_MASTER_WFS_LEVEL10 = 100000;
public static readonly int CODE_MASTER_WFS_LEVEL11 = 110000;
public static readonly int CODE_MASTER_WFS_LEVEL12 = 120000;
public static readonly int CODE_MASTER_WFS_LEVEL13 = 130000;
public static readonly int CODE_MASTER_WFS_LEVEL14 = 140000;
public static readonly int CODE_MASTER_WFS_LEVEL15 = 150000;
public static readonly int CODE_MASTER_WFS_LEVEL16 = 160000;
public static readonly int CODE_MASTER_WFS_LEVEL17 = 170000;
public static readonly int CODE_MASTER_WFS_LEVEL18 = 180000;
public static readonly int CODE_MASTER_WFS_LEVEL19 = 190000;
public static readonly int CODE_MASTER_WFS_LEVEL20 = 200000;
public static readonly int CODE_MASTER_WFS_LEVEL_ULTIMATE = 900000;
public static readonly int CODE_MASTER_WFS_LEVEL_COMPLETE = 900000000;
//工时单位
public static readonly string WORKHOUR_UOM = "H";
#endregion
#region 责任方阵
public static readonly string PERMISSION_PAGE_VALUE_RESMATRIXCHANGELOG = "ResMatrixChangeLogRep";
#endregion
#region 新增异常报表
public static readonly string PERMISSION_PAGE_VALUE_PRODUCTIONINOUT = "ProductionInOutRep";
public static readonly string PERMISSION_PAGE_VALUE_SPCLOG = "SPCLogRep";
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using saintify.Business;//Business Namespace to get easily access to business classes
using Newtonsoft.Json;//To manage JSON Content
using System.IO;//To manager files
namespace saintify.Data
{
/// <summary>
/// This class is designed to manage JSON File
/// </summary>
public class JsonConnector
{
#region private attributes
private String jsonFileName = "";
private List<Artist> listOfArtists;
#endregion private attributes
#region constructors
/// <summary>
/// This constructor initializes a new instance of the artist class.
/// </summary>
/// <param name="jsonFileName">File Name containing the json string</param>
public JsonConnector (String jsonFileName)
{
this.jsonFileName = jsonFileName;
this.listOfArtists = ReadJsonFile();
}
#endregion constructors
#region private methods
/// <summary>
/// This method is designed to extrat from file json content and convert it in artist object
/// </summary>
/// <returns>A list of artists extracted from Json File</returns>
private List<Artist> ReadJsonFile()
{
StreamReader strReader = new StreamReader(jsonFileName);
String jsonFileContent = "";
List<Artist> listOfArtists = null;
if (File.Exists(jsonFileName))
{
try
{
jsonFileContent = strReader.ReadToEnd();
if (jsonFileContent != null)
{
try
{
listOfArtists = new List<Artist>();
listOfArtists = JsonConvert.DeserializeObject<List<Artist>>(jsonFileContent);
}
catch (JsonReaderException ex)
{
listOfArtists = null;
}
}
}
finally
{
strReader.Close();
}
}
return listOfArtists;
}
#endregion private methods
#region public methods
#region getters and setters
/// <summary>
/// This getter delivers the list of artists read in the JsonFile
/// </summary>
/// <returns>A list of artists coming from the JSON File read.</returns>
public List<Artist> ListOfArtists()
{
return this.listOfArtists;
}
public Artist GetArtistById(int artistId)
{
foreach (Artist art in this.listOfArtists)
{
if (art.Id() == artistId)
{
return art;
}
}
return null;
}
#endregion getters and setters
#endregion public methods
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
using Caserraria.Items;
namespace Caserraria.Items.Weapons
{
public class PhoenixwingBow : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Phoenixwing Bow");
Tooltip.SetDefault("Wooden arrows turn into phoenixes");
}
public override void SetDefaults()
{
item.damage = 42;
item.ranged = true;
item.width = 28;
item.height = 58;
item.useTime = 13;
item.useAnimation = 13;
item.useStyle = 5;
item.noMelee = true;
item.knockBack = 3f;
item.value = Item.sellPrice(gold: 8);
item.rare = 8;
item.UseSound = SoundID.Item5;
item.autoReuse = true;
item.shoot = 1;
item.shootSpeed = 13f;
item.useAmmo = AmmoID.Arrow;
}
public override bool Shoot(Player player, ref Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack)
{
Vector2 perturbedSpeed = new Vector2(speedX, speedY).RotatedByRandom(MathHelper.ToRadians(20));
speedX = perturbedSpeed.X;
speedY = perturbedSpeed.Y;
if (type == ProjectileID.WoodenArrowFriendly) // or ProjectileID.WoodenArrowFriendly
{
type = ProjectileID.DD2PhoenixBowShot; // or ProjectileID.FireArrow;
}
return true; // return true to allow tmodloader to call Projectile.NewProjectile as normal
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.HellwingBow);
recipe.AddIngredient(ItemID.DD2PhoenixBow);
recipe.AddIngredient(ItemID.Ectoplasm, 5);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}
|
using System;
using System.Collections.Generic;
using Breeze.AssetTypes.DataBoundTypes;
using Breeze.FontSystem;
using Breeze.Screens;
using Breeze.AssetTypes.StaticTemplates;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json;
namespace Breeze.AssetTypes
{
public class StaticButtonAsset : InteractiveAsset
{
private bool dirty = true;
public DataboundValue<MDL2Symbols?> Symbol { get; set; } = new DataboundValue<MDL2Symbols?>();
public DataboundValue<bool> Enabled { get; set; } = new DataboundValue<bool>(true);
public DataboundValue<ButtonVisualDescriptor> Normal { get; set; } = new DataboundValue<ButtonVisualDescriptor>();
public DataboundValue<ButtonVisualDescriptor> Hover { get; set; } = new DataboundValue<ButtonVisualDescriptor>();
public DataboundValue<ButtonVisualDescriptor> Pressing { get; set; } = new DataboundValue<ButtonVisualDescriptor>();
public DataboundValue<ButtonVisualDescriptor> Disabled { get; set; } = new DataboundValue<ButtonVisualDescriptor>();
public DataboundValue<float> FontMargin { get; set; } = new DataboundValue<float>();
public DataboundValue<string> Text { get; set; } = new DataboundValue<string>();
public float FontMarginInit
{
get => FontMargin.Value;
set => FontMargin.Value = value;
}
public bool EnabledInit
{
get => Enabled.Value;
set => Enabled.Value = value;
}
// [JsonIgnore]
public DataboundEvent<ButtonClickEventArgs> Clicked { get; set; } = new DataboundEvent<ButtonClickEventArgs>();
// [JsonIgnore]
public DataboundEvent<ButtonClickEventArgs> ButtonDown { get; set; } = new DataboundEvent<ButtonClickEventArgs>();
//[JsonIgnore]
public DataboundEvent<ButtonClickEventArgs> ButtonUp { get; set; } = new DataboundEvent<ButtonClickEventArgs>();
public object Tag { get; set; }
public StaticButtonAsset()
{
}
public StaticButtonAsset(FloatRectangle position, MDL2Symbols symbol, Action<ButtonClickEventArgs> clickAction = null, ButtonVisualDescriptor normal = null, ButtonVisualDescriptor hover = null, ButtonVisualDescriptor pressing = null, ButtonVisualDescriptor disabled = null, float fontMargin = 0, Color? backgroundColor = null, Color? hoverColor = null)
{
CreateButtonAsset(position, symbol.AsChar(), clickAction, normal, hover, pressing, disabled, fontMargin, backgroundColor, hoverColor, Solids.Instance.Fonts.MDL2);
//Position.SetChangeAction(() => { base.Position = this.Position.Value; });
}
public StaticButtonAsset(StaticTemplate template, FloatRectangle position, MDL2Symbols symbol, string text, Action<ButtonClickEventArgs> clickAction = null, float fontMargin = 0, Color? backgroundColor = null, Color? hoverColor = null)
{
Symbol.Value = symbol;
CreateButtonAsset(position, text, clickAction, template.Normal, template.Hover, template.Pressing, template.Disabled, fontMargin, backgroundColor, hoverColor, Solids.Instance.Fonts.MDL2);
}
public StaticButtonAsset(StaticTemplate template, FloatRectangle position, string text, Action<ButtonClickEventArgs> clickAction = null, float fontMargin = 0, Color? backgroundColor = null, Color? hoverColor = null)
{
CreateButtonAsset(position, text, clickAction, template?.Normal, template?.Hover, template?.Pressing, template?.Disabled, fontMargin, backgroundColor, hoverColor);
}
public StaticButtonAsset(FloatRectangle position, string text, Action<ButtonClickEventArgs> clickAction = null, ButtonVisualDescriptor normal = null, ButtonVisualDescriptor hover = null, ButtonVisualDescriptor pressing = null, ButtonVisualDescriptor disabled = null, float fontMargin = 0, Color? backgroundColor = null, Color? hoverColor = null)
{
CreateButtonAsset(position, text, clickAction, normal, hover, pressing, disabled, fontMargin, backgroundColor, hoverColor);
}
private void CreateButtonAsset(FloatRectangle position, string text, Action<ButtonClickEventArgs> clickAction = null, ButtonVisualDescriptor normal = null, ButtonVisualDescriptor hover = null, ButtonVisualDescriptor pressing = null, ButtonVisualDescriptor disabled = null, float fontMargin = 0, Color? backgroundColor = null, Color? hoverColor = null, FontFamily font = null)
{
if (font == null)
{
font = Solids.Instance.Fonts.EuroStile;
}
Position.Value = position;
Normal.Value = normal;
Hover.Value = hover;
Pressing.Value = pressing;
Disabled.Value = disabled;
FontMargin.Value = fontMargin;
Text.Value = text;
Clicked.Action = clickAction;
if (Normal.Value == null)
{
Normal.Value = new ButtonVisualDescriptor
{
FontFamily = font,
BackgroundColor = backgroundColor ?? Color.Black * 0.68f,
Text = text,
BorderBrushSize = 0,
BorderColor = Color.LightGray,
FontColor = Color.White,
FontScale = 1f,
TextJustification = FontAsset.FontJustification.Center,
BlurAmount = 12
};
}
else
{
if (Normal.Value.Text == null) Normal.Value.Text = text;
}
if (Hover.Value == null)
{
Hover.Value = new ButtonVisualDescriptor
{
FontFamily = font,
BackgroundColor = hoverColor ?? Color.Green * 0.5f,
Text = text,
BorderBrushSize = 0,
BorderColor = Color.Purple,
FontColor = Color.White,
FontScale = 1f,
TextJustification = FontAsset.FontJustification.Center,
ShadowDepth = 0.095f,
BlurAmount = 20
};
}
else
{
if (Hover.Value.Text == null) Hover.Value.Text = text;
}
if (Pressing.Value == null)
{
Pressing.Value = new ButtonVisualDescriptor
{
FontFamily = font,
BackgroundColor = Color.Purple,
Text = text,
BorderBrushSize = 0,
BorderColor = Color.Purple,
FontColor = Color.White,
FontScale = 1f,
TextJustification = FontAsset.FontJustification.Center,
ShadowDepth = 0.045f,
BlurAmount = 10
};
}
else
{
if (Pressing.Value.Text == null) Pressing.Value.Text = text;
}
if (Disabled.Value == null)
{
Disabled.Value = new ButtonVisualDescriptor
{
FontFamily = font,
BackgroundColor = backgroundColor ?? Color.Black * 0.48f,
Text = text,
BorderBrushSize = 0,
BorderColor = Color.LightGray,
FontColor = Color.White * 0.5f,
FontScale = 1f,
TextJustification = FontAsset.FontJustification.Center,
BlurAmount = 12
};
}
else
{
if (Disabled.Value.Text == null) Disabled.Value.Text = text;
}
this.Position.SetChangeAction(() => dirty = true);
this.Text.SetChangeAction(TextChangeEvent);
this.State.SetChangeAction(() => dirty = true);
this.Symbol.SetChangeAction(() => dirty = true);
this.Enabled.SetChangeAction(() => dirty = true);
}
private void TextChangeEvent()
{
Normal.Value.Text = Text.Value;
Hover.Value.Text = Text.Value;
Pressing.Value.Text = Text.Value;
Disabled.Value.Text = Text.Value;
}
List<DataboundAsset> assetscache = new List<DataboundAsset>();
private string assetscachekey = "";
public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null)
{
FloatRectangle? tclip = screen.Translate(clip);
FloatRectangle possy = ActualPosition;//.Clamp(clip);
List<DataboundAsset> assets = null;
string key = Text.Value + State.Value.ToString() + Position.Value.ToString() + Enabled.Value.ToString();
if (dirty || assetscache == null || assetscache.Count == 0 || assetscachekey != key)
{
assets = new List<DataboundAsset>();
ButtonVisualDescriptor currentVisual = null;
switch (State.Value)
{
case ButtonState.Normal:
{
currentVisual = Normal.Value;
break;
}
case ButtonState.Hover:
{
currentVisual = Hover.Value;
break;
}
case ButtonState.Pressing:
{
currentVisual = Pressing.Value;
break;
}
}
if (!Enabled.Value)
{
currentVisual = Disabled.Value;
}
if (currentVisual.ShadowDepth > 0)
{
assets.Add(new BoxShadowAsset(Color.White, currentVisual.ShadowDepth, possy) { Clip = clip });
}
if (!string.IsNullOrEmpty(currentVisual?.BackgroundTexture))
{
assets.Add(new RectangleAsset(currentVisual.BackgroundColor, 0, possy, currentVisual.BackgroundTexture, null, currentVisual.BackgroundTileMode) { Clip = clip });
}
assets.Add(new RectangleAsset(currentVisual.BorderColor, 0, possy, currentVisual.BackgroundColor, currentVisual.BlurAmount) { Clip = clip });
if (Symbol.Value != null)
{
FloatRectangle fontPos = new FloatRectangle(FontMargin.Value + possy.X, possy.Y + FontMargin.Value, ActualPosition.Width, ActualPosition.Height - (FontMargin.Value * 2f));
assets.Add(new FontAsset(Symbol.Value.Value.AsChar(), currentVisual.FontColor, fontPos, Solids.Instance.Fonts.MDL2, FontAsset.FontJustification.Left) { Clip = tclip });
}
if (!string.IsNullOrEmpty(currentVisual.Text))
{
var all = currentVisual.TextJustification;
float xx = 0;
if (Symbol != null)
{
xx = ActualPosition.Height * 0.75f;
all = FontAsset.FontJustification.Left;
}
FloatRectangle fontPos = new FloatRectangle(possy.X + xx, ActualPosition.Y + FontMargin.Value, possy.Width, possy.Height - (FontMargin.Value * 2f));
assets.Add(new FontAsset(Text.Value, currentVisual.FontColor, fontPos, currentVisual.FontFamily, all) { Clip = clip });
}
if (currentVisual.BorderBrushSize > 0)
{
assets.Add(new RectangleAsset(currentVisual.BorderColor, currentVisual.BorderBrushSize, possy)
{
Clip = clip,
});
}
dirty = false;
assetscache = assets;
assetscachekey = key;
}
else
{
assets = assetscache;
}
foreach (DataboundAsset screenAsset in assets)
{
screenAsset.Draw(screenResources, spriteBatch, screen, opacity, clip, bgTexture);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HMSApp.Models
{
/// <summary>
/// Department Information
/// </summary>
public class Department
{
/// <summary>
/// Department code
/// </summary>
public string DepartmentCode { get; set; }
/// <summary>
/// Department Name
/// </summary>
public string DepartmentName { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace TestForPlugin
{
class Program
{
static void Main(string[] args)
{
string retString = "CDATA[nbf+isCUcgz1DgfSC7cr7U2aBGvxCZLvpotAz7UTaWI3c+sgdT9YkE9N9jnR8b0pf+q+PPJkmY34hKB8nb7LQ+PPThA4kjg08Y+if+j8TY+AXpNxkwb1ttez6Qe8OG8GP/1SosmYYwLmxu993KNW/ZhW23N7opai9Z9QmX8/r3Q69anZcQpxfe3w4NiUW7Cr]]></";
string regString = "CDATA\\[(?<value>(.|\n)*?)\\]";
Match match = Regex.Match(retString, regString);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Terminal.Gui;
using Xunit;
using Xunit.Abstractions;
namespace Terminal.Gui.ViewTests {
public class AutocompleteTests {
readonly ITestOutputHelper output;
public AutocompleteTests (ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void Test_GenerateSuggestions_Simple ()
{
var ac = new TextViewAutocomplete ();
ac.AllSuggestions = new List<string> { "fish", "const", "Cobble" };
var tv = new TextView ();
tv.InsertText ("co");
ac.HostControl = tv;
ac.GenerateSuggestions ();
Assert.Equal (2, ac.Suggestions.Count);
Assert.Equal ("const", ac.Suggestions [0]);
Assert.Equal ("Cobble", ac.Suggestions [1]);
}
[Fact]
[AutoInitShutdown]
public void TestSettingColorSchemeOnAutocomplete ()
{
var tv = new TextView ();
// to begin with we should be using the default menu color scheme
Assert.Same (Colors.Menu, tv.Autocomplete.ColorScheme);
// allocate a new custom scheme
tv.Autocomplete.ColorScheme = new ColorScheme () {
Normal = Application.Driver.MakeAttribute (Color.Black, Color.Blue),
Focus = Application.Driver.MakeAttribute (Color.Black, Color.Cyan),
};
// should be separate instance
Assert.NotSame (Colors.Menu, tv.Autocomplete.ColorScheme);
// with the values we set on it
Assert.Equal (Color.Black, tv.Autocomplete.ColorScheme.Normal.Foreground);
Assert.Equal (Color.Blue, tv.Autocomplete.ColorScheme.Normal.Background);
Assert.Equal (Color.Black, tv.Autocomplete.ColorScheme.Focus.Foreground);
Assert.Equal (Color.Cyan, tv.Autocomplete.ColorScheme.Focus.Background);
}
[Fact]
[AutoInitShutdown]
public void KeyBindings_Command ()
{
var tv = new TextView () {
Width = 10,
Height = 2,
Text = " Fortunately super feature."
};
var top = Application.Top;
top.Add (tv);
Application.Begin (top);
Assert.Equal (Point.Empty, tv.CursorPosition);
Assert.NotNull (tv.Autocomplete);
Assert.Empty (tv.Autocomplete.AllSuggestions);
tv.Autocomplete.AllSuggestions = Regex.Matches (tv.Text.ToString (), "\\w+")
.Select (s => s.Value)
.Distinct ().ToList ();
Assert.Equal (3, tv.Autocomplete.AllSuggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.AllSuggestions [0]);
Assert.Equal ("super", tv.Autocomplete.AllSuggestions [1]);
Assert.Equal ("feature", tv.Autocomplete.AllSuggestions [^1]);
Assert.Equal (0, tv.Autocomplete.SelectedIdx);
Assert.Empty (tv.Autocomplete.Suggestions);
Assert.True (tv.ProcessKey (new KeyEvent (Key.F, new KeyModifiers ())));
top.Redraw (tv.Bounds);
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [0]);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [^1]);
Assert.Equal (0, tv.Autocomplete.SelectedIdx);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [tv.Autocomplete.SelectedIdx]);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorDown, new KeyModifiers ())));
top.Redraw (tv.Bounds);
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [0]);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [^1]);
Assert.Equal (1, tv.Autocomplete.SelectedIdx);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [tv.Autocomplete.SelectedIdx]);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorDown, new KeyModifiers ())));
top.Redraw (tv.Bounds);
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [0]);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [^1]);
Assert.Equal (0, tv.Autocomplete.SelectedIdx);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [tv.Autocomplete.SelectedIdx]);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorUp, new KeyModifiers ())));
top.Redraw (tv.Bounds);
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [0]);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [^1]);
Assert.Equal (1, tv.Autocomplete.SelectedIdx);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [tv.Autocomplete.SelectedIdx]);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorUp, new KeyModifiers ())));
top.Redraw (tv.Bounds);
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [0]);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [^1]);
Assert.Equal (0, tv.Autocomplete.SelectedIdx);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [tv.Autocomplete.SelectedIdx]);
Assert.True (tv.Autocomplete.Visible);
top.Redraw (tv.Bounds);
Assert.True (tv.ProcessKey (new KeyEvent (tv.Autocomplete.CloseKey, new KeyModifiers ())));
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Empty (tv.Autocomplete.Suggestions);
Assert.Equal (3, tv.Autocomplete.AllSuggestions.Count);
Assert.False (tv.Autocomplete.Visible);
top.Redraw (tv.Bounds);
Assert.True (tv.ProcessKey (new KeyEvent (tv.Autocomplete.Reopen, new KeyModifiers ())));
Assert.Equal ($"F Fortunately super feature.", tv.Text);
Assert.Equal (new Point (1, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal (3, tv.Autocomplete.AllSuggestions.Count);
Assert.True (tv.ProcessKey (new KeyEvent (tv.Autocomplete.SelectionKey, new KeyModifiers ())));
Assert.Equal ($"Fortunately Fortunately super feature.", tv.Text);
Assert.Equal (new Point (11, 0), tv.CursorPosition);
Assert.Equal (2, tv.Autocomplete.Suggestions.Count);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [0]);
Assert.Equal ("feature", tv.Autocomplete.Suggestions [^1]);
Assert.Equal (0, tv.Autocomplete.SelectedIdx);
Assert.Equal ("Fortunately", tv.Autocomplete.Suggestions [tv.Autocomplete.SelectedIdx]);
Assert.True (tv.ProcessKey (new KeyEvent (tv.Autocomplete.CloseKey, new KeyModifiers ())));
Assert.Equal ($"Fortunately Fortunately super feature.", tv.Text);
Assert.Equal (new Point (11, 0), tv.CursorPosition);
Assert.Empty (tv.Autocomplete.Suggestions);
Assert.Equal (3, tv.Autocomplete.AllSuggestions.Count);
}
[Fact, AutoInitShutdown]
public void CursorLeft_CursorRight_Mouse_Button_Pressed_Does_Not_Show_Popup ()
{
var tv = new TextView () {
Width = 50,
Height = 5,
Text = "This a long line and against TextView."
};
tv.Autocomplete.AllSuggestions = Regex.Matches (tv.Text.ToString (), "\\w+")
.Select (s => s.Value)
.Distinct ().ToList ();
var top = Application.Top;
top.Add (tv);
Application.Begin (top);
for (int i = 0; i < 7; i++) {
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This a long line and against TextView.", output);
}
Assert.True (tv.MouseEvent (new MouseEvent () {
X = 6,
Y = 0,
Flags = MouseFlags.Button1Pressed
}));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This a long line and against TextView.", output);
Assert.True (tv.ProcessKey (new KeyEvent (Key.g, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This ag long line and against TextView.
against ", output);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorLeft, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This ag long line and against TextView.
against ", output);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorLeft, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This ag long line and against TextView.
against ", output);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorLeft, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This ag long line and against TextView.", output);
for (int i = 0; i < 3; i++) {
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This ag long line and against TextView.", output);
}
Assert.True (tv.ProcessKey (new KeyEvent (Key.Backspace, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This a long line and against TextView.", output);
Assert.True (tv.ProcessKey (new KeyEvent (Key.n, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This an long line and against TextView.
and ", output);
Assert.True (tv.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers ())));
Application.Refresh ();
TestHelpers.AssertDriverContentsWithFrameAre (@"
This an long line and against TextView.", output);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace GymWorkout.Commands
{
public static class CustomCommands
{
public static readonly RoutedUICommand Workouts = new RoutedUICommand
(
"Workouts",
"Workouts",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.L, ModifierKeys.Alt)
}
);
public static readonly RoutedUICommand WorkoutAdd = new RoutedUICommand
(
"WorkoutAdd",
"WorkoutAdd",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.A, ModifierKeys.Alt)
}
);
public static readonly RoutedUICommand WorkoutEdit = new RoutedUICommand
(
"WorkoutEdit",
"WorkoutEdit",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.E, ModifierKeys.Alt)
}
);
public static readonly RoutedUICommand WorkoutDelete = new RoutedUICommand
(
"WorkoutDelete",
"WorkoutDelete",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.D, ModifierKeys.Alt)
}
);
public static readonly RoutedUICommand WorkoutDetailEdit = new RoutedUICommand
(
"WorkoutDetailEdit",
"WorkoutDetailEdit",
typeof(CustomCommands)
);
public static readonly RoutedUICommand WorkoutDetailDelete = new RoutedUICommand
(
"WorkoutDetailDelete",
"WorkoutDetailDelete",
typeof(CustomCommands)
);
}
}
|
using Microsoft.AspNet.Http;
using Microsoft.Data.Entity;
using Stolons.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Stolons.ViewModels.ProductsManagement
{
public class ProductEditionViewModel
{
public bool IsNew { get; set; }
public string[] SelectedLabels { get; set; }
public string FamillyName { get; set; }
public Product Product { get; set; }
public List<ProductType> ProductTypes { get; set; }
public IFormFile UploadFile1 { get; set; }
public IFormFile UploadFile2 { get; set; }
public IFormFile UploadFile3 { get; set; }
public ProductEditionViewModel()
{
}
public ProductEditionViewModel(Product product, ApplicationDbContext context, bool isNew)
{
Product = product;
IsNew = isNew;
RefreshTypes(context);
}
public void RefreshTypes(ApplicationDbContext context)
{
ProductTypes = context.ProductTypes.Include(x => x.ProductFamilly).ToList();
SelectedLabels = Product.Labels.Select(s => s.ToString()).ToArray();
}
}
}
|
using Framework.Core.Common;
using Tests.Data.Van.Input;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace Tests.Pages.Van.Main.VirtualPhoneBankPages.VirtualPhoneBankDetailsPageComponents
{
public class NameDescriptionScriptVpbDetailsPageComponent : VirtualPhoneBankDetailsPageComponent
{
private readonly Driver _driver;
#region Element Declarations
public IWebElement NameField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemVirtualPhoneBankListName_VANInputItemDetailsItemVirtualPhoneBankListName_VirtualPhoneBankListName")); } }
public IWebElement DescriptionField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemVPBLDescription_VANInputItemDetailsItemVPBLDescription_VPBLDescription")); } }
public IWebElement ScriptDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemScriptID_VANInputItemDetailsItemScriptID_ScriptID")); } }
#endregion
public NameDescriptionScriptVpbDetailsPageComponent(Driver driver)
{
_driver = driver;
}
public override void SetFields(VirtualPhoneBank vpb)
{
_driver.ClearAndSendKeysIfStringNotNullOrEmpty(NameField, vpb.Name);
_driver.ClearAndSendKeysIfStringNotNullOrEmpty(DescriptionField, vpb.Description);
_driver.SelectOptionByTextIfStringNotNullOrEmpty(ScriptDropdown, vpb.Script);
}
public override bool Validate(VirtualPhoneBank vpb)
{
var errorCount = 0;
if (!NameField.GetAttribute("value").Equals(vpb.Name))
{
errorCount++;
WriteVirtualPhoneBankValidationToConsole(NameField,
vpb.Name,
NameField.GetAttribute("value"));
}
if (!DescriptionField.GetAttribute("value").Equals(vpb.Description))
{
errorCount++;
WriteVirtualPhoneBankValidationToConsole(DescriptionField,
vpb.Description,
DescriptionField.GetAttribute("value"));
}
var scriptDropdownText = new SelectElement(ScriptDropdown).SelectedOption.Text;
if (!scriptDropdownText.Equals(vpb.Script))
{
errorCount++;
WriteVirtualPhoneBankValidationToConsole(ScriptDropdown,
vpb.Script,
scriptDropdownText);
}
return errorCount < 1;
}
}
}
|
using System;
using System.IO;
namespace _12.IDEs
{
class Program
{
static void Main()
{
/*
Worldwide, Oct 2016 compared to a year ago:
Rank
Change IDE Share Trend
1 Visual Studio 22.7 % -0.8 %
2 Eclipse 22.05 % -5.9 %
3 Android Studio 10.47 % +2.5 %
4 Vim 8.25 % +0.3 %
5 NetBeans 5.59 % -0.3 %
6 Xcode 5.48 % -0.6 %
7 Sublime Text 4.45 % +0.2 %
8 IntelliJ 4.26 % +1.2 %
9 Komodo 3.74 % +0.6 %
10 Xamarin 3.68 % +2.3 %
11 Emacs 1.91 % +0.1 %
12 pyCharm 1.64 % +0.5 %
13 PhpStorm 1.58 % +0.2 %
14 Light Table 1.07 % +0.0 %
15 Cloud9 0.85 % -0.2 %
16 Qt Creator 0.39 % +0.0 %
17 JDeveloper 0.32 % +0.0 %
18 Aptana 0.31 % -0.1 %
19 geany 0.28 % +0.0 %
20 MonoDevelop 0.23 % +0.0 %
21 RubyMine 0.18 % +0.0 %
22 JCreator 0.1 % -0.1 %
23 SharpDevelop 0.09 % +0.0 %
24 Monkey Studio 0.07 % +0.0 %
25 Julia Studio 0.06 % +0.0 %
26 Coda 2 0.06 % +0.0 %
27 Zend Studio 0.06 % +0.0 %
28 Eric Python 0.06 % +0.0 %
29 DrJava 0.04 % +0.0 %
30 SlickEdit 0.03 % +0.0 %
*/
string text = " ";
File.WriteAllText("output.txt", text);
}
}
}
|
namespace Ejercicio
{
public class Chuck : Pajaros
{
private int velocidad;
public Chuck(int velocidad, int ira) : base(ira)
{
this.velocidad = velocidad;
}
public override void seEnoja() => velocidad *= 2;
public override int fuerza(){
if(velocidad <= 80){
return 150;
}else{
return 150 + 5 * (velocidad-80);
}
}
}
} |
using Common;
using Common.Data;
using Common.Exceptions;
using Common.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
namespace Entity
{
[DataContract]
public partial class SystemSearchTitles : IMappable
{
#region Constructors
public SystemSearchTitles()
{ }
#endregion
#region Public Properties
/// <summary>
/// Gets the name of the table to which this object maps.
/// </summary>
public string TableName
{
get { return "System_Search_Titles"; }
}
[DataMember, Index(true)]
public Int32? ID { get; set; }
[DataMember]
public Int32? TitleSortOrder { get; set; }
[DataMember]
public string TitleName { get; set; }
[DataMember]
public string TitleField { get; set; }
[DataMember]
public Int32? TitleGroup { get; set; }
[DataMember]
public Int32? TitleForeign { get; set; }
[DataMember]
public string TitleLanguage { get; set; }
[DataMember]
public Int32? Title_Length { get; set; }
[DataMember]
public string Button_1_Name { get; set; }
[DataMember]
public string Button_2_Name { get; set; }
#endregion
#region Public Methods
public SystemSearchTitles GetRecord(string connectionString, string sql, SqlParameter[] parameters = null)
{
SystemSearchTitles result = null;
using (Database database = new Database(connectionString))
{
try
{
CommandType commandType = CommandType.Text;
if (parameters != null)
commandType = CommandType.StoredProcedure;
using (DataTable table = database.ExecuteSelect(sql, commandType, parameters))
{
if (table.HasRows())
{
Mapper<SystemSearchTitles> m = new Mapper<SystemSearchTitles>();
result = m.MapSingleSelect(table);
}
}
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public List<SystemSearchTitles> GetList(string connectionString, string sql, SqlParameter[] parameters = null)
{
List<SystemSearchTitles> result = new List<SystemSearchTitles>();
using (Database database = new Database(connectionString))
{
try
{
CommandType commandType = CommandType.Text;
if (parameters != null)
commandType = CommandType.StoredProcedure;
using (DataTable table = database.ExecuteSelect(sql, commandType, parameters))
{
if (table.HasRows())
{
Mapper<SystemSearchTitles> m = new Mapper<SystemSearchTitles>();
result = m.MapListSelect(table);
}
}
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using POSServices.Config;
using POSServices.Models;
using POSServices.WebAPIModel;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace POSServices.Controllers
{
[Route("api/[controller]")]
public class HoTransactionLineController : Controller
{
private readonly DB_BIENSI_POSContext _context;
public HoTransactionLineController(DB_BIENSI_POSContext context)
{
_context = context;
}
[HttpGet]
public IActionResult Get([FromQuery] int headerId, [FromQuery] int offset = 0, [FromQuery] int limit = 50)
{
int total = _context.InventoryTransactionLines.Where(n => n.InventoryTransactionId == headerId).Count();
var listModel = _context.InventoryTransactionLines.Where(n => n.InventoryTransactionId == headerId)
.OrderByDescending(c => c.Id)
.Skip(offset)
.Take(limit)
.ToList();
return Ok(new
{
Data = listModel,
Paging = new
{
Total = total,
Limit = 50,
Offset = 0,
Returned = listModel.Count
}
});
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
APIResponse response = new APIResponse();
if (id == 0)
{
response.code = "0";
response.message = "ID can not be empty";
return Ok(response);
}
var header = _context.InventoryTransactionLines.Where(n => n.Id == id).FirstOrDefault<InventoryTransactionLines>();
if (header.Id == 0)
{
response.code = "0";
response.message = "Transaction does not exists";
return Ok(response);
}
return Ok(header);
}
// POST: api/PostTransaction
[HttpPost]
public async Task<IActionResult> PostTransaction([FromBody] InventoryTransactionLines transactionApi)
{
APIResponse response = new APIResponse();
try
{
Models.InventoryTransactionLines transactionLines = new Models.InventoryTransactionLines();
transactionLines.InventoryTransactionId = transactionApi.InventoryTransactionId;
transactionLines.ArticleId = transactionApi.ArticleId;
transactionLines.ArticleName = transactionApi.ArticleName;
transactionLines.Qty = transactionApi.Qty;
_context.InventoryTransactionLines.Add(transactionLines);
await _context.SaveChangesAsync();
response.code = "1";
response.message = "Sucess Add Data";
}
catch (Exception ex)
{
response.code = "0";
response.message = ex.ToString();
}
return Ok(response);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, InventoryTransactionLines model)
{
if (id != model.Id)
{
return BadRequest();
}
_context.Entry(model).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IdExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
private bool IdExists(int id)
{
return _context.InventoryTransactionLines.Any(e => e.Id == id);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
APIResponse response = new APIResponse();
try
{
var model = await _context.InventoryTransactionLines.FindAsync(id);
if (model == null)
{
return NotFound();
}
_context.InventoryTransactionLines.Remove(model);
await _context.SaveChangesAsync();
response.code = "1";
response.message = "Sucess Delete Data";
}
catch (Exception ex)
{
response.code = "0";
response.message = ex.ToString();
}
return Ok(response);
}
}
}
|
using Uintra.Core.Activity.Models.Headers;
using Uintra.Features.Comments.Services;
using Uintra.Features.Likes;
namespace Uintra.Features.Social.Models
{
public class SocialExtendedItemViewModel : SocialItemViewModel
{
public ILikeable LikesInfo { get; set; }
public ICommentable CommentsInfo { get; set; }
public new ExtendedItemHeaderViewModel HeaderInfo { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoadTrigger : MonoBehaviour {
public int LevelTarget;
public Transform targetPoint;
public float playerTurningDisplace;
void OnTriggerEnter (Collider other) {
if (other.tag == "Player") {
other.SendMessage ("OnLoadTrigger", new object[]{ LevelTarget, (targetPoint.position - transform.position), playerTurningDisplace });
}
}
}
|
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Sfa.Poc.ResultsAndCertification.Dfe.Api.Filters;
using Sfa.Poc.ResultsAndCertification.Dfe.Api.Infrastructure;
using Sfa.Poc.ResultsAndCertification.Dfe.Application.Interfaces;
using Sfa.Poc.ResultsAndCertification.Dfe.Models;
namespace Sfa.Poc.ResultsAndCertification.Dfe.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class TqProviderController : ControllerBase
{
private readonly IMapper _mapper;
private readonly IProviderService _providerService;
private readonly ITqAwardingOrganisationService _tqAwardingOrganisationService;
private readonly ITqProviderService _tqProviderService;
private readonly ITqRouteService _tqRouteService;
private readonly ITqPathwayService _tqPathwayService;
private readonly ITqSpecialismService _tqSpecialismService;
public TqProviderController(IMapper mapper,
IProviderService providerService,
ITqAwardingOrganisationService tqAwardingOrganisationService,
ITqProviderService tqProviderService,
ITqRouteService tqRouteService,
ITqPathwayService tqPathwayService,
ITqSpecialismService tqSpecialismService)
{
_mapper = mapper;
_providerService = providerService;
_tqAwardingOrganisationService = tqAwardingOrganisationService;
_tqProviderService = tqProviderService;
_tqRouteService = tqRouteService;
_tqPathwayService = tqPathwayService;
_tqSpecialismService = tqSpecialismService;
}
[HttpPost]
[Route("register-tqprovider", Name = "RegisterTechnicalQualificationProvider")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
//[ValidateModel]
public async Task<IActionResult> RegisterTechnicalQualificationProvider(RegisterTqProvider registerProvider)
{
var ao = await _tqAwardingOrganisationService.GetTqAwardingOrganisationDetailsByCodeAsync(registerProvider.UkAoCode);
//if(ao == null) return BadRequest(new BadRequestResponse($"AoCode '{registerProvider.UkAoCode}' does not exist."));
if (!ao.Success) return NotFound(new ApiResponse((int)HttpStatusCode.NotFound, ao.Message));
var provider = await _providerService.GetProviderDetailsByCodeAsync(registerProvider.UkProviderCode);
if (provider == null) return BadRequest(new BadRequestResponse($"Provider Code '{registerProvider.UkProviderCode}' does not exist."));
var tqRoute = await _tqRouteService.GetTqRouteDetailsByCodeAsync(registerProvider.TqRouteCode);
if (tqRoute == null) return BadRequest(new BadRequestResponse($"Tq Route Code '{registerProvider.TqRouteCode}' does not exist."));
var tqPathway = await _tqPathwayService.GetTqPathwayDetailsByCodeAsync(registerProvider.TqPathwayCode);
if (tqPathway == null) return BadRequest(new BadRequestResponse($"Tq Pathway Code '{registerProvider.TqRouteCode}' does not exist."));
var tqSpecialism = await _tqSpecialismService.GetTqSpecialismDetailsByCodeAsync(registerProvider.TqSpecialismCode);
if (tqSpecialism == null) return BadRequest(new BadRequestResponse($"Tq Specialism Code '{registerProvider.TqRouteCode}' does not exist."));
var tqProvider = new TqProviderDetails
{
AwardingOrganisationId = ao.Value.Id,
ProviderId = provider.Id,
RouteId = tqRoute.Id,
PathwayId = tqPathway.Id,
SpecialismId = tqSpecialism.Id
};
if(await _tqProviderService.CheckIfTqProviderAlreadyExistsAsync(tqProvider))
{
return BadRequest(new BadRequestResponse("A record was not created because a duplicate of the current record already exists."));
}
var tqProviderId = await _tqProviderService.CreateTqProvidersAsync(tqProvider);
//return tqProvider != 0 ? Ok() : (ActionResult)BadRequest();
return CreatedAtAction(nameof(GetRegisteredTqProviderInformation), new { tqProviderId }, registerProvider);
}
[HttpGet]
[Route("registeredtqprovider-information/{tqProviderId}", Name = "GetRegisteredTqProviderInformation")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetRegisteredTqProviderInformation(int tqProviderId)
{
var user = ControllerContext.HttpContext.User;
var registerdTqProviderDetails = await _tqProviderService.GetRegisteredTqProviderDetailsByIdAsync(tqProviderId);
return (registerdTqProviderDetails != null) ? Ok(registerdTqProviderDetails) : (ActionResult)NotFound();
//return (registerdTqProviderDetails != null) ? Ok(new OkResponse<RegisteredTqProviderDetails>(registerdTqProviderDetails)) : (ActionResult)NotFound(new ApiResponse(404, $"Registered Tq Provider not found with id {tqProviderId}"));
}
[HttpPost]
//[Produces("application/json", "multipart/form-data")]
[Route("onboard-tqprovider", Name = "OnBoardTechnicalQualificationProvider")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
//[ValidateModel]
public async Task<IActionResult> OnBoardTechnicalQualificationProvider(OnboardTqProvider registerProvider)
{
var ao = await _tqAwardingOrganisationService.GetTqAwardingOrganisationDetailsByCodeAsync(registerProvider.AoCode);
//if(ao == null) return BadRequest(new BadRequestResponse($"AoCode '{registerProvider.UkAoCode}' does not exist."));
if (!ao.Success) return NotFound(new ApiResponse((int)HttpStatusCode.NotFound, ao.Message));
foreach (var provider in registerProvider.Providers)
{
var providerDetails = await _providerService.GetProviderDetailsByCodeAsync(provider.UkPrnNumber);
if (providerDetails == null) return BadRequest(new BadRequestResponse($"Provider Code '{provider.UkPrnNumber}' does not exist."));
foreach(var route in provider.Routes)
{
var tqRoute = await _tqRouteService.GetTqRouteDetailsByCodeAsync(route.RouteId);
if (tqRoute == null) return BadRequest(new BadRequestResponse($"Tq Route Code '{route.RouteId}' does not exist."));
foreach(var pathway in route.Pathways)
{
var tqPathway = await _tqPathwayService.GetTqPathwayDetailsByCodeAsync(pathway.PathwayId);
if (tqPathway == null) return BadRequest(new BadRequestResponse($"Tq Pathway Code '{pathway.PathwayId}' does not exist."));
foreach(var specialism in pathway.Specialisms)
{
var tqSpecialism = await _tqSpecialismService.GetTqSpecialismDetailsByCodeAsync(specialism.SpecialismId);
if (tqSpecialism == null) return BadRequest(new BadRequestResponse($"Tq Specialism Code '{specialism.SpecialismId}' does not exist."));
}
}
}
}
//var tqProvider = new TqProviderDetails
//{
// AwardingOrganisationId = ao.Value.Id,
// ProviderId = provider.Id,
// RouteId = tqRoute.Id,
// PathwayId = tqPathway.Id,
// SpecialismId = tqSpecialism.Id
//};
//if (await _tqProviderService.CheckIfTqProviderAlreadyExistsAsync(tqProvider))
//{
// return BadRequest(new BadRequestResponse("A record was not created because a duplicate of the current record already exists."));
//}
//var tqProviderId = await _tqProviderService.CreateTqProvidersAsync(tqProvider);
var tqProviderId = 7;
//return tqProvider != 0 ? Ok() : (ActionResult)BadRequest();
return CreatedAtAction(nameof(GetRegisteredTqProviderInformation), new { tqProviderId }, registerProvider);
}
[HttpPost]
//[Produces("application/json", "multipart/form-data")]
[Route("upload-resultsfile", Name = "UploadResultsFile")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
//[ValidateModel]
public async Task<IActionResult> UploadResultsFile([FromForm]TestFileUpload fileUpload)
{
var provider = await _providerService.GetProviderDetailsByCodeAsync(12345);
var fi = fileUpload;
return Ok();
}
}
public class TestFileUpload
{
public int Id { get; set; }
public IFormFile File { get; set; }
}
} |
using GalaSoft.MvvmLight.CommandWpf;
using MahApps.Metro.Controls;
using Sales.Helpers;
using Sales.Models;
using Sales.Reports;
using Sales.Services;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace Sales.ViewModels.SaleViewModels
{
public class SaleOfferShowViewModel : ValidatableBindableBase
{
MetroWindow _currentWindow;
SaleOfferServices _saleOfferServ = new SaleOfferServices();
SaleOfferCategoryServices _saleOfferCategoryServ = new SaleOfferCategoryServices();
public static int ID
{
get; set;
}
public SaleOfferShowViewModel()
{
_currentWindow = Application.Current.Windows.OfType<MetroWindow>().LastOrDefault();
_selectedSaleOffer = _saleOfferServ.GetSaleOffer(ID);
_saleOfferCategories = new ObservableCollection<SaleOfferCategoryVM>(_saleOfferCategoryServ.GetSaleOfferCategories(ID));
}
private SaleOffer _selectedSaleOffer;
public SaleOffer SelectedSaleOffer
{
get { return _selectedSaleOffer; }
set { SetProperty(ref _selectedSaleOffer, value); }
}
private ObservableCollection<SaleOfferCategoryVM> _saleOfferCategories;
public ObservableCollection<SaleOfferCategoryVM> SaleOfferCategories
{
get { return _saleOfferCategories; }
set { SetProperty(ref _saleOfferCategories, value); }
}
// Show
private RelayCommand _print;
public RelayCommand Print
{
get
{
return _print
?? (_print = new RelayCommand(PrintMethod));
}
}
private void PrintMethod()
{
Mouse.OverrideCursor = Cursors.Wait;
DS ds = new DS();
ds.Sale.Rows.Clear();
int i = 0;
foreach (var item in _saleOfferCategories)
{
ds.Sale.Rows.Add();
ds.Sale[i]["Client"] = _selectedSaleOffer.Client.Name;
ds.Sale[i]["Serial"] = i + 1;
ds.Sale[i]["Category"] = item.Category + " " + item.Company;
ds.Sale[i]["Qty"] = item.Qty;
ds.Sale[i]["Price"] = Math.Round(Convert.ToDecimal(item.PriceAfterDiscount), 2);
ds.Sale[i]["TotalPrice"] = Math.Round(Convert.ToDecimal(item.PriceTotalAfterDiscount), 2);
ds.Sale[i]["BillPrice"] = Math.Round(Convert.ToDecimal(_selectedSaleOffer.PriceAfterDiscount), 2); ;
i++;
}
ReportWindow rpt = new ReportWindow();
SaleOfferReport saleOfferRPT = new SaleOfferReport();
saleOfferRPT.SetDataSource(ds.Tables["Sale"]);
rpt.crv.ViewerCore.ReportSource = saleOfferRPT;
Mouse.OverrideCursor = null;
_currentWindow.Hide();
rpt.ShowDialog();
_currentWindow.ShowDialog();
}
}
}
|
using System;
using Environment;
namespace ActiveAbility
{
public interface IUseAbility
{
void UseAbility();
void PickUpAbility();
void DropAbility(Room room);
int Cooldown { get; set; }
int CurrentCharge { get; set; }
bool CanUseAbility { get; }
Action<int> UpdateCharge { get; set; }
}
} |
using StudyMateLibrary.Attributes;
namespace StudyMateLibrary.Enities
{
public class City : Entity
{
[ForeignKey(typeof(Country))]
public string CountryId { get; set; }
[ForeignKey(typeof(State))]
public int StateId { get; set; }
public string CityName { get; set; }
}
} |
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 Myriad.Models;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
using System.Configuration;
namespace Myriad.Controllers
{
public class MoviesController : Controller
{
private static readonly string _awsAccessKey = ConfigurationManager.AppSettings["AccessId"];
private static readonly string _awsSecretKey = ConfigurationManager.AppSettings["secretKey"];
private static readonly string _bucketName = ConfigurationManager.AppSettings["bucketname"];
private MyriadDbEntities db = new MyriadDbEntities();
public static IList<SelectListItem> GetGender()
{
IList<SelectListItem> _result = new List<SelectListItem>();
_result.Add(new SelectListItem { Value = "1", Text = "Male" });
_result.Add(new SelectListItem { Value = "2", Text = "Female" });
_result.Add(new SelectListItem { Value = "3", Text = "Others" });
return _result;
}
public string UploadAndRetreieveUrl(HttpPostedFileBase file)
{
var additive = DateTime.Now.Millisecond.ToString();
string keyname = Path.GetFileNameWithoutExtension(file.FileName);
try
{
IAmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
{
var request = new PutObjectRequest()
{
BucketName = _bucketName,
CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
//Key = string.Format("UPLOADS/{0}", file.FileName),
Key = string.Format("UPLOADS/{0}", keyname + additive + ".jpg"),
InputStream = file.InputStream//SEND THE FILE STREAM
};
client.PutObject(request);
}
}
catch (Exception ex)
{
}
string ImageUrl = "https://" + "s3-us-west-2.amazonaws.com/myriadposterappharbour/UPLOADS/" + keyname + additive + ".jpg";
return ImageUrl;
}
public List<CheckActorsModel> GetAactorsCheckList()
{
var results = from a in db.Actors
select new
{
a.ActID,
a.Name,
Checked = false
};
var actorsList = new List<CheckActorsModel>();
foreach (var item in results)
{
actorsList.Add(new CheckActorsModel { id = item.ActID, Name = item.Name, isChecked = item.Checked });
}
return actorsList;
}
// GET: Movies
public ActionResult Index()
{
db.SaveChanges();
var movies = db.Movies.Include(m => m.Producer);
var mvModel = new MovieViewModel();
var mvModelList = new List<MovieViewModel>();
foreach (var item in movies)
{
var results = from a in db.Actors
select new
{
a.ActID,
a.Name,
Checked = ((from ab in db.MovieActors
where ((item.MovID == ab.MovID) & (a.ActID == ab.ActID))
select ab).Count() > 0)
};
var actorsList = new List<CheckActorsModel>();
foreach (var item1 in results)
{
actorsList.Add(new CheckActorsModel { id = item1.ActID, Name = item1.Name, isChecked = item1.Checked });
}
mvModelList.Add(new MovieViewModel
{
MovID = item.MovID,
Name = item.Name,
Producer = item.Producer,
Plot = item.Plot,
Poster = item.Poster,
ProID = item.ProID,
ReleaseDate = item.ReleaseDate,
ActorsList = actorsList
});
}
return View(mvModelList);
}
// GET: Movies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
var results = from a in db.Actors
select new
{
a.ActID,
a.Name,
Checked = ((from ab in db.MovieActors
where ((id == ab.MovID) & (a.ActID == ab.ActID))
select ab).Count() > 0)
};
var moviewView = new MovieViewModel();
moviewView.MovID = id.Value;
moviewView.Name = movie.Name;
moviewView.Plot = movie.Plot;
moviewView.Poster = movie.Poster;
moviewView.ProID = movie.ProID;
moviewView.ReleaseDate = movie.ReleaseDate;
moviewView.Producer = movie.Producer;
var actorsList = new List<CheckActorsModel>();
foreach (var item in results)
{
actorsList.Add(new CheckActorsModel { id = item.ActID, Name = item.Name, isChecked = item.Checked });
}
moviewView.ActorsList = actorsList;
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
return View(moviewView);
}
// GET: Movies/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
var results = from a in db.Actors
select new
{
a.ActID,
a.Name,
Checked = ((from ab in db.MovieActors
where ((id == ab.MovID) & (a.ActID == ab.ActID))
select ab).Count() > 0)
};
var moviewView = new MovieViewModel();
moviewView.MovID = id.Value;
moviewView.Name = movie.Name;
moviewView.Plot = movie.Plot;
moviewView.Poster = movie.Poster;
moviewView.ProID = movie.ProID;
moviewView.ReleaseDate = movie.ReleaseDate;
var actorsList = new List<CheckActorsModel>();
foreach (var item in results)
{
actorsList.Add(new CheckActorsModel { id = item.ActID, Name = item.Name, isChecked = item.Checked });
}
moviewView.ActorsList = actorsList;
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
return View(moviewView);
}
// POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MovieViewModel mvModel)
{
var movie = db.Movies.Find(mvModel.MovID);
movie.Name = mvModel.Name;
movie.Plot = mvModel.Plot;
movie.Poster = mvModel.Poster;
movie.ReleaseDate = mvModel.ReleaseDate;
movie.ProID = mvModel.ProID;
if (ModelState.IsValid)
{
foreach (var item in db.MovieActors)
{
if (item.MovID == movie.MovID)
db.Entry(item).State = System.Data.Entity.EntityState.Deleted;
}
foreach (var item in mvModel.ActorsList)
{
if (item.isChecked)
db.MovieActors.Add(new MovieActor() { MovID = movie.MovID, ActID = item.id });
}
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
return View(movie);
}
// GET: Movies/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Movie movie = db.Movies.Find(id);
IEnumerable<MovieActor> movieActor = db.MovieActors.Where(m => m.MovID == id);
foreach (var item in movieActor)
{
db.MovieActors.Remove(item);
}
db.Movies.Remove(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
//[ActionName("CreateActor")]
public PartialViewResult CreateActorPartialView()
{
ActorsViewModels actor = new ActorsViewModels();
Movie movie = new Movie();
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
ViewBag.Sex = new SelectList(MoviesController.GetGender(), "Value", "Text", actor.Sex);
return PartialView("CreateActorPartialView");
}
[HttpPost]
//,ActionName("CreateActor")
public ActionResult CreateActorPartialView(ActorsViewModels actorModel)
{
if (ModelState.IsValid)
{
Actor actor = new Actor();
actor.Name = actorModel.Name;
actor.Sex = (byte)actorModel.Sex;
actor.Bio = actorModel.Bio;
actor.DOB = actorModel.DOB;
actor.MovieActors = actorModel.MovieActors;
db.Actors.Add(actor);
db.SaveChanges();
return Content("Actor Added Successfully");
}
ViewBag.Sex = new SelectList(MoviesController.GetGender(), "Value", "Text", actorModel.Sex);
return View(actorModel);
}
//[ActionName("CreateProducer")]
public PartialViewResult CreateProducerPartialView()
{
Producer pro = new Producer();
ViewBag.Sex = new SelectList(MoviesController.GetGender(), "Value", "Text", pro.Sex);
return PartialView("CreateProducerPartialView");
}
[HttpPost]
//[ActionName("CreateProducer")]
public ActionResult CreateProducerPartialView(ProducerViewModel producerModel)
{
if (ModelState.IsValid)
{
Producer producer = new Producer();
producer.Name = producerModel.Name;
producer.Sex = (byte)producerModel.Sex;
producer.Bio = producerModel.Bio;
producer.DOB = producerModel.DOB;
db.Producers.Add(producer);
db.SaveChanges();
return Content("Producer Added Successfully");
}
ViewBag.Sex = new SelectList(MoviesController.GetGender(), "Value", "Text",producerModel.Sex);
return View(producerModel);
}
//third trial
//ActionName("AddMovie")]
public PartialViewResult CreateMoviesPartialView(int? id)
{
var movieModel = new MovieViewModel();
movieModel.ActorsList = GetAactorsCheckList();
Movie movie = new Movie();
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
return PartialView("CreateMoviesPartialView", movieModel);
}
//fghjhvm
[HttpPost]
//[ActionName("AddMovie")]
public ActionResult CreateMoviesPartialView(MovieViewModel mvModel, List<CheckActorsModel> caModel, HttpPostedFileBase file)
{
var movie = new Movie();
movie.Name = mvModel.Name;
movie.Plot = mvModel.Plot;
movie.ReleaseDate = mvModel.ReleaseDate;
movie.ProID = mvModel.ProID;
mvModel.ActorsList = caModel;
if (ModelState.IsValid)
{
//movie.Poster = file.ToString();
var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg)
//var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
//if (ext == ".jpg") //check what type of extension
//{
string keyname = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
// string myfile = name + "_" + movie.MovID + ext; //appending the name with id
// // store the file inside ~/project folder(Img)
// var path = Path.Combine(Server.MapPath("~/App_Data/img"), myfile);
// //var path = Path.Combine("https://drive.google.com/drive/folders/0B0iUAcFc1a98Ni1wMGVIdGhGSlU",myfile);
// movie.Poster = path;
// file.SaveAs(path);
//}
//else
//{
// ViewBag.message = "Please choose only Image file";
//}
try
{
IAmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
{
var request = new PutObjectRequest()
{
BucketName = _bucketName,
CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
Key = string.Format("UPLOADS/{0}", file.FileName),
InputStream = file.InputStream//SEND THE FILE STREAM
};
client.PutObject(request);
}
}
catch (Exception ex)
{
}
movie.Poster = "https://"+"s3-us-west-2.amazonaws.com/myriadposterappharbour/UPLOADS/" + keyname + ".jpg";
db.Movies.Add(movie);
if (mvModel.ActorsList != null)
{
foreach (var item in mvModel.ActorsList)
{
if (item.isChecked)
db.MovieActors.Add(new MovieActor() { MovID = movie.MovID, ActID = item.id });
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
CreateAll c = new CreateAll();
c.movieModel = mvModel;
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
TempData["doc"] = c;
return RedirectToAction("AddToCatalogue",c);
//return View(mvModel);
}
//[ActionName("CreateCatalogue")]
public ActionResult CreateAllAction()
{
var movieModel = new MovieViewModel();
movieModel.ActorsList = GetAactorsCheckList();
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movieModel.ProID);
return View(movieModel);
}
[HttpPost]
//[ActionName("CreateCatalogue")]
public ActionResult CreateAllAction(MovieViewModel mvModel,int ProID, List<CheckActorsModel> caModel, HttpPostedFileBase file)
{
var movie = new Movie();
movie.Name = mvModel.Name;
movie.Plot = mvModel.Plot;
movie.Producer = mvModel.Producer;
movie.ReleaseDate = mvModel.ReleaseDate;
movie.ProID = mvModel.ProID = ProID;
mvModel.ActorsList = caModel;
if (ModelState.IsValid)
{
movie.Poster = UploadAndRetreieveUrl(file);
db.Movies.Add(movie);
if (mvModel.ActorsList != null)
{
foreach (var item in mvModel.ActorsList)
{
if (item.isChecked)
db.MovieActors.Add(new MovieActor() { MovID = movie.MovID, ActID = item.id });
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", movie.ProID);
return View(mvModel);
}
//[ActionName("CreateEverything")]
public ActionResult AddToCatalogue()
{
if (TempData["doc"] != null)
{
CreateAll newC = (CreateAll) TempData["doc"];
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", newC.movieModel.ProID);
return View(newC);
}
var model = new CreateAll();
model.actor = new Actor();
model.movieModel = new MovieViewModel();
model.producer = new Producer();
model.movieModel.ActorsList = GetAactorsCheckList();
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", model.movieModel.ProID);
return View(model);
}
[HttpPost]
//[ActionName("CreateEverything")]
public ActionResult AddToCatalogue(CreateAll c)
{
var model = new CreateAll();
model.actor = c.actor;
model.movieModel = c.movieModel;
model.producer = c.producer;
model.movieModel.ActorsList = GetAactorsCheckList();
ViewBag.ProID = new SelectList(db.Producers, "ProID", "Name", model.movieModel.ProID);
return View(model);
}
public ActionResult CheckActorsPartialView(MovieViewModel m)
{
var actorsList = new List<CheckActorsModel>();
actorsList = GetAactorsCheckList();
return View(actorsList);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Tasks : MonoBehaviour
{
//Script duoc dung boi cac toggle Task
private int id;
private string t;//Ten cong viec
private int completed;//hoan thanh hay chua 0:chua hoan thanh, 1:da hoan thanh
private int statBonus;
public GameObject gc;
public GameObject parti;
public int daCong;//cong viec nay sau khi hoan thanh da cong chi so cho nguoi choi hay chua 0:chua, 1:roi
public int Id { get => id; set => id = value; }
public string T { get => t; set => t = value; }
public int StatBonus { get => statBonus; set => statBonus = value; }
public int Completed { get => completed; set => completed = value; }
private void Start()
{
gc = GameObject.FindGameObjectWithTag("GameController");
if (Completed == 1)
{
gameObject.GetComponent<Toggle>().isOn = true;
gameObject.GetComponent<Toggle>().interactable = false;
}
}
public void CheckedClick()
{
if (gameObject.GetComponent<Toggle>().isOn)
{
Completed = 1;
gameObject.GetComponent<Toggle>().interactable = false;
PlayerPrefs.SetInt("completed" + Id.ToString() + "tk" + PlayerPrefs.GetInt("idTKCurrent").ToString(), 1);
Vector2 logPos = new Vector2(200, 200 - Id * 40);//vi tri log
if (daCong == 0)
{
daCong = 1;
PlayerPrefs.SetInt("daCong" + Id.ToString() + "tk" + PlayerPrefs.GetInt("idTKCurrent").ToString(), 1);
gc.GetComponent<GameController>().stat.AddStat(statBonus, 1);
Vector3 pos = new Vector3(0, 0, -4.7f);
gc.GetComponent<GameController>().TaoHieuUng(parti, 1.5f, pos);
}
}
}
public void DeleteTask()
{
int demCV = PlayerPrefs.GetInt("demCV" + "tk" + PlayerPrefs.GetInt("idTKCurrent").ToString());
if (Id == demCV)
{
demCV--;
PlayerPrefs.SetInt("demCV" + "tk" + PlayerPrefs.GetInt("idTKCurrent").ToString(), demCV);
Destroy(gameObject);
}
else
gc.GetComponent<TaskController>().XoaTheoId(Id);
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EntMob.Models;
namespace EntMob.DAL
{
public interface IHumidityRepository
{
Task<Humidity> AddHumidity(Humidity humidity);
Task<List<Humidity>> GetHumiditiesForSession(Session session);
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace SuperMario.Entities
{
public abstract class MovingAnimatedEntity : MovingEntity
{
int animationDelayInTicks;
long lastGameTime;
protected MovingAnimatedEntity(Vector2 screenLocation, int animationDelay) : base(screenLocation)
{
animationDelayInTicks = animationDelay;
EntityXDirection = Direction.Right;
}
public override void Draw(SpriteBatch spriteBatch)
{
if (CurrentSprite == null)
CurrentSprite = FirstSprite;
CurrentSprite.Draw(ScreenLocation, spriteBatch);
}
public override void Update(GameTime gameTime)
{
if (lastGameTime == 0)
lastGameTime = gameTime.TotalGameTime.Ticks;
if (gameTime.TotalGameTime.Ticks - lastGameTime > animationDelayInTicks)
{
lastGameTime = gameTime.TotalGameTime.Ticks;
CurrentSprite = NextSprite;
}
base.Update(gameTime);
}
public abstract ISprite NextSprite { get; }
public abstract ISprite FirstSprite { get; }
}
}
|
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using Aria.Core.Resources;
using OpenTK.Graphics.OpenGL;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
namespace Aria.Core.Graphics
{
public class SpriteSheet : Resource
{
// List holding the sprites belonging to this sprite sheet.
private IList<Texture2D> _sprites;
/// <summary>
/// Constructor: Create a new sprite sheet object from passed image.
/// </summary>
/// <param name="path"></param>
/// <param name="numFrames"></param>
public SpriteSheet(string path, int numFrames) : base("sprite_sheet")
{
CreateSpriteSheet(path, numFrames);
}
/// <summary>
/// Constructor: Create a new named sprite sheet object from passed image.
/// </summary>
/// <param name="path"></param>
/// <param name="numFrames"></param>
/// <param name="name"></param>
public SpriteSheet(string path, int numFrames, string name) : base(name)
{
CreateSpriteSheet(path, numFrames);
}
/// <summary>
/// The height of each frame in the sprite sheet in pixels.
/// </summary>
public int FrameHeight { get; private set; }
/// <summary>
/// The width of each frame in the sprite sheet in pixels.
/// </summary>
public int FrameWidth { get; private set; }
/// <summary>
/// The number of frames in this sprite sheet.
/// </summary>
public int NumFrames { get; private set; }
/// <summary>
/// Get the specified frame from this sprite sheet.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Texture2D this[int value] => _sprites[value];
/// <summary>
/// Helper method to create the sprite sheet.
/// </summary>
/// <param name="path"></param>
/// <param name="numFrames"></param>
private void CreateSpriteSheet(string path, int numFrames)
{
_sprites = new List<Texture2D>();
// Using system drawing to help with disk loading.
var bitmap = new Bitmap(path);
FrameWidth = bitmap.Width/numFrames;
FrameHeight = bitmap.Height;
NumFrames = numFrames;
// Create each texture for the sprite sheet.
for (var i = 0; i < numFrames; i++)
{
// Cut the image for the current sprite.
var bmp = bitmap.Clone(new Rectangle(i*FrameWidth, 0, FrameWidth, FrameHeight), bitmap.PixelFormat);
// Grab the rectangle for the current sprite frame.
var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Generate unique texture ID.
var tex = GL.GenTexture();
// Bind texture to ID.
GL.BindTexture(TextureTarget.Texture2D, tex);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
bmp.UnlockBits(data);
// Set texture filters.
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter,
(int) TextureMinFilter.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter,
(int) TextureMagFilter.Nearest);
_sprites.Add(new Texture2D(tex, FrameWidth, FrameHeight, Name + "_" + i));
}
}
}
} |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace RU.Tinkoff.Acquiring.Sdk {
// Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']"
[global::Android.Runtime.Register ("ru/tinkoff/acquiring/sdk/PayFormActivity", DoNotGenerateAcw=true)]
public sealed partial class PayFormActivity : global::Android.Support.V7.App.AppCompatActivity {
// Metadata.xml XPath field reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/field[@name='API_ERROR_NO_CUSTOMER']"
[Register ("API_ERROR_NO_CUSTOMER")]
public const string ApiErrorNoCustomer = (string) "7";
// Metadata.xml XPath field reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/field[@name='RESULT_ERROR']"
[Register ("RESULT_ERROR")]
public const int ResultError = (int) 500;
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("ru/tinkoff/acquiring/sdk/PayFormActivity", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (PayFormActivity); }
}
internal PayFormActivity (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/constructor[@name='PayFormActivity' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public unsafe PayFormActivity ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
return;
try {
if (((object) this).GetType () != typeof (PayFormActivity)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor);
} finally {
}
}
static IntPtr id_isCardChooseEnable;
public unsafe bool IsCardChooseEnable {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/method[@name='isCardChooseEnable' and count(parameter)=0]"
[Register ("isCardChooseEnable", "()Z", "GetIsCardChooseEnableHandler")]
get {
if (id_isCardChooseEnable == IntPtr.Zero)
id_isCardChooseEnable = JNIEnv.GetMethodID (class_ref, "isCardChooseEnable", "()Z");
try {
return JNIEnv.CallBooleanMethod (((global::Java.Lang.Object) this).Handle, id_isCardChooseEnable);
} finally {
}
}
}
static IntPtr id_dispatchResult_ILandroid_content_Intent_Lru_tinkoff_acquiring_sdk_OnPaymentListener_;
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/method[@name='dispatchResult' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='android.content.Intent'] and parameter[3][@type='ru.tinkoff.acquiring.sdk.OnPaymentListener']]"
[Register ("dispatchResult", "(ILandroid/content/Intent;Lru/tinkoff/acquiring/sdk/OnPaymentListener;)V", "")]
public static unsafe void DispatchResult (int p0, global::Android.Content.Intent p1, global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener p2)
{
if (id_dispatchResult_ILandroid_content_Intent_Lru_tinkoff_acquiring_sdk_OnPaymentListener_ == IntPtr.Zero)
id_dispatchResult_ILandroid_content_Intent_Lru_tinkoff_acquiring_sdk_OnPaymentListener_ = JNIEnv.GetStaticMethodID (class_ref, "dispatchResult", "(ILandroid/content/Intent;Lru/tinkoff/acquiring/sdk/OnPaymentListener;)V");
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
JNIEnv.CallStaticVoidMethod (class_ref, id_dispatchResult_ILandroid_content_Intent_Lru_tinkoff_acquiring_sdk_OnPaymentListener_, __args);
} finally {
}
}
static IntPtr id_init_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/method[@name='init' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]"
[Register ("init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lru/tinkoff/acquiring/sdk/PayFormStarter;", "")]
public static unsafe global::RU.Tinkoff.Acquiring.Sdk.PayFormStarter Init (string p0, string p1, string p2)
{
if (id_init_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_init_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lru/tinkoff/acquiring/sdk/PayFormStarter;");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p2 = JNIEnv.NewString (p2);
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (native_p1);
__args [2] = new JValue (native_p2);
global::RU.Tinkoff.Acquiring.Sdk.PayFormStarter __ret = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.PayFormStarter> (JNIEnv.CallStaticObjectMethod (class_ref, id_init_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
}
}
static IntPtr id_onNoNetwork;
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='PayFormActivity']/method[@name='onNoNetwork' and count(parameter)=0]"
[Register ("onNoNetwork", "()V", "")]
public unsafe void OnNoNetwork ()
{
if (id_onNoNetwork == IntPtr.Zero)
id_onNoNetwork = JNIEnv.GetMethodID (class_ref, "onNoNetwork", "()V");
try {
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onNoNetwork);
} finally {
}
}
}
}
|
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.Speech.Synthesis;
using System.IO;
namespace TextToSpeech
{
public partial class Form1 : Form
{
SpeechSynthesizer reader;
public Form1()
{
InitializeComponent();
pauseButton.Enabled = false;
reader = new SpeechSynthesizer();
}
private void startButton_Click(object sender, EventArgs e)
{
play();
}
//event handler
void reader_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
startButton.Text = "Start";
pauseButton.Enabled = false;
}
private void pauseButton_Click(object sender, EventArgs e)
{
if (reader != null)
{
if (reader.State == SynthesizerState.Paused)
{
reader.Resume();
pauseButton.Enabled = true;
pauseButton.Text = "Pause";
}
else if (reader.State == SynthesizerState.Speaking)
{
reader.Pause();
pauseButton.Enabled = true;
pauseButton.Text = "Resume";
}
}
}
private void play()
{
reader.Dispose();
if (mainTextBox.Text != "")
{
startButton.Text = "Replay";
pauseButton.Text = "Pause";
reader = new SpeechSynthesizer();
reader.SpeakAsync(mainTextBox.Text.ToString().Trim());
pauseButton.Enabled = true;
reader.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(reader_SpeakCompleted);
}
else
{
MessageBox.Show("Please enter some text in the textbox", "Message", MessageBoxButtons.OK);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppointmentManagement.UI.DTOs
{
public class OrderAsnDto
{
public Guid OrderAsnHeaderID { get; set; }
public string OrderAsnNumber { get; set; }
public DateTime OrderAsnDate { get; set; }
public double TotalPackage { get; set; }
public double TotalCHW { get; set; }
public string WarehouseDescription { get; set; }
public string ContainerTypeDescription { get; set; }
public bool IsConfirmed { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using ErrorLog;
using Pronto.Common;
namespace Pronto
{
public partial class Search : Form
{
DataTable dt;
int selectedRootNo = -1;
ErrorLog.Logger errorLog;
ComboBoxData cmbData;
LoginType curmode;
public Search(ErrorLog.Logger Log, ComboBoxData comboBoxData, LoginType CurMode)
{
InitializeComponent();
errorLog = Log;
cmbData = comboBoxData;
curmode = CurMode;
this.Text = this.Text + " " + CurMode.ToString();
}
public int SelectedRootNo
{
get
{
return selectedRootNo;
}
}
private void SearchBtn_Click(object sender, EventArgs e)
{
string query = "";
List<string> paramList = new List<string>();
if (!string.IsNullOrEmpty(driverNameCmb.Text))
{
paramList.Add(String.Format(" DriverName LIKE '%{0}%'", driverNameCmb.Text));
}
if (!string.IsNullOrEmpty(TruckCombo.Text))
{
paramList.Add(String.Format(" TruckId LIKE '%{0}%'", TruckCombo.Text));
}
if (!string.IsNullOrEmpty(HelperCombo.Text))
{
paramList.Add(String.Format(" HELPERS LIKE '%{0}%'", HelperCombo.Text));
}
if (!string.IsNullOrEmpty(CustomerCombo.Text))
{
paramList.Add(String.Format(" Customers LIKE '%{0}%'", CustomerCombo.Text));
}
if (!string.IsNullOrEmpty(ServiceCombo.Text))
{
paramList.Add(String.Format(" Services LIKE '%{0}%'", ServiceCombo.Text));
}
if (!string.IsNullOrEmpty(ClientNameTxt.Text))
{
paramList.Add(String.Format(" ClientName LIKE '%{0}%'", ClientNameTxt.Text));
}
if (!string.IsNullOrEmpty(ClientPhTxt.Text))
{
paramList.Add(String.Format(" ClientPH LIKE '%{0}%'", ClientPhTxt.Text));
}
if (!string.IsNullOrEmpty(ClientCityTxt.Text))
{
paramList.Add(String.Format(" ClientCity LIKE '%{0}%'", ClientCityTxt.Text));
}
if (!string.IsNullOrEmpty(ClientZipTxt.Text))
{
paramList.Add(String.Format(" ClientZipCode LIKE '%{0}%'", ClientZipTxt.Text));
}
if (!string.IsNullOrEmpty(PtsIdTxt.Text))
{
paramList.Add(String.Format(" PtsId LIKE '%{0}%'", PtsIdTxt.Text));
}
if (paramList.Count > 0)
{ query = " WHERE " + string.Join(" AND ", paramList); }
if (!string.IsNullOrEmpty(RootNoCombo.Text))
{
dt = Pronto.Common.DataAccessFactory.GetResultForRoot(RootNoCombo.Text);
}
else
{
dt = Pronto.Common.DataAccessFactory.GetSearchResult(dateTimePicker1.Value, dateTimePicker2.Value, query);
}
dataGridView1.DataSource = dt;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoResizeColumns();
}
private void SearchPanel_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void tableLayoutPanel2_Paint(object sender, PaintEventArgs e)
{
}
private void helpercmb1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void Search_Load(object sender, EventArgs e)
{
string CSVPath = ConfigurationManager.AppSettings["CSVFilePath"];
driverNameCmb.DataSource = cmbData.AllDriverName;
driverNameCmb.DisplayMember = "DriverName";
TruckCombo.DataSource = cmbData.AllTruck;
TruckCombo.DisplayMember = "TruckId";
HelperCombo.DataSource = cmbData.AllHelper;
HelperCombo.DisplayMember = "HelperName";
CustomerCombo.DataSource = cmbData.AllCustomer;
CustomerCombo.DisplayMember = "CustomerName";
ServiceCombo.DataSource = cmbData.AllService;
ServiceCombo.DisplayMember = "ServiceType";
RootNoCombo.DataSource = cmbData.AllRoodNos;
//RootNoCombo.SelectedValue = "";
driverNameCmb.Text = "";
TruckCombo.Text = "";
HelperCombo.Text = "";
CustomerCombo.Text = "";
ServiceCombo.Text = "";
dataGridView1.AllowUserToDeleteRows = curmode == LoginType.Admin ? true : false;
}
private void CustomerCombo_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void helperLabel1_Click(object sender, EventArgs e)
{
}
private void driverNameCmb_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (curmode == LoginType.User)
{ return; }
if (dt != null && dt.Rows.Count > 0)
{
DataRow rw = dt.Rows[e.RowIndex];
selectedRootNo = (int)rw["RouteNo"];
}
this.DialogResult = DialogResult.OK;
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void exportToExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
this.Cursor = Cursors.WaitCursor;
if (dt != null)
{
Pronto.Common.ExcelImport.ExportExcel(dt);
}
else
{
MessageBox.Show("Please Select Search", Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
errorLog.LogError(ex);
}
finally
{
this.Cursor = Cursors.Default;
}
}
private void exportToPdfToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (dt != null)
{
SaveFileDialog svd = new SaveFileDialog();
svd.Filter = "Pdf Files | *.pdf";
svd.DefaultExt = "pdf";
svd.Title = "Select pdf file location";
DialogResult dlg = svd.ShowDialog();
if (dlg == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
Pronto.Common.ExcelImport.ExportToPdf(dt, svd.FileName);
MessageBox.Show(string.Format("Pdf file created at '{0}'", svd.FileName), Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{ MessageBox.Show("Please Select Search", Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
errorLog.LogError(ex);
}
finally
{
this.Cursor = Cursors.Default;
}
}
private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
try
{
DialogResult dlg = MessageBox.Show("Do You want to delete the Selected row", Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlg == DialogResult.Yes)
{
e.Cancel = false;
var rowv = (DataRowView)(e.Row.DataBoundItem);
DataRow rw = rowv.Row;
int RootNo = (int)rw["RouteNo"];
DataAccessFactory.DeleteRoute(RootNo);
}
else
{
e.Cancel = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Pronto.Utility.ProjectPaths.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
errorLog.LogError(ex);
e.Cancel = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
driverNameCmb.Text = "";
TruckCombo.Text = "";
HelperCombo.Text = "";
CustomerCombo.Text = "";
ServiceCombo.Text = "";
ClientNameTxt.Text = "";
ClientPhTxt.Text = "";
PtsIdTxt.Text = "";
ClientCityTxt.Text = "";
ClientZipTxt.Text = "";
RootNoCombo.Text = "";
ServiceCombo.Text = "";
dateTimePicker1.ResetText();
dateTimePicker2.ResetText();
dt = new System.Data.DataTable();
dataGridView1.DataSource = dt;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Software_Engineering.Models;
using System.Net;
using System.Data.Entity;
using System.Data.Entity.Validation;
using Microsoft.Reporting.WebForms;
namespace Software_Engineering.Controllers
{
public class CarsController : Controller
{
Software_EngineeringEntities1 db = new Software_EngineeringEntities1();
// GET: Cars
public bool isModified1 = false;
public bool isModified2 = false;
public bool isModified3 = false;
public bool isModified4 = false;
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Index()
{
var car = db.Cars.Include(q => q.Customer);
car = db.Cars.Include(q => q.Tracker);
car=db.Cars.Include(q => q.Insurance);
return View(db.Cars.ToList());
}
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Renew_List()
{
DateTime now = DateTime.Now;
DateTime nowPlus30Days = now.AddDays(30);
var car = db.Cars.Include(q => q.Customer);
car = db.Cars.Include(q => q.Tracker);
car = db.Cars.Include(q => q.Insurance);
var viewModel = new ViewModel
{
Sold = db.Cars.Where(q => q.insExpiry.Value <= nowPlus30Days).OrderBy(q=>q.insExpiry.Value).ToList(),
UnSold = db.Cars.Where(q => q.traExpiry.Value <= nowPlus30Days).OrderBy(q => q.traExpiry.Value).ToList()
};
return View(viewModel);
}
public int TotalExpiries()
{
DateTime now = DateTime.Now;
DateTime nowPlus30Days = now.AddDays(30);
var car = db.Cars.Include(q => q.Customer);
car = db.Cars.Include(q => q.Tracker);
car = db.Cars.Include(q => q.Insurance);
var total = db.Cars.Where(q => q.insExpiry.Value <= nowPlus30Days).OrderBy(q => q.insExpiry.Value).ToList().Count + db.Cars.Where(q => q.traExpiry.Value <= nowPlus30Days).OrderBy(q => q.traExpiry.Value).ToList().Count;
return total;
}
//[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Cars()
{
var car = db.Cars.Include(q => q.Customer);
car = db.Cars.Include(q => q.Tracker);
car = db.Cars.Include(q => q.Insurance);
car=db.Cars.Where(q=>q.soldDate==null).OrderBy(q=>q.Make);
return View(car.ToList());
}
//[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Home()
{
return View();
}
[Authorize(Roles = "Finance Manager")]
public ActionResult Report(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
LocalReport localreport= new LocalReport();
localreport.ReportPath = Server.MapPath("~/Report/Rdlc/Cars.rdlc");
int custid = Convert.ToInt32(db.Cars.Where(x => x.Id == id).Select(x => x.customerId).First());
int insuid = Convert.ToInt32(db.Cars.Where(x => x.Id == id).Select(x => x.insuranceId).First());
int tracid = Convert.ToInt32(db.Cars.Where(x => x.Id == id).Select(x => x.trackerId).First());
ReportDataSource reportdatasource = new ReportDataSource();
reportdatasource.Name = "DataSet1";
reportdatasource.Value = db.Cars.Where(x=> x.Id==id).ToList();
localreport.DataSources.Add(reportdatasource);
ReportDataSource reportdatasource2 = new ReportDataSource();
reportdatasource2.Name = "DataSet2";
reportdatasource2.Value = db.Customers.Where(x => x.Id == custid).ToList();
localreport.DataSources.Add(reportdatasource2);
ReportDataSource reportdatasource3 = new ReportDataSource();
reportdatasource3.Name = "DataSet3";
reportdatasource3.Value = db.Insurances.Where(x => x.Id == insuid).ToList();
localreport.DataSources.Add(reportdatasource3);
ReportDataSource reportdatasource4 = new ReportDataSource();
reportdatasource4.Name = "DataSet4";
reportdatasource4.Value = db.Trackers.Where(x => x.Id == tracid).ToList();
localreport.DataSources.Add(reportdatasource4);
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension = "pdf";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = localreport.Render(reportType, "", out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
Response.AddHeader("content-disposition", "attachment; filename=Urls." + fileNameExtension);
return File(renderedBytes, fileNameExtension);
return View(car);
}
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Sell()
{
var car = db.Cars.Include(q => q.Customer);
car = db.Cars.Include(q => q.Tracker);
car = db.Cars.Include(q => q.Insurance);
var viewModel = new ViewModel
{
Sold = db.Cars.Where(x => x.soldDate != null).ToList(),
UnSold = db.Cars.Where(x => x.soldDate == null).ToList()
};
return View(viewModel);
}
// GET: Cars/Details/5
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// GET: Cars/Create
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Create()
{
ViewBag.customerId = new SelectList(db.Customers, "Id", "Name");
ViewBag.trackerId= new SelectList(db.Trackers,"Id","Company");
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company");
return View();
}
public Closing Update(Closing closing, long diff,bool newl)
{
//bool updated = false;
var query2 = from m in db.Closings
where m.Month < closing.Month && m.Year==closing.Year || m.Year < closing.Year
orderby m.Month, m.Year
select m;
if (newl == true)
{
foreach (var item in query2.ToList())
{
if ((item.Month == closing.Month - 1 && item.Year == closing.Year) || (item.Month == 12 && item.Year == closing.Year - 1))
{
closing.ClosingBalance += item.ClosingBalance;
//updated = true;
break;
}
}
}
query2 = from m in db.Closings
where (m.Month > closing.Month && m.Year==closing.Year) || m.Year > closing.Year
orderby m.Month, m.Year
select m;
foreach (var item in query2.ToList())
{
if ((item.Month > closing.Month && item.Year == closing.Year) || item.Year > closing.Year)
{
item.ClosingBalance += diff;
db.Entry(item).State = EntityState.Modified;
}
}
return closing;
}
public Closing CUpdate(Car car, Closing closing,bool newl)
{
var buyprice = car.buyingPrice;
long sellprice = 0;
long mcost = 0;
if (car.soldDate != null && car.soldDate.Value.Month == closing.Month && car.soldDate.Value.Year == closing.Year)
{
sellprice = car.sellingPrice.Value;
mcost = car.maintainanceCost.Value;
closing.ClosingBalance += car.sellingPrice - car.maintainanceCost;
}
else if (car.soldDate != null)
{
NewSell(car);
}
var diff = sellprice - buyprice - mcost;
//bool updated = false;
closing = Update(closing, diff,newl);
return closing;
}
// POST: Cars/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Create([Bind(Exclude = "image1,image2,image3,image4")]Car car,HttpPostedFileBase image1, HttpPostedFileBase image2, HttpPostedFileBase image3, HttpPostedFileBase image4)
{
if (ModelState.IsValid)
{
if (car.trackerId != null && car.soldDate!=null)
{
car.traExpiry = car.soldDate;
car.traExpiry.Value.AddYears(1);
}
if (car.insuranceId != null && car.soldDate != null)
{
car.insExpiry = car.soldDate;
car.insExpiry.Value.AddYears(1);
}
var query = from m in db.Closings where m.Month == car.purchasedDate.Month && m.Year == car.purchasedDate.Year select m;
var data = query.ToList();
Closing closing = new Closing();
if (data.Count == 0)
{
closing.Month = car.purchasedDate.Month;
closing.Year = car.purchasedDate.Year;
closing.ClosingBalance = 0 - car.buyingPrice;
closing = CUpdate(car, closing, true);
db.Closings.Add(closing);
}
else
{
closing = data[0];
closing.ClosingBalance -= car.buyingPrice;
closing = CUpdate(car, closing, false);
db.Entry(closing).State = EntityState.Modified;
}
if (image1 != null)
{
car.Image = new byte[image1.ContentLength];
image1.InputStream.Read(car.Image, 0, image1.ContentLength);
}
if (image2 != null)
{
car.Image2 = new byte[image2.ContentLength];
image2.InputStream.Read(car.Image2, 0, image2.ContentLength);
}
if (image3 != null)
{
car.Image3 = new byte[image3.ContentLength];
image3.InputStream.Read(car.Image3, 0, image3.ContentLength);
}
if (image4 != null)
{
car.Image4 = new byte[image4.ContentLength];
image4.InputStream.Read(car.Image4, 0, image4.ContentLength);
}
//cagtegory.SecretCode = GenerateSecretCode();
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.customerId = new SelectList(db.Customers, "Id", "Name", car.customerId);
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company",car.trackerId);
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company",car.insuranceId);
return View(car);
}
// GET: Cars/Edit/5
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
ViewBag.customerId = new SelectList(db.Customers, "Id", "Name", car.customerId);
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company", car.trackerId);
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company", car.insuranceId);
return View(car);
}
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult RenewInsurance(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
Customer customer = db.Customers.Find(car.customerId);
if (car == null || customer==null)
{
return HttpNotFound();
}
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company", car.insuranceId);
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult RenewInsurance(Car car)
{
if (ModelState.IsValid)
{
var carl = db.Cars.Find(car.Id);
carl.insExpiry = car.insExpiry;
db.Entry(carl).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Renew_List");
}
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company", car.insuranceId);
return View(car);
}
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult RenewTracker(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
Customer customer = db.Customers.Find(car.customerId);
if (car == null || customer == null)
{
return HttpNotFound();
}
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company", car.trackerId);
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult RenewTracker(Car car)
{
if (ModelState.IsValid)
{
var carl = db.Cars.Find(car.Id);
carl.traExpiry = car.traExpiry;
db.Entry(carl).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Renew_List");
}
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company", car.trackerId);
return View(car);
}
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult SellCar(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
ViewBag.customerId = new SelectList(db.Customers, "Id", "Name", car.customerId);
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company", car.trackerId);
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company", car.insuranceId);
return View(car);
}
public Closing NewSell(Car car)
{
var closing = new Closing();
closing.Month = car.soldDate.Value.Month;
closing.Year = car.soldDate.Value.Year;
var query = from m in db.Closings
where m.Month == closing.Month && m.Year == closing.Year
select m;
var result = query.ToList();
long diff = car.sellingPrice.Value - car.maintainanceCost.Value;
if (result.Count != 0)
{
closing = result[0];
closing.ClosingBalance += car.sellingPrice-car.maintainanceCost;
closing = Update(closing, diff, false);
db.Entry(closing).State = EntityState.Modified;
}
else
{
closing.ClosingBalance = 0 + car.sellingPrice-car.maintainanceCost;
closing = Update(closing, diff, true);
db.Closings.Add(closing);
}
return closing;
}
public Closing NewPurchase(Car car)
{
var closing = new Closing();
closing.Month = car.purchasedDate.Month;
closing.Year = car.purchasedDate.Year;
var query = from m in db.Closings
where m.Month == closing.Month && m.Year == closing.Year
select m;
var result = query.ToList();
long diff = -car.buyingPrice;
if (result.Count != 0)
{
closing = result[0];
closing.ClosingBalance -= car.buyingPrice;
closing = Update(closing, diff, false);
db.Entry(closing).State = EntityState.Modified;
}
else
{
closing.ClosingBalance = 0 - car.buyingPrice;
closing = Update(closing, diff, true);
db.Closings.Add(closing);
}
return closing;
}
// POST: Cars/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult Edit([Bind(Exclude = "image1,image2,image3,image4,modified1,modified2,modified3,modified4")]Car car,HttpPostedFileBase image1, HttpPostedFileBase image2, HttpPostedFileBase image3, HttpPostedFileBase image4,bool modified1, bool modified2, bool modified3, bool modified4)
{
if (ModelState.IsValid)
{
if (car.traExpiry == null && car.trackerId != null && car.soldDate != null)
{
car.traExpiry = car.soldDate;
car.traExpiry.Value.AddYears(1);
}
if (car.insExpiry == null && car.insuranceId != null && car.soldDate != null)
{
car.insExpiry = car.soldDate;
car.insExpiry.Value.AddYears(1);
}
var carl = db.Cars.Find(car.Id);
var sDate = db.Cars.Find(car.Id).soldDate;
var pDate = db.Cars.Find(car.Id).purchasedDate;
if (car.soldDate != sDate || car.sellingPrice != carl.sellingPrice || car.maintainanceCost != carl.maintainanceCost)
{
var query = from m in db.Closings
where m.Month == sDate.Value.Month && m.Year == sDate.Value.Year
select m;
if (query.ToList().Count > 0)
{
var result = query.ToList()[0];
result.ClosingBalance -= carl.sellingPrice;
result.ClosingBalance += carl.maintainanceCost;
result=Update(result, carl.maintainanceCost.Value - carl.sellingPrice.Value, false);
db.Entry(result).State = EntityState.Modified;
}
if (car.soldDate != null)
{
NewSell(car);
}
}
if (car.purchasedDate != pDate || car.buyingPrice != carl.buyingPrice)
{
var query = from m in db.Closings
where m.Month == pDate.Month && m.Year == pDate.Year
select m;
if (query.ToList().Count > 0)
{
var result = query.ToList()[0];
result.ClosingBalance += carl.buyingPrice;
result=Update(result, carl.buyingPrice, false);
db.Entry(result).State = EntityState.Modified;
}
NewPurchase(car);
}
if (image1 != null)
{
car.Image = new byte[image1.ContentLength];
image1.InputStream.Read(car.Image, 0, image1.ContentLength);
}
if (image2 != null)
{
car.Image2 = new byte[image2.ContentLength];
image2.InputStream.Read(car.Image2, 0, image2.ContentLength);
}
if (image3 != null)
{
car.Image3 = new byte[image3.ContentLength];
image3.InputStream.Read(car.Image3, 0, image3.ContentLength);
}
if (image4 != null)
{
car.Image4 = new byte[image4.ContentLength];
image4.InputStream.Read(car.Image4, 0, image4.ContentLength);
}
if (image1 == null)
{
car.Image = db.Cars.Where(i => i.Id == car.Id).Select(i => i.Image).ToList()[0];
}
if (image2 == null)
{
car.Image2 = db.Cars.Where(i => i.Id == car.Id).Select(i => i.Image2).ToList()[0];
}
if (image3 == null)
{
car.Image3 = db.Cars.Where(i => i.Id == car.Id).Select(i => i.Image3).ToList()[0];
}
if (image4 == null)
{
car.Image4 = db.Cars.Where(i => i.Id == car.Id).Select(i => i.Image4).ToList()[0];
}
if (modified1 == true)
{
car.Image = null;
}
if (modified2 == true)
{
car.Image2 = null;
}
if (modified3 == true)
{
car.Image3 = null;
}
if (modified4 == true)
{
car.Image4 = null;
}
var card = db.Cars.Find(car.Id);
db.Entry(card).State = EntityState.Detached;
db.Entry(car).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.customerId = new SelectList(db.Customers, "Id", "Name", car.customerId);
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company", car.trackerId);
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company", car.insuranceId);
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult SellCar([Bind(Include = "Id,Model,Make,Mileage,Year,CC,buyingPrice,sellingPrice,maintainanceCost,Condition,Imported,ownerName,purchasedDate,soldDate,registerationNo,customerId,trackerId,InsuranceId")] Car car)
{
if (ModelState.IsValid)
{
if (car.traExpiry == null && car.trackerId != null && car.soldDate != null)
{
car.traExpiry = car.soldDate;
car.traExpiry.Value.AddYears(1);
}
if (car.insExpiry == null && car.insuranceId != null && car.soldDate != null)
{
car.insExpiry = car.soldDate;
car.insExpiry.Value.AddYears(1);
}
var carl = db.Cars.Find(car.Id);
var sDate = db.Cars.Find(car.Id).soldDate;
if (car.soldDate != sDate || car.sellingPrice != carl.sellingPrice || car.maintainanceCost != carl.maintainanceCost)
{
var query = from m in db.Closings
where m.Month == sDate.Value.Month && m.Year == sDate.Value.Year
select m;
if (query.ToList().Count > 0)
{
var result = query.ToList()[0];
result.ClosingBalance -= carl.sellingPrice;
result.ClosingBalance += carl.maintainanceCost;
result=Update(result, carl.maintainanceCost.Value - carl.sellingPrice.Value, false);
db.Entry(result).State = EntityState.Modified;
}
if (car.soldDate != null)
{
NewSell(car);
}
}
var card = db.Cars.Find(car.Id);
db.Entry(card).State = EntityState.Detached;
db.Entry(car).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Sell");
}
ViewBag.customerId = new SelectList(db.Customers, "Id", "Name", car.customerId);
ViewBag.trackerId = new SelectList(db.Trackers, "Id", "Company", car.trackerId);
ViewBag.insuranceId = new SelectList(db.Insurances, "Id", "Company", car.insuranceId);
return View(car);
}
// GET: Cars/Delete/5
[Authorize(Roles ="Admin,Finance Manager, Manager")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// POST: Cars/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin,Finance Manager, Manager")]
public ActionResult DeleteConfirmed(int id)
{
Car car = db.Cars.Find(id);
db.Cars.Remove(car);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
namespace EPI.BinaryTree
{
public class BinaryTreeNodeWithNext<U>
{
public BinaryTreeNodeWithNext<U> Next;
public BinaryTreeNodeWithNext<U> Left;
public BinaryTreeNodeWithNext<U> Right;
public U Val;
public BinaryTreeNodeWithNext(U value)
{
Val = value;
Left = null;
Right = null;
Next = null;
}
}
/// <summary>
/// Write a function that takes a perfect binary tree and sets each node's next field to the
/// node on its right, if one exists
/// </summary>
public static class ComputeRightSibling<T>
{
public static void SetRightSibling(BinaryTreeNodeWithNext<T> root)
{
while (root != null)
{
SetNextFieldInChildren(root);
root = root.Left;
}
}
private static void SetNextFieldInChildren(BinaryTreeNodeWithNext<T> node)
{
while (node != null && node.Left != null)
{
node.Left.Next = node.Right;
if (node.Next != null)
{
node.Right.Next = node.Next.Left;
}
node = node.Next;
}
}
}
}
|
using System;
using System.Data.Odbc;
namespace Prototipo2P.Conexion
{
public class Conexion
{
OdbcConnection conn;
public string nombreBd { get; set; }
public Conexion(string nombreBd)
{
this.nombreBd = nombreBd;
}
public Tuple<OdbcConnection, OdbcTransaction> conexion()
{
conn = new OdbcConnection("Dsn="+nombreBd);// creacion de la conexion via ODBC
OdbcTransaction transaccion = null;
try
{
conn.Open();
transaccion = conn.BeginTransaction();
}
catch (OdbcException)
{
Console.WriteLine("No Conectó");
}
return Tuple.Create(conn, transaccion);
}
public void desconexion()
{
try
{
conn.Close();
}
catch (OdbcException)
{
Console.WriteLine("No Conectó");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MathCalculations
{
public static Vector3 RotateVector(Vector3 baseVector, Vector3 axis, float deg)
{
float angle = deg * Mathf.Deg2Rad;
float x = axis.x;
float y = axis.y;
float z = axis.z;
float c = Mathf.Cos(angle);
float s = Mathf.Sin(angle);
float c1 = 1 - c;
float[,] rotationMatrix = new float[,] { { c + c1 * x * x, c1 * x * y - z * s, x * z * c1 + y * s },
{ x * y * c1 + z * s, y * y * c1 + c, y * z * c1 - x * s },
{ x * z * c1 - y * s, x * z * c1 + x * s, z * z * c1 + c } };
Vector3 result = new Vector3(baseVector.x * rotationMatrix[0, 0] + baseVector.y * rotationMatrix[1, 0] + baseVector.z * rotationMatrix[2, 0],
baseVector.x * rotationMatrix[0, 1] + baseVector.y * rotationMatrix[1, 1] + baseVector.z * rotationMatrix[2, 1],
baseVector.x * rotationMatrix[0, 2] + baseVector.y * rotationMatrix[1, 2] + baseVector.z * rotationMatrix[2, 2]);
return result;
}
/// <summary>
/// From catlikecoding.com Curves And Splines Tutorial
/// Thanks to Jasper Flick
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p3"></param>
/// <param name="t"></param>
/// <returns></returns>
public static Vector3 GetFirstDerivative(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
3f * oneMinusT * oneMinusT * (p1 - p0) +
6f * oneMinusT * t * (p2 - p1) +
3f * t * t * (p3 - p2);
}
/// <summary>
/// From catlikecoding.com Curves And Splines Tutorial
/// Thanks to Jasper Flick
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p3"></param>
/// <param name="t"></param>
/// <returns></returns>
public static Vector3 GetPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
oneMinusT * oneMinusT * oneMinusT * p0 +
3f * oneMinusT * oneMinusT * t * p1 +
3f * oneMinusT * t * t * p2 +
t * t * t * p3;
}
}
|
using OlvinerBrodcast.DAL.Models;
using OlvinerBrodcast.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace OlvinerBrodcast.WebService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IOlvinerServices" in both code and config file together.
[ServiceContract]
public interface IOlvinerServices
{
#region Test_Service
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "TestService/test")]
[return: MessageParameter(Name = "Result")]
string TestService();
#endregion
#region UserAuthentication
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Authentication")]
[return: MessageParameter(Name = "Result")]
UserDetailsModel UserAuthentication(UserDetailsModel InputData);
#endregion
#region GetUserDetails
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "User/GetUserDetails/{Userid}")]
[return: MessageParameter(Name = "Result")]
UserDetailsModel GetUserDetails(string Userid);
#endregion
#region GetPostByUserid
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "User/GetPost/{id}")]
[return: MessageParameter(Name = "Result")]
PostListModel GetPostByUserid(string id);
#endregion
#region SendChat
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Chat/SendChat")]
[return: MessageParameter(Name = "Result")]
string SendChat(ChatModel input);
#endregion
#region GetUserChat
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Chat/GetUserChat")]
[return: MessageParameter(Name = "Result")]
ChatDisplayModel GetUserChat(GetUserChatInputModel input);
#endregion
#region MobileVerification
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "verification/Mobile/{ContactNo}")]
[return: MessageParameter(Name = "Result")]
string MobileVerification(string ContactNo);
#endregion
#region MobileVerification
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "User/SetProfile/{Userid}")]
[return: MessageParameter(Name = "Result")]
ProfilePic SetProfile(string Userid);
#endregion
}
}
|
using System;
using Askii;
using System.Windows.Forms;
using System.Resources;
namespace Askii.Console
{
class MainClass
{
public static void Main (string[] args)
{
var str = "" +
"==========================================================" +
"| Look Ma' |" +
"==========================================================" +
"| (i) Hi, |" +
"| this is a nice message, isn't it? |" +
"|--------------------------------------------------------|" +
"| [ Yes ] [ No ] |" +
"==========================================================";
str.Render ()
.When (DialogResult.Yes, ThankYou)
.When (DialogResult.No, () => System.Console.WriteLine ("How dare you??"));
}
static void ThankYou ()
{
System.Console.WriteLine ("Thank you!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmberKernel.Services.Statistic.Formatter.DefaultImpl.FormatExpression
{
class ExpressionException:Exception
{
public ExpressionException(string msg):base(msg)
{
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Dialog
{
public GameDatabase.CharacterName speakerName;
public bool speakerExistInScreen = true;
public List<Sentence> sentences = new List<Sentence>();
}
[System.Serializable]
public class Sentence
{
public string sentence;
public float speed = 1;
}
[System.Serializable]
public class DialogEvent : MonoBehaviour {
public int id;
public List<Dialog> dialogs = new List<Dialog>();
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using System.Windows.Controls;
namespace WPF.NewClientl.UI.Dialogs
{
/// <summary>
/// SiginStatisticsDialog.xaml 的交互逻辑
/// </summary>
public partial class MeetingSendNoticeDialog : UserControl
{
public MeetingSendNoticeDialog()
{
InitializeComponent();
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using static DataClasses.Library.Enums;
namespace DataClasses.Library
{
public class Book
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public int PageCount { get; set; }
public BookFormat Format { get; set; }
public string Isbn { get; set; }
public DateTime? OriginalPublication { get; set; }
public int? AuthorId { get; set; }
public virtual Author Author { get; set; }
public int? PublisherId { get; set; }
public virtual Publisher Publisher { get; set; }
}
}
|
using Motherload.Factories;
using Motherload.Interfaces;
using Motherload.Interfaces.Unity;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.Scripts.UI
{
/// <summary>
/// Atualiza a barra de status
/// </summary>
public class StatsBar : MonoBehaviour, IStatsbar
{
#region Properties
/// <summary>
/// Tipo de barra
/// </summary>
public TypeBar TypeBar;
/// <summary>
/// Imagem da barra
/// </summary>
public Image image;
#endregion
#region Unity
/// <summary>
/// Executado quando o jogo é iniciado
/// </summary>
public void Start()
{
image = GetComponent<Image>();
var gameUi = DependencyInjector.Retrieve<IGameUI>();
var player = DependencyInjector.Retrieve<IPlayer>();
if (TypeBar == TypeBar.LIFE) {
gameUi.LifeBar = this;
player.Health = player.Health;
}
if (TypeBar == TypeBar.FUEL) {
gameUi.FuelBar = this;
player.Fuel = player.Fuel;
}
}
#endregion
#region Methods
/// <summary>
/// Implementação de <see cref="IStatsbar.Refresh(float)"/>
/// </summary>
public void Refresh(float value)
{
image.fillAmount = value;
}
#endregion
}
/// <summary>
/// Tipo de barras
/// </summary>
public enum TypeBar
{
FUEL,
LIFE,
}
}
|
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using Report_ClassLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class XenaSAPComparison : System.Web.UI.Page
{
List<User> LoginUser = new List<User>();
Dictionary<string, bool> UserList = new Dictionary<string, bool>();
ReportDocument rdoc = new ReportDocument();
bool validateFilter = false;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AllCashReportLogin"] != null)
{
UserList = (Dictionary<string, bool>)Session["AllCashReportLogin"];
if (UserList.First().Value.ToString() == "0")
{
//Session["AllCashReportLogin"] = "0";
Response.Redirect("~/index.aspx");
}
//if (UserList.First().Key.Contains("acc"))
//{
// Response.Redirect("~/AllCashReport_V2.aspx");
//}
}
if (Session["AllCashReportLogin"] == null)
{
//UserList.Add(username, false);
//Session["AllCashReportLogin"] = "0";
Response.Redirect("~/index.aspx");
}
if (!IsPostBack)
{
InitPage();
}
}
private void InitPage()
{
Dictionary<string, string> branchList = new Dictionary<string, string>();
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand("proc_XenaSapComparison_GetBranch", cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
branchList.Add("-1", "---All---");
while (reader.Read())
{
branchList.Add(reader["RowNum"].ToString(), reader["PrcName"].ToString());
}
cn.Close();
}
ddlBranch.Items.Clear();
ddlBranch.DataSource = branchList;
ddlBranch.DataTextField = "Value";
ddlBranch.DataValueField = "Key";
ddlBranch.DataBind();
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw;
}
}
protected void btnReport_Click(object sender, EventArgs e)
{
}
protected void CrystalReportViewer1_Load(object sender, EventArgs e)
{
GenReport();
}
private void GenReport()
{
try
{
if (!string.IsNullOrEmpty(txtStartDate.Text) && !string.IsNullOrEmpty(txtEndDate.Text))
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
cn.Open();
string dateFrom = "";
string dateTo = "";
var _dateFrom = txtStartDate.Text.Split('/').ToList();
dateFrom = string.Join("/", _dateFrom[1], _dateFrom[0], _dateFrom[2]);
var _dateTo = txtEndDate.Text.Split('/').ToList();
dateTo = string.Join("/", _dateTo[1], _dateTo[0], _dateTo[2]);
var branchName = ddlBranch.SelectedItem.Text == "---All---" ? "" : ddlBranch.SelectedItem.Text;
SqlCommand cmd = null;
cmd = new SqlCommand("proc_XenaSapComparison_GetData", cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@DocDateFrom", dateFrom));
cmd.Parameters.Add(new SqlParameter("@DocDateTo", dateTo));
cmd.Parameters.Add(new SqlParameter("@PrcName", branchName));
cmd.CommandTimeout = 0;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "XenaSapComparisonReport");
rdoc.Load(Server.MapPath("XenaSapComparisonReport.rpt"));
rdoc.SetDataSource(ds.Tables["XenaSapComparisonReport"]);
rdoc.SetParameterValue("@DocDateFrom", dateFrom);
rdoc.SetParameterValue("@DocDateTo", dateTo);
rdoc.SetParameterValue("@PrcName", branchName);
CrystalReportViewer1.RefreshReport();
CrystalReportViewer1.ReportSource = rdoc;
CrystalReportViewer1.DataBind();
cn.Close();
}
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
} |
using Cs_Notas.Aplicacao.Interfaces;
using Cs_Notas.Dominio.Entities;
using Cs_Notas.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Aplicacao.ServicosApp
{
public class AppServicoTipoImovel: AppServicoBase<TipoImovel>, IAppServicoTipoImovel
{
private readonly IServicoTipoImovel _servicoTipoImovel;
public AppServicoTipoImovel(IServicoTipoImovel servicoTipoImovel)
:base(servicoTipoImovel)
{
_servicoTipoImovel = servicoTipoImovel;
}
}
}
|
using BLL.DLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Controls_LibCmsPage_PageView : System.Web.UI.Page
{
#region vars
public int PageID
{
get { return Request["PageID"] == "" ? 0 : Convert.ToInt32(Request["PageID"]); }
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!Access.IsAdmin())
Page.Response.Redirect("~/login.aspx");
if (!IsPostBack)
FormInit();
}
protected void FormInit()
{
if (PageID > 0)
{
lbl1.Text = CmsPage.GetCmsPage(PageID).GetOutputOfPage(Lang.GetDefaultLang().ID);
}
}
} |
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
var problem = Problem.CreateSample();
var configuration = Configuration.Default;
var finalSolution = GeneticAlgorithm.Run(problem, configuration);
//Essa solução final contém todas as configurações, dentre os 300 itens do exemplo.
//Pra obter os itens exatos, é necessário ir pegando os itens até a capacidade da mochila.
//O que amezina isso é que a solução contém o número de items, então seria só pegar o número de itens retornados.
System.Console.WriteLine($"Final solution: {finalSolution}");
public class GeneticAlgorithm
{
public static Solution Run(
Problem problem,
Configuration configuration)
{
var population = new Population(problem, configuration);
Solution bestSolution = population.GetBestSolution();
System.Console.WriteLine($"First Generation: {bestSolution}");
var initialMutationRate = configuration.MutationRate;
var staleGenerationsCount = 0;
for (int i = 0; i < configuration.MaxGenerations; i++)
{
population = population.Evolve();
var candidate = population.GetBestSolution();
if (configuration.FitnessComparer
.Compare(bestSolution, candidate) == 0)
{
System.Console.WriteLine(
$"Generation {i + 1}: No improvements, incrementing mutation"
);
staleGenerationsCount++;
configuration.MutationRate = initialMutationRate * (Math.Pow(1.1, staleGenerationsCount));
}
else
{
bestSolution = candidate;
configuration.MutationRate = initialMutationRate;
staleGenerationsCount = 0;
System.Console.WriteLine($"Generation {i + 1}: {bestSolution}");
}
}
return bestSolution;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.