text stringlengths 13 6.01M |
|---|
using System;
using HaloSharp.Model.Stats.CarnageReport;
namespace HaloHistory.Business.Entities.Stats
{
public class MatchEventsData : BaseDataEntity<string, MatchEvents>
{
public MatchEventsData()
{
}
public MatchEventsData(Guid id, MatchEvents data) : base(id.ToString(), data)
{
}
}
}
|
using System;
using System.Collections.Generic;
//Write a program to convert hexadecimal numbers to their decimal representation.
class HexadecimalToDecimal
{
static void Main()
{
Console.WriteLine(ConvertHexadecimalToDecimal("E8287A8"));
}
static int ConvertHexadecimalToDecimal(string numberInHex)
{
int numberInDecimal = 0;
for (int i = 0; i < numberInHex.Length; i++)
{
if (numberInHex[numberInHex.Length - 1 - i] >= 'A')
{
int p = 10 + (numberInHex[numberInHex.Length - 1 - i] - 'A');
numberInDecimal += (int)(p*Math.Pow(16, i));
}
else
{
int p = numberInHex[numberInHex.Length - 1 - i] - '0';
numberInDecimal += (int)(p*Math.Pow(16, i));
}
}
return numberInDecimal;
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OmniSharp.Extensions.JsonRpc.Generators.Contexts;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies
{
internal class ExtensionMethodGeneratorStrategy : ICompilationUnitGeneratorStrategy
{
private readonly ImmutableArray<IExtensionMethodGeneratorStrategy> _extensionMethodGeneratorStrategies;
public ExtensionMethodGeneratorStrategy(ImmutableArray<IExtensionMethodGeneratorStrategy> extensionMethodGeneratorStrategies)
{
_extensionMethodGeneratorStrategies = extensionMethodGeneratorStrategies;
}
public IEnumerable<MemberDeclarationSyntax> Apply(SourceProductionContext context, GeneratorData item)
{
var methods = _extensionMethodGeneratorStrategies.Aggregate(
new List<MemberDeclarationSyntax>(), (m, strategy) => {
try
{
m.AddRange(strategy.Apply(context, item));
}
catch (Exception e)
{
Debug.WriteLine($"Strategy {strategy.GetType().FullName} failed!");
Debug.WriteLine(e);
Debug.WriteLine(e.StackTrace);
}
return m;
}
);
var className = item.JsonRpcAttributes.HandlerName + "Extensions" + ( item.TypeDeclaration.Arity == 0 ? "" : item.TypeDeclaration.Arity.ToString() );
var obsoleteAttribute = item.TypeDeclaration.AttributeLists
.SelectMany(z => z.Attributes)
.Where(z => z.IsAttribute("Obsolete"))
.ToArray();
var attributes = List(
new[] {
AttributeList(
SeparatedList(
new[] {
Attribute(ParseName("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute")),
Attribute(ParseName("System.Runtime.CompilerServices.CompilerGeneratedAttribute")),
}.Union(obsoleteAttribute)
)
)
}
);
if (methods.Count == 0) yield break;
yield return NamespaceDeclaration(ParseName(item.JsonRpcAttributes.HandlerNamespace))
.WithMembers(
SingletonList<MemberDeclarationSyntax>(
ClassDeclaration(className)
.WithAttributeLists(attributes)
.WithModifiers(
TokenList(
new [] {
Token(item.TypeSymbol.DeclaredAccessibility == Accessibility.Public ? SyntaxKind.PublicKeyword : SyntaxKind.InternalKeyword),
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.PartialKeyword)
}
)
)
.WithMembers(List(methods))
.WithLeadingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true))))
.WithTrailingTrivia(TriviaList(Trivia(NullableDirectiveTrivia(Token(SyntaxKind.RestoreKeyword), true))))
)
);
}
}
}
|
namespace _1.Logger.Interfaces
{
using _1.Logger.Enums;
public interface ILayout
{
string Formatting(ReportLevel reportLevel, string date, string msg);
}
} |
using PDV.RETAGUARDA.WEB.AppContext;
using System;
using System.Web;
using System.Web.SessionState;
namespace PDV
{
public class Global : HttpApplication, IRequiresSessionState
{
public override void Init()
{
this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MGL_API.Model.Saida.Game
{
public class RetornoAvaliarGame : Retorno
{
public string Classificacao { get; set;}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SecondProject.Controllers.Services.Model.Domain
{
public class LogLevel
{
public string Default { get; set; }
public string System { get; set; }
public string Microsoft { get; set; }
}
}
|
using System;
using Workout.ViewModels.Workout;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Workout.Views.Workout
{
/// <summary>
/// Workout main view.
/// </summary>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainView : ContentPage
{
#region fields
/// <summary>
/// An instance of workout view model.
/// </summary>
private MainViewModel _viewModel;
#endregion
#region methods
/// <summary>
/// Initializes class instance.
/// </summary>
public MainView()
{
InitializeComponent();
_viewModel = BindingContext as MainViewModel;
}
/// <summary>
/// Overrides method called when the page appears.
/// Starts workout.
/// </summary>
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.StartWorkout();
}
/// <summary>
/// Overrides method handling hardware "back" button press.
/// Pauses workout.
/// </summary>
protected override bool OnBackButtonPressed()
{
_viewModel.PauseWorkout();
return true;
}
/// <summary>
/// Overrides method called when the page disappears.
/// Disposes binding context.
/// </summary>
protected override void OnDisappearing()
{
base.OnDisappearing();
if (BindingContext is IDisposable disposableBindingContext)
{
disposableBindingContext.Dispose();
BindingContext = null;
}
}
#endregion
}
}
|
using Microsoft.WindowsAzure.Storage.Table;
using System;
namespace XcExport.Cortex.AzureStorage.Model
{
public class InteractionEntity : TableEntity
{
public static string PartitionKey = "Cortex.InteractionEntity";
public InteractionEntity(string userAgent, TimeSpan duration, Guid? interactionId, Guid? contactId, DateTime startDateTime, string ipInfo, string city)
{
base.PartitionKey = PartitionKey;
RowKey = interactionId.ToString();
UserAgent = userAgent;
Duration = duration;
InteractionId = interactionId;
ContactId = contactId;
StartDateTime = startDateTime;
IpInfo = ipInfo;
City = city;
}
public InteractionEntity() { }
public string UserAgent { get; set; }
public TimeSpan Duration { get; set; }
public Guid? InteractionId { get; set; }
public Guid? ContactId { get; set; }
public DateTime StartDateTime { get; set; }
public string IpInfo { get; set; }
public string City { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeacvtivateSnapAreas : MonoBehaviour
{
//makes sure only one object can be in a spot at a time
private void OnTriggerStay(Collider other)
{
transform.tag = "Untagged";
}
private void OnTriggerExit(Collider other)
{
transform.tag = "snapPosition";
}
}
|
using System;
using System.Collections.Generic;
using SMSEntities.SMSDBEntities;
using System.Data;
using MySql.Data.MySqlClient;
namespace SMSDAL.SMSDB
{
public class UserInfoDBAccess
{
public int InsertUserInfo(UserInfo p_UserInfo)
{
//if (!IsUserExists(p_UserInfo))
//{
int result = 0;
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_DeploymentID", p_UserInfo.DeploymentID),
new MySqlParameter("p_UserTypeID", p_UserInfo.UserTypeID),
new MySqlParameter("p_LoginID", p_UserInfo.LoginID),
new MySqlParameter("p_UserName",p_UserInfo.UserName),
new MySqlParameter("p_EmailID",p_UserInfo.EmailID),
new MySqlParameter("p_Password",p_UserInfo.Password),
new MySqlParameter("p_result",MySqlDbType.Int32, 2,ParameterDirection.Output,false,1,1,"Out",DataRowVersion.Default,result)
};
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("AddUserDetails", CommandType.StoredProcedure, parameters);
//}
//else return false;
}
public int UpdateUserInfo(UserInfo p_UserInfo)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_UID", p_UserInfo.UID),
new MySqlParameter("p_DeploymentID", p_UserInfo.DeploymentID),
new MySqlParameter("p_UserTypeID", p_UserInfo.UserTypeID),
new MySqlParameter("p_LoginID", p_UserInfo.LoginID),
new MySqlParameter("p_UserName",p_UserInfo.UserName),
new MySqlParameter("p_EmailID",p_UserInfo.EmailID),
new MySqlParameter("p_Password",p_UserInfo.Password)};
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("UpdateUserDetails", CommandType.StoredProcedure, parameters);
}
public int DeleteUserType(int p_UID)
{
//string sqlQuery = "Delete From `userdetails` WHERE `UserTypeID` = " + p_UserInfo.UserTypeID;
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_UID", p_UID)};
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("DeleteUserdetail", CommandType.StoredProcedure, parameters);
}
public int DeleteUser(int p_UID)
{
//string sqlQuery = "Delete From `userdetails` WHERE `UserTypeID` = " + p_UserInfo.UserTypeID;
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_UID", p_UID)};
return MySQLDB.MySQLDBHelper.ExecuteNonQuery("DeleteUserdetail", CommandType.StoredProcedure, parameters);
}
public UserInfo IsUserExists(UserInfo p_UserInfo)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_LoginID", p_UserInfo.LoginID),
new MySqlParameter("p_Password",p_UserInfo.Password)};
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("IsUserExists", CommandType.StoredProcedure, parameters);
UserInfo userdetails = null;
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
userdetails = new UserInfo();
userdetails.UID = Convert.ToInt32(dr["UID"]);
userdetails.UserTypeID = Convert.ToInt32(dr["UserTypeID"].ToString());
userdetails.UserName = dr["UserName"].ToString();
userdetails.UserType = dr["UserType"].ToString();
userdetails.DeploymentID = Convert.ToInt32(dr["DeploymentID"]);
return userdetails;
}
return null;
}
public List<UserInfo> SeletctUsersListByUserTypeID(int p_UserTypeID)
{
string sqlQuery = "SELECT `UID`, `UserName` FROM `userdetails` WHERE UserTypeID = " + p_UserTypeID + "";
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand(sqlQuery, CommandType.Text);
List<UserInfo> usertypetCol = new List<UserInfo>();
UserInfo userdetails;
foreach (DataRow dr in dt.Rows)
{
userdetails = new UserInfo();
userdetails.UID = Convert.ToInt32(dr["UID"]);
userdetails.UserName = dr["UserName"].ToString();
usertypetCol.Add(userdetails);
}
return usertypetCol;
}
public List<UserInfo> SeletctUsersList(int deploymentId, int currentUserType)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("currentUserType", currentUserType),
new MySqlParameter("p_deploymentId", deploymentId)};
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetUserdetails", CommandType.StoredProcedure,parameters);
List<UserInfo> usersCol = new List<UserInfo>();
UserInfo userdetails;
foreach (DataRow dr in dt.Rows)
{
userdetails = new UserInfo();
userdetails.UserTypeID = Convert.ToInt32(dr["UserTypeID"].ToString());
userdetails.DeploymentID = Convert.ToInt32(dr["DeploymentID"]);
userdetails.EmailID = dr["EmailID"].ToString();
userdetails.LoginID = dr["LoginID"].ToString();
userdetails.UserName = dr["UserName"].ToString();
userdetails.UID = Convert.ToInt32(dr["UID"]);
usersCol.Add(userdetails);
}
return usersCol;
}
/// To select the all existing deployments
/// </summary>
/// <returns>data can return as collection list</returns>
public List<UserInfo> SelectUsersByDeploymentId(int p_DeployementID)
{
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_DeploymentId", p_DeployementID)
};
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetUsersByDeploymentID", CommandType.StoredProcedure, parameters);
List<UserInfo> usersCol = new List<UserInfo>();
UserInfo userdetails;
foreach (DataRow dr in dt.Rows)
{
userdetails = new UserInfo();
userdetails.UID = Convert.ToInt32(dr["UID"]);
userdetails.DeploymentID = Convert.ToInt32(dr["DeploymentID"]);
userdetails.UserTypeID = Convert.ToInt32(dr["UserTypeID"].ToString());
userdetails.LoginID = dr["LoginID"].ToString();
userdetails.UserName = dr["UserName"].ToString();
userdetails.EmailID = dr["EmailID"].ToString();
usersCol.Add(userdetails);
}
dt.Clear();
dt.Dispose();
return usersCol;
}
/// <summary>
/// To select the all existing deployments
/// </summary>
/// <returns>data can return as collection list</returns>
public UserInfo SeletctUserInfoByID(int p_UID)
{
//string sqlQuery = "SELECT `DeploymentID`, `EmailID`, `LoginID`, `UID`, `UserName`, `UserTypeID` FROM `userdetails` WHERE `UID` = " + p_UID;
MySqlParameter[] parameters = new MySqlParameter[] {
new MySqlParameter("p_UID", p_UID)};
DataTable dt = MySQLDB.MySQLDBHelper.ExecuteSelectCommand("GetUserdetailByID", CommandType.StoredProcedure, parameters);
UserInfo userdetails = null;
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
userdetails = new UserInfo();
userdetails.UserTypeID = Convert.ToInt32(dr["UserTypeID"].ToString());
userdetails.DeploymentID = Convert.ToInt32(dr["DeploymentID"]);
userdetails.EmailID = dr["EmailID"].ToString();
userdetails.LoginID = dr["LoginID"].ToString();
userdetails.UserName = dr["UserName"].ToString();
userdetails.UID = Convert.ToInt32(dr["UID"]);
}
return userdetails;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Salesforce.Force;
namespace ConsoleApplication1
{
class Program
{
private static string _securityToken = Encoding.UTF8.GetString(Convert.FromBase64String("V1dnVGFiSEdETE5wV29SbERaYkpJOElyOQ=="));
private static string _clientId = Encoding.UTF8.GetString(Convert.FromBase64String("M01WRzl4T0NYcTRJRDF1RUNwckh3OXlBMmVqbGE2OGI1MDk2a2hPQnFLZXdDeHVXZjNPOEJOYWc1eW0ycXJPTGxkQ2xQOFNwVTVwLkRhUmtRa19BQw=="));
private static string _clientSecret = Encoding.UTF8.GetString(Convert.FromBase64String("NjQ3ODMyMDc4MjU1MDE1NTIwOA=="));
private static string _username = "demo@appplat.com";
private static string _password = Encoding.UTF8.GetString(Convert.FromBase64String("UGEkJHcwcmQh")) + _securityToken;
static void Main(string[] args)
{
var auth = new AuthenticationClient();
auth.UsernamePasswordAsync(_clientId, _clientSecret, _username, _password).Wait();
var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
var results = client.QueryAsync<dynamic>("SELECT Id, Name, Description FROM Account");
results.Wait();
Console.WriteLine(results.Result.records.Count);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
namespace ArcheryTool
{
class Ring<T> : IEnumerable<T>, IEnumerator<T>
{
protected int nElements;
protected int nHead = -1; //list has no items in it, so head is outside range of nElements
protected T[] ring;
public Ring(int nElements)
{
this.nElements = nElements;
ring = new T[nElements];
}
public T Current => ring[nHead];
public int GetHead()
{
return nHead;
}
public int GetSize()
{
int size = 0;
for (int i = 0; i < ring.Length; i++)
{
if (ring[i] != null)
size++;
}
return size;
}
public virtual void Add(T element)
{
MoveNext();
ring[nHead] = element;
}
public T this[int nIndex]
{
get { return ring[nIndex]; }
}
object IEnumerator.Current => ring[nHead];
public void Dispose()
{
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
public bool MoveNext()
{
nHead++;
if (nHead > nElements - 1) //0 indexed to match array, resets to 0 instead of ticking over to nElements - 1
nHead = 0;
return true;
}
public void SetHead(int element)
{
nHead = element;
}
public void ResetHead()
{
nHead = -1;
}
public void Reset()
{
ResetHead();
ring = new T[nElements];
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public int GetNumElements()
{
return nElements;
}
}
class UIRing<T> : Ring<T> where T : UIElement
{
public UIRing(int nElements) : base(nElements)
{
this.nElements = nElements;
ring = new T[nElements];
}
public override void Add(T element)
{
MoveNext();
ring[nHead] = (T)element;
}
public void SetNumElements(int newNElements)
{
if (newNElements > nElements)
{
nElements = newNElements;
}
else
{
T[] temp = new T[nElements];
for(int i = 0; i < nElements; i++)
{
temp[i] = Current;
MoveNext();
}
nElements = newNElements;
ring = new T[nElements];
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using StudentExercises.Models;
namespace StudentExercises.Data
{
public class Repository
{
private readonly IConfiguration _config;
public Repository(IConfiguration config)
{
_config = config;
}
public SqlConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DefaultConnection"));
}
}
/************************************************************************************
* Query the database for all the Exercises.
* Exercise JSON response should have all currently assigned students if the
include=students query string parameter is there.
************************************************************************************/
public List<Exercise> GetAllExercises(string q, string _include, string active)
{
var studentList = new List<Student>();
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
var filter = "";
if (!string.IsNullOrEmpty(q))
{
filter = @" WHERE e.ExName
LIKE '%' + @filter + '%'
OR e.ExLanguage
LIKE '%' + @filter + '%' ";
}
cmd.CommandText = @"SELECT Id, ExName, ExLanguage
FROM Exercise" + filter;
if (!string.IsNullOrEmpty(q))
{
cmd.Parameters.Add(new SqlParameter("@filter", q));
}
SqlDataReader reader = cmd.ExecuteReader();
List<Exercise> exercises = new List<Exercise>();
while (reader.Read())
{
if (_include == "student")
studentList = GetAllStudentsByExerciseId(reader.GetInt32(reader.GetOrdinal("Id")));
int idColumnPosition = reader.GetOrdinal("Id");
int idValue = reader.GetInt32(idColumnPosition);
var exName = reader.GetString(reader.GetOrdinal("ExName"));
var exLanguage = reader.GetString(reader.GetOrdinal("ExLanguage"));
Exercise exercise = new Exercise
{
Id = idValue,
ExName = exName,
ExLanguage = exLanguage,
studentList = studentList
};
exercises.Add(exercise);
}
reader.Close();
return exercises;
}
}
}
/************************************************************************************
* Find all the exercises in the database where the language is JavaScript.
************************************************************************************/
public List<Exercise> GetByLanguage(string language)
{
var exercises = new List<Exercise>();
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT Id, ExName, ExLanguage
FROM Exercise
WHERE ExLanguage LIKE '%' + @language + '%'";
cmd.Parameters.Add(new SqlParameter("@language", language));
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int idColumnPosition = reader.GetOrdinal("Id");
int idValue = reader.GetInt32(idColumnPosition);
var exName = reader.GetString(reader.GetOrdinal("ExName"));
var exLanguage = reader.GetString(reader.GetOrdinal("ExLanguage"));
Exercise exercise = new Exercise
{
Id = idValue,
ExName = exName,
ExLanguage = exLanguage
};
exercises.Add(exercise);
}
reader.Close();
return exercises;
}
}
}
/************************************************************************************
* Insert a new exercise into the database.
************************************************************************************/
public void AddExercise(string exName, string exLanguage)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"INSERT INTO Exercise
(ExName, ExLanguage)
VALUES (@exName, @exLanguage)";
cmd.Parameters.Add(new SqlParameter("@exName", exName));
cmd.Parameters.Add(new SqlParameter("@exLanguage", exLanguage));
cmd.ExecuteScalar();
}
}
}
/************************************************************************************
* Find all instructors in the database.Include each instructor's cohort.
* Provide support for each resource (Instructor, Student, Cohort, Exercise) and the q query string parameter.
If it is provided, your SQL should search relevant property for a match, search all properties of the resource for a match.
FirstName, LastName, and SlackHandle for instructors and students.
Name and Language for exercises.
Name for cohorts.
************************************************************************************/
public List<Instructor> GetInstructorsWithCohort(string q, string _include, string active)
{
var instructors = new List<Instructor>();
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
var filter = "";
if(!string.IsNullOrEmpty(q))
{
filter = @" WHERE i.FirstName
LIKE '%' + @filter + '%'
OR i.LastName
LIKE '%' + @filter + '%'
OR i.SlackHandle
LIKE '%' + @filter + '%' ";
}
cmd.CommandText = @"SELECT i.Id, i.FirstName, i.LastName, c.CohortNum, i.SlackHandle
FROM Instructor i
JOIN CohortInstructors ci
ON ci.InstructorId = i.Id
JOIN Cohort c
ON c.Id = ci.CohortId" + filter;
if (!string.IsNullOrEmpty(q))
{
cmd.Parameters.Add(new SqlParameter("@filter", q));
}
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int idColumnPosition = reader.GetOrdinal("Id");
int idValue = reader.GetInt32(idColumnPosition);
var FirstName = reader.GetString(reader.GetOrdinal("FirstName"));
var LastName = reader.GetString(reader.GetOrdinal("LastName"));
var CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum"));
var slackHanlde = reader.GetString(reader.GetOrdinal("SlackHandle"));
Instructor instructor = new Instructor
{
Id = idValue,
FirstName = FirstName,
LastName = LastName,
SlackHandle = slackHanlde,
cohort = new Cohort { CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum")), CohortName = "Cohort " + reader.GetInt32(reader.GetOrdinal("CohortNum")) }
};
instructors.Add(instructor);
}
reader.Close();
return instructors;
}
}
}
/************************************************************************************
* Insert a new instructor into the database.
* Assign the instructor to an existing cohort.
************************************************************************************/
public void InsertInstructorWithAssign(string firstName, string lastName, string slackHandle, int cohortNum)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
DECLARE @InstructorTemp TABLE (Id int);
INSERT INTO Instructor (FirstName, LastName, SlackHandle)
OUTPUT INSERTED.Id INTO @InstructorTemp(Id)
VALUES (@FirstName, @LastName, @SlackHandle)
SELECT TOP 1 @ID = Id FROM @InstructorTemp";
SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(new SqlParameter("@FirstName", firstName));
cmd.Parameters.Add(new SqlParameter("@LastName", lastName));
cmd.Parameters.Add(new SqlParameter("@SlackHandle", slackHandle));
cmd.ExecuteNonQuery();
var newInstructorId = (int)outputParam.Value;
cmd.CommandText = @"INSERT INTO CohortInstructors (CohortId, InstructorId)
SELECT c.Id, @InstructorId
FROM Cohort c
WHERE c.CohortNum = @CohortNum";
cmd.Parameters.Add(new SqlParameter("@InstructorId", newInstructorId));
cmd.Parameters.Add(new SqlParameter("@CohortNum", cohortNum));
cmd.ExecuteNonQuery();
}
}
}
/************************************************************************************
* Assign an existing exercise to an existing student.
************************************************************************************/
public void AddExerciseToStudent(string firstName, string lastName, string slackHandle, string exerciseName)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DECLARE @ExerciseId int = 0;
SELECT TOP 1 @ExerciseId = e.Id FROM Exercise e WHERE e.ExName = @exerciseName
IF @ExerciseId > 0
BEGIN
INSERT INTO StudentExercises (ExerciseId, StudentId)
SELECT @ExerciseId, s.Id FROM Student s
WHERE s.FirstName = @FirstName AND s.LastName = @LastName AND s.SlackHandle = @SlackHandle
END";
cmd.Parameters.Add(new SqlParameter("@FirstName", firstName));
cmd.Parameters.Add(new SqlParameter("@LastName", lastName));
cmd.Parameters.Add(new SqlParameter("@SlackHandle", slackHandle));
cmd.Parameters.Add(new SqlParameter("@exerciseName", exerciseName));
cmd.ExecuteNonQuery();
}
}
}
/************************************************************************************
* Student JSON response should have all exercises that are assigned to them if the
include=exercise query string parameter is there.
************************************************************************************/
public List<Student> GetAllStudents(string q, string _include, string active)
{
var exerciseList = new List<Exercise>();
using (SqlConnection conn = Connection)
{
var filter = "";
if (!string.IsNullOrEmpty(q))
{
filter = @" WHERE s.FirstName
LIKE '%' + @filter + '%'
OR s.LastName
LIKE '%' + @filter + '%'
OR s.SlackHandle
LIKE '%' + @filter + '%' ";
}
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT s.Id, s.FirstName, s.LastName, s.SlackHandle, c.CohortNum
FROM Student s
JOIN CohortStudents cs
ON cs.StudentId = s.Id
JOIN Cohort c
ON cs.CohortId = c.Id" + filter;
if (!string.IsNullOrEmpty(q))
{
cmd.Parameters.Add(new SqlParameter("@filter", q));
}
SqlDataReader reader = cmd.ExecuteReader();
List<Student> students = new List<Student>();
while (reader.Read())
{
if (_include == "exercise")
exerciseList = GetAllExercisesByStudentId(reader.GetInt32(reader.GetOrdinal("Id")));
var student = new Student
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
LastName = reader.GetString(reader.GetOrdinal("LastName")),
SlackHandle = reader.GetString(reader.GetOrdinal("SlackHandle")),
cohort = new Cohort { CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum")), CohortName = "Cohort " + reader.GetInt32(reader.GetOrdinal("CohortNum")) },
exerciseList = exerciseList
};
students.Add(student);
}
reader.Close();
return students;
}
}
}
/************************************************************************************
* Additional Methods
************************************************************************************/
public Student GetOneStudent(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT Id, FirstName, LastName, SlackHandle
FROM Student
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
Student student = null;
if (reader.Read())
{
student = new Student
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
LastName = reader.GetString(reader.GetOrdinal("LastName")),
SlackHandle = reader.GetString(reader.GetOrdinal("SlackHandle"))
};
}
reader.Close();
return student;
}
}
}
public Student AddStudent(Student newStudent)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DECLARE @TempStudent TABLE (Id int)
INSERT INTO Student (FirstName, LastName, SlackHandle)
OUTPUT INSERTED.Id INTO @TempStudent
VALUES (@firstName, @lastName, @slackHandle)
SELECT top 1 @OutputId = Id FROM @TempStudent";
SqlParameter outPutId = new SqlParameter("@OutputId", SqlDbType.Int);
outPutId.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutId);
cmd.Parameters.Add(new SqlParameter("@firstName", newStudent.FirstName));
cmd.Parameters.Add(new SqlParameter("@lastName", newStudent.LastName));
cmd.Parameters.Add(new SqlParameter("@slackHandle", newStudent.SlackHandle));
cmd.ExecuteScalar();
newStudent.Id = (int)outPutId.Value;
return newStudent;
}
}
}
public Student UpdateStudent(int id, Student student)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"UPDATE Student
SET FirstName = @firstName,
LastName = @lastName,
SlackHandle = @slackHandle
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@firstName", student.FirstName));
cmd.Parameters.Add(new SqlParameter("@lastName", student.LastName));
cmd.Parameters.Add(new SqlParameter("@slackHandle", student.SlackHandle));
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
if (!StudentExists(id))
{
throw;
}
}
return student;
}
public void DeleteStudent(int id)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DELETE FROM Student WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
if (!StudentExists(id))
{
throw;
}
}
}
public List<Exercise> GetAllExercisesByStudentId(int studentId)
{
var exercises = new List<Exercise>();
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT e.Id, e.ExName, e.ExLanguage FROM Exercise e
JOIN StudentExercises se
ON se.ExerciseId = e.Id
WHERE se.StudentId = @StudentId";
cmd.Parameters.Add(new SqlParameter("@StudentId", studentId));
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int idColumnPosition = reader.GetOrdinal("Id");
int idValue = reader.GetInt32(idColumnPosition);
var exName = reader.GetString(reader.GetOrdinal("ExName"));
var exLanguage = reader.GetString(reader.GetOrdinal("ExLanguage"));
Exercise exercise = new Exercise
{
Id = idValue,
ExName = exName,
ExLanguage = exLanguage
};
exercises.Add(exercise);
}
reader.Close();
return exercises;
}
}
}
public List<Student> GetAllStudentsByExerciseId(int exerciseId)
{
var students = new List<Student>();
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT s.Id, s.FirstName, s.LastName
FROM Student s
JOIN StudentExercises se
ON se.StudentId = s.Id
WHERE se.ExerciseId = @ExerciseId";
cmd.Parameters.Add(new SqlParameter("@ExerciseId", exerciseId));
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int idColumnPosition = reader.GetOrdinal("Id");
int idValue = reader.GetInt32(idColumnPosition);
var FirstName = reader.GetString(reader.GetOrdinal("FirstName"));
var LastName = reader.GetString(reader.GetOrdinal("LastName"));
Student student = new Student
{
Id = idValue,
FirstName = FirstName,
LastName = LastName
};
students.Add(student);
}
reader.Close();
return students;
}
}
}
/************************************************************************************
* CRUD for Cohorts
************************************************************************************/
public List<Cohort> GetAllCohorts(string q, string _include, string active)
{
var cohortList = new List<Cohort>();
using (SqlConnection conn = Connection)
{
var filter = "";
if (!string.IsNullOrEmpty(q))
{
filter = @" WHERE CohortNum
LIKE '%' + @filter + '%' ";
}
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT Id, CohortNum
FROM Cohort" + filter;
if (!string.IsNullOrEmpty(q))
{
cmd.Parameters.Add(new SqlParameter("@filter", q));
}
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var cohort = new Cohort
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum")),
CohortName = "Cohort " + reader.GetInt32(reader.GetOrdinal("CohortNum"))
};
cohortList.Add(cohort);
}
reader.Close();
return cohortList;
}
}
}
public Cohort GetOneCohort(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT Id, IsDayTime, CohortNum
FROM Cohort
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
Cohort cohort = null;
if (reader.Read())
{
cohort = new Cohort
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
IsDayTime = reader.GetBoolean(reader.GetOrdinal("IsDayTime")),
CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum"))
};
}
reader.Close();
return cohort;
}
}
}
public Cohort AddCohort(Cohort newCohort)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DECLARE @TempCohort TABLE (Id int)
INSERT INTO Cohort (IsDayTime, CohortNum)
OUTPUT INSERTED.Id INTO @TempCohort
VALUES (@isDayTime, @cohortNum)
SELECT top 1 @OutputId = Id FROM @TempCohort";
SqlParameter outPutId = new SqlParameter("@OutputId", SqlDbType.Int);
outPutId.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutId);
cmd.Parameters.Add(new SqlParameter("@isDayTime", newCohort.IsDayTime));
cmd.Parameters.Add(new SqlParameter("@cohortNum", newCohort.CohortNum));
cmd.ExecuteScalar();
newCohort.Id = (int)outPutId.Value;
return newCohort;
}
}
}
public Cohort UpdateCohort(int id, Cohort cohort)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"UPDATE Cohort
SET IsDayTime = @isDayTime,
CohortNum = @cohortNum
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@isDayTime", cohort.IsDayTime));
cmd.Parameters.Add(new SqlParameter("@cohortNum", cohort.CohortNum));
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
throw new Exception("No rows affected");
}
}
}
catch (Exception)
{
if (!CohortExists(id))
{
throw;
}
}
return cohort;
}
public void DeleteCohort(int id)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DELETE FROM Cohort WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
if (!CohortExists(id))
{
throw;
}
}
}
/************************************************************************************
* CRUD for Instructors
************************************************************************************/
public Instructor GetOneInstructor(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT Id, FirstName, LastName, SlackHandle
FROM Instructor
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
Instructor instructor = null;
if (reader.Read())
{
instructor = new Instructor
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
LastName = reader.GetString(reader.GetOrdinal("LastName")),
SlackHandle = reader.GetString(reader.GetOrdinal("SlackHandle"))
};
}
reader.Close();
return instructor;
}
}
}
public Instructor UpdateInstructor(int id, Instructor instructor)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"UPDATE Instructor
SET FirstName = @firstName,
LastName = @lastName,
SlackHandle = @slackHandle
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@firstName", instructor.FirstName));
cmd.Parameters.Add(new SqlParameter("@lastName", instructor.LastName));
cmd.Parameters.Add(new SqlParameter("@slackHandle", instructor.SlackHandle));
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
throw new Exception("No rows affected");
}
}
}
catch (Exception)
{
if (!InstructorExists(id))
{
throw;
}
}
return instructor;
}
public void DeleteInstructor(int id)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DELETE FROM Instructor WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
if (!InstructorExists(id))
{
throw;
}
}
}
/************************************************************************************
* CRUD for Exercises
************************************************************************************/
public Exercise GetOneExercise(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT Id, ExName, ExLanguage
FROM Exercise
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
Exercise exercise = null;
if (reader.Read())
{
exercise = new Exercise
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
ExName = reader.GetString(reader.GetOrdinal("ExName")),
ExLanguage = reader.GetString(reader.GetOrdinal("ExLanguage"))
};
}
reader.Close();
return exercise;
}
}
}
public Exercise AddExercise(Exercise newExercise)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DECLARE @TempExercise TABLE (Id int)
INSERT INTO Exercise (ExName, ExLanguage)
OUTPUT INSERTED.Id INTO @TempExercise
VALUES (@exName, @exLanguage)
SELECT top 1 @OutputId = Id FROM @TempExercise";
SqlParameter outPutId = new SqlParameter("@OutputId", SqlDbType.Int);
outPutId.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutId);
cmd.Parameters.Add(new SqlParameter("@exName", newExercise.ExName));
cmd.Parameters.Add(new SqlParameter("@exLanguage", newExercise.ExLanguage));
cmd.ExecuteScalar();
newExercise.Id = (int)outPutId.Value;
return newExercise;
}
}
}
public Exercise UpdateExercise(int id, Exercise exercise)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"UPDATE Exercise
SET ExName = @exName,
ExLanguage = @exLanguage
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@exName", exercise.ExName));
cmd.Parameters.Add(new SqlParameter("@exLanguage", exercise.ExLanguage));
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
throw new Exception("No rows affected");
}
}
}
catch (Exception)
{
if (!ExerciseExists(id))
{
throw;
}
}
return exercise;
}
public void DeleteExercise(int id)
{
try
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"DELETE FROM Exercise WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
int rowsAffected = cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
if (!ExerciseExists(id))
{
throw;
}
}
}
/************************************************************************************
* Add the following to your program:
Find all the students in the database.Include each student's cohort
AND each student's list of exercises.
************************************************************************************/
public List<Student> GetStudentsWithCohortExercise()
{
var students = new List<Student>();
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT s.Id, s.FirstName, s.LastName, s.SlackHandle, c.CohortNum, e.ExName
FROM Student s
JOIN CohortInstructors ci
ON ci.InstructorId = s.Id
JOIN Cohort c
ON c.Id = ci.CohortId
JOIN StudentExercises se
ON s.Id = se.StudentId
JOIN Exercise e
ON e.Id = se.ExerciseId";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int idColumnPosition = reader.GetOrdinal("Id");
int idValue = reader.GetInt32(idColumnPosition);
var FirstName = reader.GetString(reader.GetOrdinal("FirstName"));
var LastName = reader.GetString(reader.GetOrdinal("LastName"));
var CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum"));
var SlackHanlde = reader.GetString(reader.GetOrdinal("SlackHandle"));
var ExName = reader.GetString(reader.GetOrdinal("ExName"));
Student student = new Student
{
Id = idValue,
FirstName = FirstName,
LastName = LastName,
SlackHandle = SlackHanlde,
cohort = new Cohort { CohortNum = reader.GetInt32(reader.GetOrdinal("CohortNum")), CohortName = "Cohort " + reader.GetInt32(reader.GetOrdinal("CohortNum")) },
exerciseList = GetAllExercisesByStudentId(idValue)
};
students.Add(student);
}
reader.Close();
return students;
}
}
}
/************************************************************************************
* Write a method in the Repository class that accepts an Exercise and
a Cohort and assigns that exercise to each student in the cohort
IF and ONLY IF the student has not already been assigned the exercise.
************************************************************************************/
public void AssignCohortExercises(int exerciseId, int cohortId)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"INSERT INTO StudentExercises
(StudentId, ExerciseId)
SELECT s.Id, @exerciseId
FROM Student s
JOIN CohortStudents cs
ON cs.StudentId = s.Id
WHERE cs.CohortId = @cohortId
AND s.Id NOT IN (SELECT StudentExercises.StudentId
FROM StudentExercises
WHERE StudentExercises.ExerciseId = @exerciseId)";
cmd.Parameters.Add(new SqlParameter("@exerciseId", exerciseId));
cmd.Parameters.Add(new SqlParameter("@cohortId", cohortId));
cmd.ExecuteScalar();
}
}
}
/************************************************************************************
* Private Methods
************************************************************************************/
private bool StudentExists(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT Id, FirstName, LastName, SlackHandle
FROM Student
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
return reader.Read();
}
}
}
private bool CohortExists(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT Id, IsDayTime, CohortNum
FROM Cohort
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
return reader.Read();
}
}
}
private bool InstructorExists(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT Id, FirstName, LastName, SlackHandle
FROM Instructor
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
return reader.Read();
}
}
}
private bool ExerciseExists(int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT Id, ExName, ExLanguage
FROM Exercise
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
return reader.Read();
}
}
}
}
}
|
namespace TicketShopProject.Data.Repositories
{
public class IorderRepository
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RPSLab12
{
class Randy : Player
{
Random r = new Random();
public Randy()
{
SetName("Randy");
}
public override string GenerateRPS()
{
int choice = r.Next(1, 4);
string output = "rock";
switch (choice)
{
case 1: output = "rock";
break;
case 2: output = "paper";
break;
case 3: output = "scissors";
break;
}
return output;
}
}
}
|
using System;
namespace Nmli.Experimental
{
public class TruncatedNormalSampler
{
[ThreadStatic]
static Random rng;
static Random Rng
{
get
{
if (rng == null)
rng = new Random();
return rng;
}
}
static readonly double sqrt2 = Math.Sqrt(2);
public static double CDF(double mean, double stdev, double x)
{
// x -> z
double z = (x - mean) / (sqrt2 * stdev);
// z -> y
double y = 0;
Nmli.Mkl.ExclusiveExterns.AsRefs.vdErf(1, ref z, ref y);
// y -> q
double q = 0.5 * (1 + y);
return q;
}
public static double InvCDF(double mean, double stdev, double q)
{
// q -> y
double y = 2 * q - 1;
// y -> z
double z = 0;
Nmli.Mkl.ExclusiveExterns.AsRefs.vdErfInv(1, ref y, ref z);
// z -> x
double x = z * (sqrt2 * stdev) + mean;
return x;
}
static bool throwOnErrors = false;
public static bool ThrowOnErrors { get { return throwOnErrors; } set { throwOnErrors = value; } }
/// <summary>
/// Maps a Uniform(0,1] random variable to a truncated normal. Note this function is deterministic.
/// </summary>
/// <param name="mean">Mean of untruncated normal</param>
/// <param name="stdev">Stdev of untruncated normal</param>
/// <param name="minValue">Lower bound of support of truncated distribution</param>
/// <param name="uniformSample">The sample to map, should be on (0,1]</param>
/// <returns>A truncated normal sample</returns>
public static double UniformToTruncatedNormal(double mean, double stdev, double minValue, double uniformSample)
{
double a = 1 - CDF(mean, stdev, minValue); // P[X >= minValue]
if (a == 0)
{
if (throwOnErrors)
throw new ArgumentOutOfRangeException("minValue",
"The given normal distribution has insufficient mass above minValue");
else
return minValue;
}
double restrictedSample = a * (1 - uniformSample); // sample from Uniform (0, a]
double toInvert = 1 - restrictedSample; // sample from Uniform [1-a, 1)
double mapped = InvCDF(mean, stdev, toInvert);
return Math.Max(mapped, minValue); // because sometimes errors propogate through
}
/// <summary>
/// Generates a random sample from a truncated normal random variable
/// </summary>
/// <param name="mean">Mean of untruncated normal</param>
/// <param name="stdev">Stdev of untruncated normal</param>
/// <param name="minValue">Lower bound of support of truncated distribution</param>
/// <returns>A random sample from the truncated normal random variable</returns>
public static double SampleTruncatedNormal(double mean, double stdev, double minValue)
{
double uniformSample = 1 - Rng.NextDouble(); // sample from Uniform (0, 1]
return UniformToTruncatedNormal(mean, stdev, minValue, uniformSample);
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Event arguments for the <see cref="DbContext.SavingChanges" /> event.
/// </summary>
public class SavingChangesEventArgs : SaveChangesEventArgs
{
/// <summary>
/// Creates event arguments for the <see cref="M:DbContext.SavingChanges" /> event.
/// </summary>
/// <param name="acceptAllChangesOnSuccess"> The value passed to SaveChanges. </param>
public SavingChangesEventArgs(bool acceptAllChangesOnSuccess)
: base(acceptAllChangesOnSuccess)
{
}
}
}
|
namespace Plus.Communication.Packets.Outgoing.Rooms.Settings
{
internal class RoomMuteSettingsComposer : MessageComposer
{
public bool Status { get; }
public RoomMuteSettingsComposer(bool status)
: base(ServerPacketHeader.RoomMuteSettingsMessageComposer)
{
Status = status;
}
public override void Compose(ServerPacket packet)
{
packet.WriteBoolean(Status);
}
}
} |
using Logs.Authentication.Contracts;
using Logs.Models;
using Logs.Providers.Contracts;
using Logs.Services.Contracts;
using Logs.Web.Controllers;
using Logs.Web.Infrastructure.Factories;
using Logs.Web.Models.Nutrition;
using Moq;
using NUnit.Framework;
using System;
using TestStack.FluentMVCTesting;
namespace Logs.Web.Tests.Controllers.MeasurementControllerTests
{
[TestFixture]
public class GetMeasurementTests
{
[TestCase(1)]
[TestCase(6)]
[TestCase(1457)]
[TestCase(13)]
public void TestGetMeasurement_ShouldCallSeasurementServiceGetById(int id)
{
// Arrange
var mockedFactory = new Mock<IViewModelFactory>();
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedMeasurementService = new Mock<IMeasurementService>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var controller = new MeasurementController(mockedAuthenticationProvider.Object,
mockedMeasurementService.Object, mockedFactory.Object);
// Act
controller.GetMeasurement(id);
// Assert
mockedMeasurementService.Verify(s => s.GetById(id), Times.Once);
}
[TestCase(1)]
[TestCase(6)]
[TestCase(1457)]
[TestCase(13)]
public void TestGetMeasurement_ServiceReturnsNull_ShouldRenderPartialViewWithModelNull(int id)
{
// Arrange
var mockedFactory = new Mock<IViewModelFactory>();
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedMeasurementService = new Mock<IMeasurementService>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var controller = new MeasurementController(mockedAuthenticationProvider.Object,
mockedMeasurementService.Object, mockedFactory.Object);
// Act, Assert
controller
.WithCallTo(c => c.GetMeasurement(id))
.ShouldRenderPartialView("MeasurementDetails");
}
[TestCase(1)]
[TestCase(6)]
[TestCase(1457)]
[TestCase(13)]
public void TestGetMeasurement_ServiceReturnsMeasurement_ShouldCallFactoryCreateMeasurementViewModel(int id)
{
// Arrange
var date = new DateTime(1, 2, 3);
var measurement = new Measurement { Date = date };
var mockedFactory = new Mock<IViewModelFactory>();
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedMeasurementService = new Mock<IMeasurementService>();
mockedMeasurementService.Setup(s => s.GetById(It.IsAny<int>())).Returns(measurement);
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var controller = new MeasurementController(mockedAuthenticationProvider.Object,
mockedMeasurementService.Object, mockedFactory.Object);
// Act
controller.GetMeasurement(id);
// Assert
mockedFactory.Verify(f => f.CreateMeasurementViewModel(measurement, date), Times.Once);
}
[TestCase(1)]
[TestCase(6)]
[TestCase(1457)]
[TestCase(13)]
public void TestGetMeasurement_ServiceReturnsMeasurement_ShouldRenderPartialViewWithModel(int id)
{
// Arrange
var date = new DateTime(1, 2, 3);
var measurement = new Measurement { Date = date };
var model = new MeasurementViewModel();
var mockedFactory = new Mock<IViewModelFactory>();
mockedFactory.Setup(f => f.CreateMeasurementViewModel(It.IsAny<Measurement>(), It.IsAny<DateTime>()))
.Returns(model);
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedMeasurementService = new Mock<IMeasurementService>();
mockedMeasurementService.Setup(s => s.GetById(It.IsAny<int>())).Returns(measurement);
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var controller = new MeasurementController(mockedAuthenticationProvider.Object,
mockedMeasurementService.Object, mockedFactory.Object);
// Act, Assert
controller
.WithCallTo(c => c.GetMeasurement(id))
.ShouldRenderPartialView("MeasurementDetails")
.WithModel<MeasurementViewModel>(model);
}
}
}
|
using BancoABC.API.Domain;
using System.Collections.Generic;
using System.Linq;
namespace BancoABC.API.Services
{
public class UsuarioServices
{
private ABCDbContext _context;
public UsuarioServices(ABCDbContext context)
{
_context = context;
}
public Usuario Obter(int id)
{
return _context.Usuarios.Where(p => p.Id == id).FirstOrDefault();
}
public IList<Usuario> ListarTodos()
{
return _context.Usuarios.OrderBy(p => p.Nome).ToList();
}
public void Incluir(Usuario usuario)
{
_context.Usuarios.Add(usuario);
_context.SaveChanges();
}
public void Atualizar(Usuario usuario)
{
Usuario usuarioBD = _context.Usuarios.Where(p => p.Id == usuario.Id).FirstOrDefault();
if (usuarioBD != null)
{
usuarioBD.Nome = usuario.Nome;
usuarioBD.Idade = usuario.Idade;
usuarioBD.Documentos = usuario.Documentos;
usuarioBD.Enderecos = usuario.Enderecos;
usuarioBD.Email = usuario.Email;
usuarioBD.Genero = usuario.Genero;
usuarioBD.AplicativoUsuarios = usuario.AplicativoUsuarios;
_context.SaveChanges();
}
}
public void Excluir(int id)
{
Usuario usuario = Obter(id);
if (usuario != null)
{
_context.Usuarios.Remove(usuario);
_context.SaveChanges();
}
}
}
}
|
/************************************
** Created by Wizcas (wizcas.me)
************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class SpeechManager : UIBehaviour
{
[SerializeField]
private TextBubble _bubblePrefab;
protected override void Awake()
{
Messenger.AddListener<HumanThought>(HumanAI.HaveThoughtEvent, HaveThought);
}
private void HaveThought(HumanThought thought)
{
var speech = thought.RandomSpeech();
if (string.IsNullOrEmpty(speech)) return;
Show(thought.owner.transform, speech);
}
public void Show(Transform target, string content)
{
var bubble = Instantiate(_bubblePrefab, transform, false);
bubble.Show(target, content);
}
}
|
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyCompanyName.AbpZeroTemplate.Card
{
/// <summary>
/// 订单明细表
/// </summary>
public class OrderDetail : Entity<long>, IAudited
{
public long UserId { get; set; }
/// <summary>
/// 客户订单号
/// </summary>
public string OrderNum { get; set; }
/// <summary>
/// 身份证号
/// </summary>
public string IdCard { get; set; }
/// <summary>
/// 名字
/// </summary>
public string RealName { get; set; }
/// <summary>
/// 验证时间
/// </summary>
public DateTime? CheckTime { get; set; }
/// <summary>
/// 金额
/// </summary>
public int Money { get; set; }
/// <summary>
/// 当前余额
/// </summary>
public int CurrMoney { get; set; }
/// <summary>
/// 验证结果 01:实名认证正确 其他代码
/// </summary>
public string Status { get; set; }
/// <summary>
/// 无法验证原因,如"无法验证!【军人转业,户口迁移等】
/// </summary>
public string StatusMsg { get; set; }
/// <summary>
/// 请求IP
/// </summary>
public string RequestUrl { get; set; }
public DateTime CreationTime { get; set; }
public long? CreatorUserId { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
/// <summary>
/// 是否从API中获取的数据
/// </summary>
public bool IsApiData { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
}
}
|
namespace E04_MultiplicationSign
{
using System;
public class MultiplicationSign
{
public static void Main(string[] args)
{
// Write a program that shows the sign (+, - or 0) of the
// product of three real numbers, without calculating it.
// Use a sequence of if operators.
// Examples:
//
// a b c result
// 5 2 2 +
// -2 -2 1 +
// -2 4 3 -
// 0 -2.5 4 0
// -1 -0.5 -5.1 -
Console.Write("Please, enter first number : ");
double firstNumber = double.Parse(Console.ReadLine());
Console.Write("Please, enter second number : ");
double secondNumber = double.Parse(Console.ReadLine());
Console.Write("Please, enter thrid number : ");
double thirdNumber = double.Parse(Console.ReadLine());
if (firstNumber == 0 || secondNumber == 0 || thirdNumber == 0)
{
Console.WriteLine("The product is : \"{0}\"", 0);
}
else
{
bool positive = true;
if (firstNumber < 0)
{
positive = !positive;
}
if (secondNumber < 0)
{
positive = !positive;
}
if (thirdNumber < 0)
{
positive = !positive;
}
Console.WriteLine("The product is : \"{0}\"", positive ? "+" : "-");
}
Console.WriteLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Web;
namespace SIPCA.MVC.ViewModels
{
public class ApplicationUserConfiguration : EntityTypeConfiguration<ApplicationUser>
{
public ApplicationUserConfiguration()
{
Property(au => au.NombreUsuario).HasMaxLength(25).IsOptional();
Ignore(au => au.RoleList);
}
}
} |
using System;
using UIKit;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Helpers;
using Microsoft.Practices.ServiceLocation;
namespace Ts.Core.iOS
{
public abstract class BaseTableViewCell<TModel> : UITableViewCell, ICanNavigate
{
protected BaseTableViewCell () : base()
{
}
protected BaseTableViewCell (IntPtr handle) : base(handle)
{
}
protected BaseTableViewCell (UITableViewCellStyle style, string reuseIdentifier) : base(style, reuseIdentifier)
{
}
private INavigator _navigator;
public virtual INavigator Navigator {
get {
return _navigator ?? (_navigator = ServiceLocator.Current.GetInstance<INavigator> ());
}
set {
_navigator = value;
}
}
public abstract void UpdateCell (TModel model);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Rinsen.IdentityProvider.Contracts
{
public class RinsenClaimTypes
{
public const string Administrator = "http://rinsen.se/Administrator";
}
}
|
using Domen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SystemOperations.LekSO
{
public class FindObliciLekaSO : SystemOperationBase
{
protected override object ExecuteSO(IEntity entity)
{
JacinaLeka jacinaLeka = (JacinaLeka)entity;
return broker.Select(jacinaLeka).OfType<JacinaLeka>().ToList();
}
}
}
|
namespace RealEstate.ViewModels.Identity
{
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class AccountViewModels
{
[Required(ErrorMessage = "The username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "The password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DisplayName("Remember Me")]
public bool IsRemember { get; set; }
}
public class ChangePasswordViewModels
{
[Required(ErrorMessage = "This fied is required")]
public string OldPassword { get; set; }
[Required(ErrorMessage = "This fied is required")]
[MinLength(6, ErrorMessage = "Minimum length is 6")]
public string Password { get; set; }
[Required(ErrorMessage = "This fied is required")]
[Compare("Password", ErrorMessage = "Invalid confirm password")]
public string ConfirmPassword { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GSF;
using GSF.Concurrency;
namespace Server.Ingame
{
interface IMatchResolver
{
/// <summary>
/// 이 메소드를 구현하여, 매치 정보를 어딘가에 기록한다.
/// * 메모리 어딘가
/// * DB 어딘가
/// * 파일 어딘가
/// </summary>
/// <param name="matchToken">매치 토큰 (KEY)</param>
/// <param name="match">매치 정보 (VALUE)</param>
/// <returns></returns>
[ThreadSafe]
Task RegisterMatch(string matchToken, MatchMaking.MatchData match);
/// <summary>
/// 이 메소드를 구현하여, 어딘가에 저장한 매치 정보를 가져온다.
/// </summary>
/// <param name="matchToken">매치 토큰 (KEY)</param>
/// <returns></returns>
[ThreadSafe]
Task<MatchMaking.MatchData> GetMatchInfo(string matchToken);
}
}
|
using Acr.UserDialogs;
using Android.App;
using Android.Content;
using Firebase.Storage;
using StaffBusser.Droid.HelperClass;
using StaffBusser.SharedCode;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(DroidHelperClass))]
namespace StaffBusser.Droid.HelperClass
{
public class DroidHelperClass : IHelperClass
{
public void IsLoading(bool isLoading, string text = "")
{
if (!isLoading)
{
UserDialogs.Instance.HideLoading();
}
else
{
UserDialogs.Instance.ShowLoading(text, MaskType.Black);
}
}
public readonly static DroidHelperClass Default = new DroidHelperClass();
public string GetToken { get; set; } // add setting properties as you wish
public void IsAlert()
{
//UserDialogs.Instance.ShowLoading("User Already Excist", MaskType.Black);
UserDialogs.Instance.Alert("User Already Excist", "Thankyou");
}
public void DebugMEssage(string text)
{
System.Console.WriteLine("text");
}
private const int Pick_image_request = 71;
public void UploadImage()
{
//var storage = FirebaseStorage.Instance;
//var storageRef = storage.GetReference("gs://staff-busser.appspot.com");
//var spaceRef = storageRef.Child("Jens/profile.jpg");
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
((Activity)Forms.Context).StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), Pick_image_request);
}
}
} |
// -----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using Mlos.SettingsSystem.Attributes;
[assembly: DispatchTableNamespace(@namespace: "SmartSharedChannel")]
|
using Amazon;
namespace csharp_intermediate
{
public class GoldCustomer: Customer
{
public void OfferVoucher()
{
// var rating = this.CalculateRating(excludeOrders: true);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace HttpClientsExamples
{
class Program
{
static void Main(string[] args)
{
// 2 verschiede Klassen
// 1. WebClient-Klasse
// 2. HttpClient-Klasse
//using var wc = new WebClient();
//var result = wc.DownloadString("http://codework.me:8080/");
//Console.WriteLine(result);
using var httpClient = new HttpClient()
{
Timeout = new TimeSpan(0, 0, 0, 5),
BaseAddress = new Uri("http://codework.me:8080/")
};
//HttpRequestMessage getRequest = new HttpRequestMessage(HttpMethod.Get, "");
//HttpResponseMessage getResponse = httpClient.SendAsync(getRequest).Result;
//Console.WriteLine(getResponse.Content.ReadAsStringAsync().Result);
//var listRequest = new HttpRequestMessage(HttpMethod.Get, "list");
//var listResponse = httpClient.SendAsync(listRequest).Result;
//string listContent = listResponse.Content.ReadAsStringAsync().Result;
//List<WeatherEntry> weatherList = JsonSerializer.Deserialize<List<WeatherEntry>>(listContent);
//if (weatherList != null)
//{
// foreach (WeatherEntry e in weatherList)
// {
// Console.WriteLine($"Entry with Id {e.Id} has temperature {e.Temperature}°C.");
// }
//}
//var neuerEintrag = new WeatherEntry()
//{
// Id = 7,
// Temperature = 8.9,
// Pressure = 981,
// Prediction = "Cloudy",
// Datetime = DateTime.Now,
//};
//HttpRequestMessage postRequest = new HttpRequestMessage(HttpMethod.Post, "add");
//postRequest.Content = new StringContent(JsonSerializer.Serialize(neuerEintrag));
//var postResponse = httpClient.SendAsync(postRequest).Result;
//Console.WriteLine(postResponse.ReasonPhrase);
//var changedEntry = new WeatherEntry()
//{
// Id = 1,
// Temperature = 38.1,
// Pressure = 1022,
// Prediction = "Scorching",
// Datetime = DateTime.Now,
//};
//var putRequest = new HttpRequestMessage(HttpMethod.Put, "edit");
//putRequest.Content = new StringContent(JsonSerializer.Serialize(changedEntry));
//var putReponse = httpClient.SendAsync(putRequest).Result;
//Console.WriteLine(putReponse.ReasonPhrase);
string apikey = "dsfja030wnfnafnwamf0wamfwang0wqng09nswgqw03ngqne";
var deleteEntry = new WeatherEntry()
{
Id = 7,
};
var deleteRequest = new HttpRequestMessage(HttpMethod.Delete, "remove");
deleteRequest.Headers.Add("X-Api-Token", apikey);
deleteRequest.Content = new StringContent(JsonSerializer.Serialize(deleteRequest));
var deleteReponse = httpClient.SendAsync(deleteRequest).Result;
Console.WriteLine(deleteReponse.ReasonPhrase);
// Convenience-Methoden:
//var res2 = httpClient.GetAsync(uri).Result;
Console.WriteLine("\nPress any key to quit.");
Console.ReadKey();
}
}
class WeatherEntry
{
[JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("temperature")] public double Temperature { get; set; }
[JsonPropertyName("pressure")] public int Pressure { get; set; }
[JsonPropertyName("prediction")] public string Prediction { get; set; }
[JsonPropertyName("datetime")] public DateTime Datetime { get; set; }
}
}
|
namespace GildedRose.Console
{
public class LegendaryItemUpdateStrategy : IItemUpdateStrategy
{
public void Update(Item item)
{
}
}
}
|
using System;
using UnityEngine;
using UnityEngine.Assertions;
namespace UnityUIPlayables
{
[Serializable]
public class Curve
{
[SerializeField] private CurveType _curveType;
[SerializeField] [EnabledIf(nameof(_curveType), (int) CurveType.Easing)]
private EaseType _easeType;
[NormalizedAnimationCurve(false)]
[EnabledIf(nameof(_curveType), (int) CurveType.AnimationCurve)]
[SerializeField]
private AnimationCurve _animationCurve;
public float Evaluate(float progress)
{
Assert.IsTrue(progress >= 0.0f);
Assert.IsTrue(progress <= 1.0f);
switch (_curveType)
{
case CurveType.Easing:
return Easings.Interpolate(progress, _easeType);
case CurveType.AnimationCurve:
return _animationCurve.Evaluate(progress);
default:
throw new ArgumentOutOfRangeException();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Eventual.EventStore.Readers
{
public class EventStreamCheckpoint
{
#region Attributes
private string streamId;
private int revisionId;
private int eventId;
#endregion
#region Constructors
private EventStreamCheckpoint() { }
private EventStreamCheckpoint(string streamId, int revisionId, int eventId)
{
this.StreamId = streamId;
this.RevisionId = revisionId;
this.EventId = eventId;
}
#endregion
#region Factory methods
public static EventStreamCheckpoint CreateStreamCheckpoint(string streamId, int revisionId, int eventId)
{
return new EventStreamCheckpoint(streamId, revisionId, eventId);
}
public static EventStreamCheckpoint Empty
{
get
{
return CreateStreamCheckpoint(null, 0, 0);
}
}
#endregion
#region Properties
public string StreamId
{
get
{
return streamId;
}
private set
{
//TODO: Insert validation code here
streamId = value;
}
}
public int RevisionId
{
get
{
return this.revisionId;
}
private set
{
//TODO: Insert validation code here
this.revisionId = value;
}
}
public int EventId
{
get
{
return eventId;
}
private set
{
//TODO: Insert validation code here
eventId = value;
}
}
#endregion
}
}
|
// XAML Map Control - http://xamlmapcontrol.codeplex.com/
// © 2016 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Windows;
using System.Windows.Media;
namespace MapControl
{
public partial class TileLayer
{
static TileLayer()
{
IsHitTestVisibleProperty.OverrideMetadata(
typeof(TileLayer), new FrameworkPropertyMetadata(false));
}
private Rect GetTileIndexBounds(int zoomLevel)
{
var scale = (double)(1 << zoomLevel) / 360d;
var transform = parentMap.ViewportTransform.Matrix;
transform.Invert(); // view to map coordinates
transform.Translate(180d, -180d);
transform.Scale(scale, -scale); // map coordinates to tile indices
return new MatrixTransform(transform).TransformBounds(new Rect(parentMap.RenderSize));
}
private void SetRenderTransform()
{
var scale = Math.Pow(2d, parentMap.ZoomLevel - TileGrid.ZoomLevel);
var offsetX = parentMap.ViewportOrigin.X - (180d + parentMap.MapOrigin.X) * parentMap.ViewportScale;
var offsetY = parentMap.ViewportOrigin.Y - (180d - parentMap.MapOrigin.Y) * parentMap.ViewportScale;
var transform = new Matrix(1d, 0d, 0d, 1d, TileSource.TileSize * TileGrid.XMin, TileSource.TileSize * TileGrid.YMin);
transform.Scale(scale, scale);
transform.Translate(offsetX, offsetY);
transform.RotateAt(parentMap.Heading, parentMap.ViewportOrigin.X, parentMap.ViewportOrigin.Y);
((MatrixTransform)RenderTransform).Matrix = transform;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestProject1.General
{
class TablesMethods
{
private Base baseIns;
public TablesMethods(Base baseIns)//:base() //Open Google home page
{
this.baseIns = baseIns;
}
// public int getNumberOfRows(Base selector) { //get number of rows
// int numberOfRows;
// return numberOfRows;
// }
//get number of columns
//get list of column headers(it should be a list of name)
//get list of cells of specific row
//get list of cells of specific column
//get value of cell of specific row and column
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Globalization;
namespace SchedulerTask
{
class Reader
{
XDocument sdata;
XDocument tdata;
DateTime begin;
DateTime end;
string datapattern = "dd.MM.yyyy";
string dtpattern = "MM.dd.yyy H:mm:ss";
Dictionary<int, IEquipment> eqdic;
Dictionary<int,Operation> opdic;
List<Party> partlist;
XNamespace df;
public Reader()
{
sdata = XDocument.Load("system.xml");
tdata = XDocument.Load("tech.xml");
}
public Dictionary<int, IEquipment> ReadSystemData() //чтение данных по расписанию и станкам
{
List<Interval> intlist = new List<Interval>();
List<Interval> doneintlist = new List<Interval>();
eqdic = new Dictionary<int, IEquipment>();
DateTime start = new DateTime();
DateTime end = new DateTime();
XElement root = sdata.Root;
df = sdata.Root.Name.Namespace;
foreach (XElement elm in root.Descendants(df + "CalendarInformation"))
{
if (elm.Attribute("date_begin") != null)
{
string date = elm.Attribute("date_begin").Value;
DateTime.TryParseExact(date, datapattern, null, DateTimeStyles.None, out start);
}
if (elm.Attribute("date_end") != null)
{
string date = elm.Attribute("date_end").Value;
DateTime.TryParseExact(date, datapattern, null, DateTimeStyles.None, out end);
}
foreach (XElement eg in elm.Elements(df + "EquipmentGroup"))
{
foreach (XElement inc in eg.Elements(df + "Include"))
{
DateTime tmpdata = start;
while (tmpdata != end)
{
if ((int)tmpdata.DayOfWeek == int.Parse(inc.Attribute("day_of_week").Value))
{
int ind = inc.Attribute("time_period").Value.IndexOf("-");
int sh = int.Parse(inc.Attribute("time_period").Value.Substring(0, 1));
int eh = int.Parse(inc.Attribute("time_period").Value.Substring(ind + 1, 2));
intlist.Add(new Interval(new DateTime(tmpdata.Year, tmpdata.Month, tmpdata.Day, sh, 0, 0), new DateTime(tmpdata.Year, tmpdata.Month, tmpdata.Day, eh, 0, 0)));
}
tmpdata = tmpdata.AddDays(1);
}
}
foreach (XElement exc in eg.Elements(df + "Exclude"))
{
foreach (Interval t in intlist)
{
if ((int)t.GetStartTime().DayOfWeek == int.Parse(exc.Attribute("day_of_week").Value))
{
int ind = exc.Attribute("time_period").Value.IndexOf("-");
int sh = int.Parse(exc.Attribute("time_period").Value.Substring(0, 2));
int eh = int.Parse(exc.Attribute("time_period").Value.Substring(ind + 1, 2));
DateTime dt = t.GetStartTime().AddHours(-t.GetStartTime().Hour);
Interval tmpint;
doneintlist.Add(SeparateInterval(t, dt.AddHours(sh), dt.AddHours(eh), out tmpint));
doneintlist.Add(tmpint);
}
}
}
}
}
Calendar calendar = new Calendar(doneintlist);
foreach (XElement elm in root.Descendants(df + "EquipmentInformation").Elements(df + "EquipmentGroup"))
{
GroupEquipment tmp = new GroupEquipment(calendar, int.Parse(elm.Attribute("id").Value), elm.Attribute("name").Value);
foreach (XElement eg in elm.Elements(df + "EquipmentGroup"))
{
GroupEquipment gtmp = new GroupEquipment(calendar, int.Parse(eg.Attribute("id").Value), eg.Attribute("name").Value);
foreach (XElement eq in eg.Elements(df + "Equipment"))
{
SingleEquipment stmp = new SingleEquipment(calendar, int.Parse(eq.Attribute("id").Value), eq.Attribute("name").Value);
eqdic.Add(stmp.GetID(), stmp);
gtmp.AddEquipment(stmp);
}
tmp.AddEquipment(gtmp);
eqdic.Add(gtmp.GetID(), gtmp);
}
eqdic.Add(tmp.GetID(), tmp);
}
return eqdic;
}
public void ReadTechData(out List<Party> partlist, out Dictionary<int, IOperation> opdic) //чтение данных по деталям и операциям
{
XElement root = tdata.Root;
df = root.Name.Namespace;
partlist = new List<Party>();
opdic = new Dictionary<int, IOperation>();
List<IOperation> tmpop;
foreach (XElement product in root.Descendants(df + "Product"))
{
foreach (XElement part in product.Elements(df + "Part"))
{
DateTime.TryParseExact(part.Attribute("date_begin").Value, datapattern, null, DateTimeStyles.None, out begin);
DateTime.TryParseExact(part.Attribute("date_end").Value, datapattern, null, DateTimeStyles.None, out end);
Party parent = new Party(begin, end, int.Parse(part.Attribute("priority").Value), part.Attribute("name").Value, int.Parse(part.Attribute("num_products").Value));
tmpop = ReadOperations(part , parent, opdic);
foreach(IOperation op in tmpop)
{
parent.addOperationToForParty(op);
}
foreach (XElement subpart in part.Elements(df + "SubPart"))
{
Party sp = new Party(subpart.Attribute("name").Value, int.Parse(subpart.Attribute("num_products").Value));
tmpop = ReadOperations(subpart, parent, opdic);
foreach (IOperation op in tmpop)
{
sp.addOperationToForParty(op);
}
parent.addSupParty(sp);
//partlist.Add(sp);
}
partlist.Add(parent);
}
}
}
private List<IOperation> ReadOperations(XElement part, Party parent, Dictionary<int, IOperation> opdic)
{
List<IOperation> tmpop = new List<IOperation>();
foreach (XElement oper in part.Elements(df + "Operation"))
{
List<IOperation> pop = new List<IOperation>();
if (oper.Elements(df + "Previous") != null)
{
foreach (XElement prop in oper.Elements(df + "Previous"))
{
pop.Add(opdic[int.Parse(prop.Attribute("id").Value)]);
}
}
int id = int.Parse(oper.Attribute("id").Value);
int duration = int.Parse(oper.Attribute("duration").Value);
int group = int.Parse(oper.Attribute("equipmentgroup").Value);
tmpop.Add(new Operation(id, oper.Attribute("name").Value,new TimeSpan(duration, 0, 0), pop, eqdic[group], parent));
opdic.Add(id, new Operation(id, oper.Attribute("name").Value, new TimeSpan(duration, 0, 0), pop, eqdic[group], parent));
}
return tmpop;
}
private Interval SeparateInterval(Interval ii, DateTime start, DateTime end, out Interval oi)
{
oi = new Interval(end, ii.GetEndTime());
return new Interval(ii.GetStartTime(), start);
}
}
}
|
using DFe.Utils;
using MetroFramework;
using MetroFramework.Forms;
using System;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Estoque.ImportacaoNFeEntrada
{
public partial class FEST_EscolhaFormatoImportacaoNFe : DevExpress.XtraEditors.XtraForm
{
public FEST_EscolhaFormatoImportacaoNFe()
{
InitializeComponent();
}
private void pictureBox2_Click(object sender, EventArgs e)
{
// Baixar NFe
new FEST_IdentificacaoChave().ShowDialog(this);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
CarregarXML();
}
public void CarregarXML()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Arquivo .XML|*.xml";
openFileDialog1.Title = "Selecione o Arquivo XML da NF-e";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
//Chamar a Tela de Importação do XML da NFe
NFe.Classes.NFe ArquivoXML = FuncoesXml.XmlStringParaClasse<NFe.Classes.NFe>(FuncoesXml.ObterNodeDeArquivoXml("NFe", openFileDialog1.FileName));
new metroButton5(ArquivoXML).ShowDialog();
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, "FORMATO DE IMPORTAÇÃO");
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Task02_CompanyApp
{
public partial class Site : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.DropDownList1.SelectedIndex == 0)
{
Response.Redirect("~/BG/Home.aspx");
}
else if (this.DropDownList1.SelectedIndex == 1)
{
Response.Redirect("~/EN/Home.aspx");
}
else if (this.DropDownList1.SelectedIndex == 2)
{
Response.Redirect("~/DE/Home.aspx");
}
}
}
} |
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 Newtonsoft.Json.Linq;
namespace protótipos
{
public partial class login : Form
{
string url = "http://localhost/Projeto-Estoque-master/";
public login()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void login_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form = new Form1();
form.Show();
try
{
JObject user = get.post(url + "login.php", "&cpf=" + txtCpf.Text + "&senha=" + txtSenha.Text);
var status = user["status"];
if (status.ToString() == "True")
{
txtCpf.Text = "";
txtSenha.Text = "";
form = new Form1();
form.Show();
if (user["type"].ToString() == "2")
{
form.bloqueia();
}
this.Visible = false;
}
else
{
MessageBox.Show("CPF ou senha errados!");
}
}
catch
{
MessageBox.Show("CPF ou senha errados");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestGrabbableObject : VRTK.VRTK_InteractableObject {
public enum EItemID
{
small,
normal,
big
}
public EItemID id;
private BoxCollider bc;
// Use this for initialization
void Start () {
bc = GetComponent<BoxCollider>();
}
// Update is called once per frame
override protected void Update () {
base.Update();
if (IsGrabbed())
{
GetComponent<MeshRenderer>().material.color = new Color(1, 0, 0);
bc.isTrigger = true;
}
else
{
GetComponent<MeshRenderer>().material.color = new Color(0, 0, 1);
bc.isTrigger = false;
}
}
void OnCollisionEnter(Collision col)
{
if(col.gameObject.GetComponent<Bag>())
{
}
}
void OnTriggerStay(Collider other)
{
}
void OnTriggerExit(Collider other)
{
//if(other.gameObject.GetComponent<Bag>())
//{
// GetComponent<BoxCollider>().isTrigger = false;
//}
}
}
|
using System.Collections.Generic;
using System;
using System.Text;
using BrainDuelsLib.view;
using BrainDuelsLib.view.forms;
using BrainDuelsLib.web;
using BrainDuelsLib.web.exceptions;
using BrainDuelsLib.model.entities;
namespace BrainDuelsLib.widgets
{
public class LobbyWidget : Widget, IStoppable
{
private Server.TokenAndId tai;
private bool isChallenging = false;
private LobbyWidgetCallbackStore store = new LobbyWidgetCallbackStore();
public LobbyWidgetCallbackStore Callbacks
{
get
{
return store;
}
}
public class LobbyWidgetCallbackStore : CallbackStore
{
public Action<BrainDuelsLib.threads.Game> goToGameAsPlayerCallback = delegate(BrainDuelsLib.threads.Game game) { };
public Action<BrainDuelsLib.threads.Game> goToGameAsObserverCallback = delegate(BrainDuelsLib.threads.Game game) { };
public Action<List<int>> getPlayersCallback = delegate(List<int> players) { };
public BrainDuelsLib.delegates.Action<int, string, string, int> rejectedChallengeCallback = delegate(int a, string aa, string aaa, int id) { };
public BrainDuelsLib.delegates.Action<int, string, string, int> newChallengeCallback = delegate(int a, string aa, string aaa, int id) { };
public BrainDuelsLib.delegates.Action unexpiredChallengeCallback = delegate() { };
public BrainDuelsLib.delegates.Action<int> expiredChallengeCallback = delegate(int a) { };
public BrainDuelsLib.delegates.Action repeatedCallback = delegate() { };
public Action<List<threads.Game>> gamesCallback = delegate(List<threads.Game> players) { };
}
public class LobbyWidgetControlsStore : CallbackStore
{
public UserInfoWidget meInfoWidget;
public GamesChallengesLobbyControl challengesControl;
public LobbyBackendWidget backgroud;
}
private LobbyWidgetControlsStore controlsStore = new LobbyWidgetControlsStore();
public LobbyWidgetControlsStore Controls
{
get
{
return controlsStore;
}
}
public LobbyWidget(Server.TokenAndId tai)
: base()
{
this.tai = tai;
}
public override void Go()
{
base.Go();
//User me = Server.GetUser(tai, tai.id);
//if(Controls.meInfoWidget != null){
//Controls.meInfoWidget.Update(me);
//}
Controls.backgroud.Callbacks.gamesCallback = OnGamesCallback;
if (Controls.challengesControl != null)
{
Controls.challengesControl.SetOnEnterGameAsPlayerCallback(OnEnterGameAsPlayer);
Controls.challengesControl.SetOnEnterGameAsObserverCallback(OnEnterGameAsObserver);
Controls.challengesControl.SetOnLeaveGameCallback(OnLeaveGame);
}
Controls.backgroud.Callbacks.goToGameCallback = OnGoToGameCallback;
Controls.backgroud.Callbacks.errorCallback = delegate(Exception e)
{
store.errorCallback(e);
Controls.backgroud.Stop();
};
Controls.backgroud.Callbacks.usersCallback = delegate(List<int> l)
{
Callbacks.getPlayersCallback(l);
};
Controls.backgroud.Callbacks.rejectedChallengeCallback = delegate(int a, string aa, string aaa, int id)
{
this.Controls.backgroud.Expire(id);
this.Callbacks.rejectedChallengeCallback(a, aa, aaa, id);
};
Controls.backgroud.Callbacks.newChallengeCallback = delegate(int a, string aa, string aaa, int id)
{
this.Callbacks.newChallengeCallback(a, aa, aaa, id);
};
Controls.backgroud.Callbacks.expireChallengeCallback = delegate(int id)
{
this.Callbacks.expiredChallengeCallback(id);
};
Controls.backgroud.Callbacks.repeatedCallback = delegate()
{
this.Callbacks.repeatedCallback();
};
Controls.backgroud.Go();
}
public void CreateNewChallenge(int ch, string title, string settings)
{
if (Controls.backgroud.CanChallenge())
{
Controls.backgroud.ChallengeUser(ch, title, settings);
}
else
{
this.Callbacks.unexpiredChallengeCallback();
}
}
public void AcceptChallenge(int ch, string title, string settings, int id)
{
Controls.backgroud.AcceptChallenge(ch, title, settings, id);
}
public void RejectChallenge(int ch, string title, string settings, int id)
{
Controls.backgroud.RejectChallenge(ch, title, settings, id);
}
public void CreateNewGame(int max, string title, string settings)
{
Controls.backgroud.CreateNewGame(max, title, settings);
isChallenging = true;
}
public void OnGamesCallback(List<threads.Game> _games)
{
List<threads.Game> gms = new List<BrainDuelsLib.threads.Game>();
foreach (BrainDuelsLib.threads.Game game in _games)
{
BrainDuelsLib.threads.Game n = game.Copy();
gms.Add(n);
}
Callbacks.gamesCallback(gms);
}
public void OnGoToGameCallback(BrainDuelsLib.threads.Game game)
{
Callbacks.goToGameAsPlayerCallback(game);
}
public void OnEnterGameAsObserver(BrainDuelsLib.threads.Game game)
{
Callbacks.goToGameAsObserverCallback(game);
}
public void OnEnterGameAsPlayer(BrainDuelsLib.threads.Game game)
{
Controls.backgroud.EnterGame(game.id);
}
public void OnLeaveGame(BrainDuelsLib.threads.Game game)
{
Controls.backgroud.LeaveGame(game.id);
}
public void Stop()
{
Controls.backgroud.Stop();
}
public void Discard()
{
this.Controls.backgroud.ExpireAll();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Navigation.Models
{
public class CommentPhoto
{
public int Id { get; set; }
public int CommentId { get; set; }
public string Photo { get; set; }
public Comment Comment { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Foemulario3.Shared
{
public static class DicionarioToObject
{
public static Usuario DictionaryToUsuario(Usuario usuario, IDictionary<string, object> value)
{
if (usuario == null)
{
usuario = new Usuario();
}
foreach (string field in value.Keys)
{
switch (field)
{
case "Id":
usuario.Id = (int)value[nameof(Usuario.Id)];
break;
case "Nome":
usuario.Nome = (string)value[nameof(Usuario.Nome)];
break;
case "Idade":
usuario.Idade = (int)value[nameof(Usuario.Idade)];
break;
}
}
return usuario;
}
}
} |
namespace Baseline.Web
{
/// <summary>
/// Specifies Media Types (formerly known as MIME types) and Media Subtypes that are listed by the IANA.
/// <see href="http://www.iana.org/assignments/media-types/media-types.xhtml"/>
/// </summary>
public static class MediaTypes
{
public static class Multipart
{
/// <summary>
/// Returning Values from Forms: multipart/form-data.
/// <see href="https://tools.ietf.org/html/rfc7578"/>
/// </summary>
public const string FormData = "multipart/form-data";
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Http;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace PCGuardWebAPI
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// 應用程式啟動時執行的程式碼
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//無論如何都使用 JSON 回傳.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
//不使用JS駝峰式命名
//var jsonformatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
//jsonformatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//改用Json.net的序列化設定,並指定 TypeNameHandling.All 來支援序列化虛擬類別與Interface
var config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
}
}
} |
namespace ADXETools.Model
{
/// <summary>
///
/// </summary>
public class ImageData
{
}
} |
using System.Collections.Generic;
using System.Linq;
namespace NWERC.DigitalClock
{
public class Sample
{
public List<SevenSegment> Segments; // 4 segments
public int Hours { get { return Segments[0].Digit * 10 + Segments[1].Digit; } }
public int Minutes { get { return Segments[2].Digit * 10 + Segments[3].Digit; } }
public Sample()
{
Segments = new List<SevenSegment>();
}
public Sample(List<SevenSegment> segments)
{
Segments = segments;
}
public List<Sample> CreateDeratives()
{
var hours10_deratives = Segments[0].FindDeratives();
var hours1_deratives = Segments[1].FindDeratives();
var mins10_deratives = Segments[2].FindDeratives();
var mins1_deratives = Segments[3].FindDeratives();
return (from hour10 in hours10_deratives
from hour1 in hours1_deratives
from mins10 in mins10_deratives
from mins1 in mins1_deratives
let hour = hour10.Digit*10 + hour1.Digit
let min = mins10.Digit*10 + mins1.Digit
where hour <= 23 && min <= 59
select new List<SevenSegment> {hour10, hour1, mins10, mins1}
into derativeSegments select new Sample(derativeSegments)).ToList();
List<Sample> deratives = new List<Sample>();
foreach(SevenSegment hour10 in hours10_deratives)
{
foreach(SevenSegment hour1 in hours1_deratives)
{
foreach(SevenSegment mins10 in mins10_deratives)
{
foreach(SevenSegment mins1 in mins1_deratives)
{
int hour = hour10.Digit*10 + hour1.Digit;
int min = mins10.Digit*10 + mins1.Digit;
if (hour <= 23 && min <= 59)
{
var derativeSegments = new List<SevenSegment> {hour10, hour1, mins10, mins1};
deratives.Add(new Sample(derativeSegments) );
}
}
}
}
}
return deratives;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grupo5_Hotel.Entidades.Excepciones
{
public class ErrorServidorException : Exception
{
public ErrorServidorException (string error) : base ("Hubo un error en la petición al servidor. Detalle: " + error) { }
}
}
|
using PDV.DAO.Atributos;
using System;
namespace PDV.DAO.GridViewModels
{
public class MovimentoDeEstoquePorProdutoGridViewModel
{
[CampoTabela(nameof(IDProduto))]
public decimal IDProduto { get; set; }
[CampoTabela(nameof(CDeBarras))]
public string CDeBarras { get; set; }
[CampoTabela(nameof(Produto))]
public string Produto { get; set; }
[CampoTabela(nameof(ValorCusto))]
public decimal ValorCusto { get; set; }
[CampoTabela(nameof(ValorVenda))]
public decimal ValorVenda { get; set; }
[CampoTabela(nameof(Grupo))]
public string Grupo { get; set; }
[CampoTabela(nameof(Entrada))]
public decimal Entrada { get; set; }
[CampoTabela(nameof(Saida))]
public decimal Saida { get; set; }
[CampoTabela(nameof(Total))]
public decimal Total { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dominio;
using Negocio;
namespace WebForm___VoucherPromo
{
public partial class FormularioClienteFilled : System.Web.UI.Page
{
public List<Cliente> listaCliente;
public Cliente cliente;
protected void Page_Load(object sender, EventArgs e)
{
try
{
ClienteNegocio cliente = new ClienteNegocio();
//var clienteViejo = Convert.ToInt32(Request.QueryString["DNI"]);
listaCliente = cliente.listar();
}
catch (Exception ex)
{
throw ex;
}
}
}
} |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
namespace Demo.DynamicCSharp.CommandLine.Providers
{
public class AssemblyProvider : IAssemblyProvider
{
public Assembly GetAssemblyFor(string source)
{
var providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
};
var provider = new CSharpCodeProvider(providerOptions);
var parameters = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
ReferencedAssemblies = { "Demo.DynamicCSharp.CommandLine.exe" }
};
var result = provider.CompileAssemblyFromSource(parameters, source);
if (result.Errors.HasErrors)
{
var errorString = FormatErrors(result.Errors);
throw new Exception($"Compilation failed. {errorString}");
}
return result.CompiledAssembly;
}
private static string FormatErrors(CompilerErrorCollection errors)
{
var builder = new StringBuilder();
for (var index = 0; index < errors.Count; index++)
{
var error = errors[index];
builder.Append($"\"{error.ErrorText}\" (line {error.Line}) ");
}
return builder.ToString();
}
}
} |
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
namespace NetFabric.Hyperlinq.SourceGenerator
{
static class StringExtensions
{
public static string ToCommaSeparated(this string[] strings)
=> string.Join(", ", strings);
public static string ToCommaSeparated(this IEnumerable<string> strings)
=> string.Join(", ", strings);
public static string ToCommaSeparated(this IReadOnlyList<string> strings)
=> strings.Count switch
{
0 => string.Empty,
1 => strings[0],
_ => AppendCommaSeparated(new StringBuilder(), strings).ToString(),
};
public static StringBuilder AppendCommaSeparated(this StringBuilder builder, IReadOnlyList<string> strings)
=> strings.Count switch
{
0 => builder,
1 => builder.Append(strings[0]),
_ => PerformAppendCommaSeparated(builder, strings),
};
static StringBuilder PerformAppendCommaSeparated(this StringBuilder builder, IReadOnlyList<string> strings)
{
_ = builder.Append(strings[0]);
for (var index = 1; index < strings.Count; index++)
{
_ = builder.Append(", ").Append(strings[index]);
}
return builder;
}
public static string ApplyMappings(this string value, ImmutableArray<(string, string, bool)> genericsMapping, out bool isConcreteType)
{
var result = value;
isConcreteType = false;
if (!genericsMapping.IsDefault)
{
foreach (var (from, to, isConcreteType2) in genericsMapping.Reverse())
{
if (value == from && isConcreteType2)
{
isConcreteType = true;
return value.Replace(from, to);
}
result = result.Replace(from, to);
}
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace TE18B_01_first
{
class Program
{
static void Main(string[] args)
{
//string efternamn = "Bergström";
string namn = Console.ReadLine();
Console.WriteLine("Hello, " + namn);
if (namn == "Micke")
{
Console.WriteLine("Du är bäst!");
}
else
{
Console.WriteLine("Du är nästan bäst, du också!");
}
Thread.Sleep(500);
Console.WriteLine("hej");
namn = "Henry";
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CivilGis.Controllers
{
public class ArcgisController : Controller
{
// GET: Arcgis
public ActionResult Index()
{
return View();
}
//----------------------- simple map section -------------------------------
public ActionResult simplemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/simplemap.cshtml");
}
public ActionResult justtiles(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/justtiles.cshtml");
}
public ActionResult justtiles_old_slider_switch(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/justtiles_old_slider_switch.cshtml");
}
public ActionResult simpleclustermap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/simpleclustermap.cshtml");
}
public ActionResult clusterpagedclienttablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/clusterpagedclienttablemap.cshtml");
}
public ActionResult clusterscrollerclienttablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/clusterscrollerclienttablemap.cshtml");
}
public ActionResult colormap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/colormap.cshtml");
}
//----------------------- End simple map section -------------------------------
//----------------------- table map section -------------------------------
public ActionResult pagedclienttablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/pagedclienttablemap.cshtml");
}
public ActionResult scrollerclienttablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/scrollerclienttablemap.cshtml");
}
public ActionResult pagedservertablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/pagedservertablemap.cshtml");
}
public ActionResult scrollerservertablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/scrollerservertablemap.cshtml");
}
public ActionResult pagedfulltablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/pagedfulltablemap.cshtml");
}
public ActionResult scrollerfulltablemap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/scrollerfulltablemap.cshtml");
}
//-----------------------End table map section -------------------------------
//----------------------- classification map section -------------------------------
public ActionResult classifycheckboxbuttonmap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/classifycheckboxbuttonmap.cshtml");
}
public ActionResult classifyradiobuttonmap(string frontmap, string area, string subject)
{
ViewBag.Subject = subject; // for api call
ViewBag.Side_Bar = area;
ViewBag.Area = area;
return View("~/Views/Arcgis/" + frontmap + "/classifyradiobuttonmap.cshtml");
}
//-----------------------end classification map section -------------------------------
}
} |
using System;
namespace Fairmas.PickupTracking.Shared.ViewModels
{
public class HotelViewModel : ViewModelBase
{
public int Id { get; set; }
public Guid Guid { get; internal set; }
public string Name { get; set; }
public string City { get; set; }
public bool AllowNavigate { get; set; }
public bool UpToDate { get; set; }
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// Well, we're here in Destiny 2, and Talent Grids are unfortunately still around. The good news is that they're pretty much only being used for certain base information on items and for Builds/Subclasses. The bad news is that they still suck. If you really want this information, grab this component. An important note is that talent grids are defined as such: A Grid has 1:M Nodes, which has 1:M Steps. Any given node can only have a single step active at one time, which represents the actual visual contents and effects of the Node (for instance, if you see a \"Super Cool Bonus\" node, the actual icon and text for the node is coming from the current Step of that node). Nodes can be grouped into exclusivity sets *and* as of D2, exclusivity groups (which are collections of exclusivity sets that affect each other). See DestinyTalentGridDefinition for more information. Brace yourself, the water's cold out there in the deep end.
/// </summary>
[DataContract]
public partial class DestinyEntitiesItemsDestinyItemTalentGridComponent : IEquatable<DestinyEntitiesItemsDestinyItemTalentGridComponent>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyEntitiesItemsDestinyItemTalentGridComponent" /> class.
/// </summary>
/// <param name="TalentGridHash">Most items don't have useful talent grids anymore, but Builds in particular still do. You can use this hash to lookup the DestinyTalentGridDefinition attached to this item, which will be crucial for understanding the node values on the item..</param>
/// <param name="Nodes">Detailed information about the individual nodes in the talent grid. A node represents a single visual \"pip\" in the talent grid or Build detail view, though each node may have multiple \"steps\" which indicate the actual bonuses and visual representation of that node..</param>
/// <param name="IsGridComplete">Indicates whether the talent grid on this item is completed, and thus whether it should have a gold border around it. Only will be true if the item actually *has* a talent grid, and only then if it is completed (i.e. every exclusive set has an activated node, and every non-exclusive set node has been activated).</param>
/// <param name="GridProgression">If the item has a progression, it will be detailed here. A progression means that the item can gain experience. Thresholds of experience are what determines whether and when a talent node can be activated..</param>
public DestinyEntitiesItemsDestinyItemTalentGridComponent(uint? TalentGridHash = default(uint?), List<DestinyDestinyTalentNode> Nodes = default(List<DestinyDestinyTalentNode>), bool? IsGridComplete = default(bool?), DestinyDestinyProgression GridProgression = default(DestinyDestinyProgression))
{
this.TalentGridHash = TalentGridHash;
this.Nodes = Nodes;
this.IsGridComplete = IsGridComplete;
this.GridProgression = GridProgression;
}
/// <summary>
/// Most items don't have useful talent grids anymore, but Builds in particular still do. You can use this hash to lookup the DestinyTalentGridDefinition attached to this item, which will be crucial for understanding the node values on the item.
/// </summary>
/// <value>Most items don't have useful talent grids anymore, but Builds in particular still do. You can use this hash to lookup the DestinyTalentGridDefinition attached to this item, which will be crucial for understanding the node values on the item.</value>
[DataMember(Name="talentGridHash", EmitDefaultValue=false)]
public uint? TalentGridHash { get; set; }
/// <summary>
/// Detailed information about the individual nodes in the talent grid. A node represents a single visual \"pip\" in the talent grid or Build detail view, though each node may have multiple \"steps\" which indicate the actual bonuses and visual representation of that node.
/// </summary>
/// <value>Detailed information about the individual nodes in the talent grid. A node represents a single visual \"pip\" in the talent grid or Build detail view, though each node may have multiple \"steps\" which indicate the actual bonuses and visual representation of that node.</value>
[DataMember(Name="nodes", EmitDefaultValue=false)]
public List<DestinyDestinyTalentNode> Nodes { get; set; }
/// <summary>
/// Indicates whether the talent grid on this item is completed, and thus whether it should have a gold border around it. Only will be true if the item actually *has* a talent grid, and only then if it is completed (i.e. every exclusive set has an activated node, and every non-exclusive set node has been activated)
/// </summary>
/// <value>Indicates whether the talent grid on this item is completed, and thus whether it should have a gold border around it. Only will be true if the item actually *has* a talent grid, and only then if it is completed (i.e. every exclusive set has an activated node, and every non-exclusive set node has been activated)</value>
[DataMember(Name="isGridComplete", EmitDefaultValue=false)]
public bool? IsGridComplete { get; set; }
/// <summary>
/// If the item has a progression, it will be detailed here. A progression means that the item can gain experience. Thresholds of experience are what determines whether and when a talent node can be activated.
/// </summary>
/// <value>If the item has a progression, it will be detailed here. A progression means that the item can gain experience. Thresholds of experience are what determines whether and when a talent node can be activated.</value>
[DataMember(Name="gridProgression", EmitDefaultValue=false)]
public DestinyDestinyProgression GridProgression { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyEntitiesItemsDestinyItemTalentGridComponent {\n");
sb.Append(" TalentGridHash: ").Append(TalentGridHash).Append("\n");
sb.Append(" Nodes: ").Append(Nodes).Append("\n");
sb.Append(" IsGridComplete: ").Append(IsGridComplete).Append("\n");
sb.Append(" GridProgression: ").Append(GridProgression).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyEntitiesItemsDestinyItemTalentGridComponent);
}
/// <summary>
/// Returns true if DestinyEntitiesItemsDestinyItemTalentGridComponent instances are equal
/// </summary>
/// <param name="input">Instance of DestinyEntitiesItemsDestinyItemTalentGridComponent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyEntitiesItemsDestinyItemTalentGridComponent input)
{
if (input == null)
return false;
return
(
this.TalentGridHash == input.TalentGridHash ||
(this.TalentGridHash != null &&
this.TalentGridHash.Equals(input.TalentGridHash))
) &&
(
this.Nodes == input.Nodes ||
this.Nodes != null &&
this.Nodes.SequenceEqual(input.Nodes)
) &&
(
this.IsGridComplete == input.IsGridComplete ||
(this.IsGridComplete != null &&
this.IsGridComplete.Equals(input.IsGridComplete))
) &&
(
this.GridProgression == input.GridProgression ||
(this.GridProgression != null &&
this.GridProgression.Equals(input.GridProgression))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.TalentGridHash != null)
hashCode = hashCode * 59 + this.TalentGridHash.GetHashCode();
if (this.Nodes != null)
hashCode = hashCode * 59 + this.Nodes.GetHashCode();
if (this.IsGridComplete != null)
hashCode = hashCode * 59 + this.IsGridComplete.GetHashCode();
if (this.GridProgression != null)
hashCode = hashCode * 59 + this.GridProgression.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameControl : MonoBehaviour
{
public int _score = 0;
[SerializeField] public Text _scoreText;
public void addScore(int score)
{
_score += score;
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
namespace BomTreeView.Database
{
public class BomDbEntries
{
public List<BomDbEntry> BomDbEntryList{ get; set; }
public BomDbEntries(List<BomDbEntry> bomDbEntryList)
{
BomDbEntryList = bomDbEntryList;
}
public BomDisplayEntries ToBomDisplayEntryList()
{
BomDbEntry topmostEntry = GetTopmostEntry();
BomDisplayEntry topmostDisplayEntry = BuildBomDisplayEntry(topmostEntry);
return new BomDisplayEntries(topmostDisplayEntry);
}
private BomDbEntry GetTopmostEntry()
{
foreach(BomDbEntry bomDbEntry in BomDbEntryList)
{
if (!bomDbEntry.HasParent())
{
return bomDbEntry;
}
}
throw new Exception("No entry in the BomDbEntryList could be identified as the topmost entry");
}
private BomDisplayEntry BuildBomDisplayEntry(BomDbEntry bomDbEntry)
{
List<BomDisplayEntry> children = BuildChildBomDisplayEntriesOf(bomDbEntry);
return new BomDisplayEntry(
bomDbEntry.ComponentName,
bomDbEntry.ParentName,
bomDbEntry.Quantity,
bomDbEntry.Type,
bomDbEntry.Item,
bomDbEntry.PartNumber,
bomDbEntry.Title,
bomDbEntry.Material,
children
);
}
private List<BomDisplayEntry> BuildChildBomDisplayEntriesOf(BomDbEntry bomDbEntry)
{
List<BomDisplayEntry> childBomDisplayEntries = new List<BomDisplayEntry>();
List<BomDbEntry> childBomDbEntries = GetChildBomDbEntriesOf(bomDbEntry);
foreach(BomDbEntry childBomDbEntry in childBomDbEntries)
{
BomDisplayEntry childBomDisplayEntry = BuildBomDisplayEntry(childBomDbEntry);
childBomDisplayEntries.Add(childBomDisplayEntry);
}
return childBomDisplayEntries;
}
private List<BomDbEntry> GetChildBomDbEntriesOf(BomDbEntry bomDbEntry)
{
List<BomDbEntry> childBomDbEntries = new List<BomDbEntry>();
foreach (BomDbEntry potentialChildBomDbEntry in BomDbEntryList)
{
if (potentialChildBomDbEntry.IsChildOf(bomDbEntry))
{
childBomDbEntries.Add(potentialChildBomDbEntry);
}
}
return childBomDbEntries;
}
public DataTable ToDataTable()
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add("COMPONENT_NAME", typeof(string));
dataTable.Columns.Add("PART_NUMBER", typeof(string));
dataTable.Columns.Add("TITLE", typeof(string));
dataTable.Columns.Add("QUANTITY", typeof(int));
dataTable.Columns.Add("TYPE", typeof(string));
dataTable.Columns.Add("ITEM ", typeof(string));
dataTable.Columns.Add("MATERIAL", typeof(string));
foreach (BomDbEntry bomDisplayEntry in BomDbEntryList)
{
dataTable.Rows.Add(
bomDisplayEntry.ComponentName,
bomDisplayEntry.PartNumber,
bomDisplayEntry.Title,
bomDisplayEntry.Quantity,
bomDisplayEntry.Type,
bomDisplayEntry.Item,
bomDisplayEntry.Material
);
}
return dataTable;
}
}
}
|
using System.Drawing;
using Top_Down_shooter.Scripts.Source;
namespace Top_Down_shooter.Scripts.GameObjects
{
class Gun : GameObject
{
public int Cooldown { get; set; }
public int CountBullets { get; set; }
public float Angle { get; set; }
public readonly Point SpawnBullets = new Point(10, -10);
public Gun(int x, int y)
{
Cooldown = GameSettings.PlayerCooldown;
CountBullets = GameSettings.StartCountBullets;
X = x;
Y = y;
}
public void Move(int x, int y)
{
X = x;
Y = y;
}
}
}
|
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 UberFrba.Abm_Chofer;
namespace UberFrba.Registro_Viajes
{
public partial class GrillaChofer_Viaje : Form
{
public AltaViaje formularioAlta;
public GrillaChofer_Viaje(AltaViaje formulario)
{
InitializeComponent();
this.formularioAlta = formulario;
}
private Boolean validarFiltros(String nombre, String apellido, String dni)
{
//Valido DNI sea numerico
Decimal dniDecimal;
if (dni != "" && !Decimal.TryParse(dni, out dniDecimal))
{
errorDni.Text = "El DNI debe ser numérico";
return false;
}
return true;
}
private void btnBuscar_Click(object sender, EventArgs e)
{
try
{
if (!validarFiltros(txtNombre.Text, txtApellido.Text, txtDni.Text))
{
MessageBox.Show("Error en los filtros de búsqueda", "Error", MessageBoxButtons.OK);
}
else
{
//Limpio la tabla de choferes
grillaChofer.Columns.Clear();
//Busco los choferes en la base de datos (solo activos)
DataTable dtChofer = Chofer.buscarChoferes(txtNombre.Text, txtApellido.Text, (txtDni.Text == "") ? 0 : Decimal.Parse(txtDni.Text));
//Le asigno a la grilla los choferes
grillaChofer.DataSource = dtChofer;
//Agrego botones para Seleccionar chofer
DataGridViewButtonColumn btnSeleccionar = new DataGridViewButtonColumn();
btnSeleccionar.HeaderText = "Seleccionar";
btnSeleccionar.Text = "Seleccionar";
btnSeleccionar.UseColumnTextForButtonValue = true;
grillaChofer.Columns.Add(btnSeleccionar);
grillaChofer.Columns["Chofer_Persona"].Visible = false;
errorDni.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show("Error inesperado: " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
private void btnLimpiar_Click(object sender, EventArgs e)
{
grillaChofer.DataSource = null;
grillaChofer.Columns.Clear();
limpiarFiltrosYErrores();
}
private void limpiarFiltrosYErrores()
{
txtNombre.Text = "";
txtApellido.Text = "";
txtDni.Text = "";
errorDni.Text = "";
}
private void grillaChofer_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
//En caso de que se presiono el boton "Seleccionar" de algun chofer, se crea un objeto Chofer y se lo envia al formulario de llamada
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && senderGrid.CurrentCell.Value.ToString() == "Seleccionar" && e.RowIndex >= 0)
{
try
{
if ((Byte)senderGrid.CurrentRow.Cells["Chofer_Activo"].Value == 1)
{
Chofer choferElegido = new Chofer();
choferElegido.Nombre = senderGrid.CurrentRow.Cells["Chofer_Nombre"].Value.ToString();
choferElegido.Apellido = senderGrid.CurrentRow.Cells["Chofer_Apellido"].Value.ToString();
choferElegido.Dni = (Decimal)senderGrid.CurrentRow.Cells["Chofer_Dni"].Value;
choferElegido.Telefono = (Decimal)senderGrid.CurrentRow.Cells["Chofer_Telefono"].Value;
choferElegido.Direccion = senderGrid.CurrentRow.Cells["Chofer_Direccion"].Value.ToString();
choferElegido.FechaNacimiento = (DateTime)(senderGrid.CurrentRow.Cells["Chofer_Fecha_Nac"].Value);
choferElegido.Mail = senderGrid.CurrentRow.Cells["Chofer_Mail"].Value.ToString();
choferElegido.Activo = (Byte)senderGrid.CurrentRow.Cells["Chofer_Activo"].Value;
this.formularioAlta.choferElegido = choferElegido;
this.formularioAlta.cambiarChofer();
this.Hide();
}
else
{
MessageBox.Show("No puede seleccionar este chofer ya que no se encuentra activo", "Error", MessageBoxButtons.OK);
}
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error al realizar la seleccion del chofer: " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildingPlacer : Placer
{
public float targetPlaceDist = 1.25f;
public float atDrillMaxAngle = 45;
public LayerMask targetUnitMask;
private Ground ground;
public void Init(Player owner, Ground ground, Building buildingPrefab)
{
this.ground = ground;
aimUp = false;
SetGoldCost(buildingPrefab.Cost);
base.Init(owner);
}
protected override void UpdateTarget()
{
if (!Released)
{
Unit unit = GetNearestUnit(MousePos, 1000, targetUnitMask, true);
if (unit)
{
float unitDist = Vector2.Distance(unit.transform.position, MousePos);
float groundDist = Mathf.Abs(ground.GetHeightAt(MousePos.x, owner.IsTop) - MousePos.y);
Target.unit = unitDist < groundDist ? unit : null;
}
else
{
Target.unit = null;
}
}
if (Target.unit)
{
SetAroundTargetUnit(targetPlaceDist, atDrillMaxAngle, -owner.Up);
}
else
{
ground.SetOnSurface(out Target.pos, out Target.up, MousePos.x, owner.IsTop);
}
Target.valid = true;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShowStore : MonoBehaviour
{
[SerializeField] private GameObject its1;
[SerializeField] private GameObject its2;
[SerializeField] private GameObject its3;
//private int type;
// Use this for initialization
void Start()
{
LoadStoreItem(0, its1);
LoadStoreItem(1, its2);
LoadStoreItem(2, its3);
}
// Update is called once per frame
void Update()
{
}
//加载商店物体
public void LoadStoreItem(int t, GameObject items)
{
GameObject gameObj;
switch (t)
{
case 0:
for (int j = ItemsRefresh.Instance.itemList[0].Count - 1; j >= 0; j--)
{
if (null != ItemsRefresh.Instance.itemList[0][j])
{
gameObj = (GameObject)Instantiate(Resources.Load("Prefabs/equip/" + ItemsRefresh.Instance.itemList[0][j].name));
gameObj.name = ItemsRefresh.Instance.itemList[0][j].name;
gameObj.transform.position = items.transform.GetChild(j).position;
gameObj.transform.SetParent(items.transform.GetChild(j));
items.transform.GetChild(j).GetChild(1).GetComponent<Text>().text = "$"+ItemsRefresh.Instance.itemList[0][j].worth.ToString();
Debug.Log(gameObj.name);
}
}
break;
case 1:
for (int j = ItemsRefresh.Instance.itemList[1].Count - 1; j >= 0; j--)
{
if (null != ItemsRefresh.Instance.itemList[1][j])
{
gameObj = (GameObject)Instantiate(Resources.Load("Prefabs/equip/" + ItemsRefresh.Instance.itemList[1][j].name));
gameObj.name = ItemsRefresh.Instance.itemList[1][j].name;
gameObj.transform.position = items.transform.GetChild(j).position;
gameObj.transform.SetParent(items.transform.GetChild(j));
items.transform.GetChild(j).GetChild(1).GetComponent<Text>().text = "$" + ItemsRefresh.Instance.itemList[1][j].worth.ToString();
Debug.Log(gameObj.name);
}
}
break;
case 2:
for (int j = ItemsRefresh.Instance.itemList[2].Count - 1; j >= 0; j--)
{
if (null != ItemsRefresh.Instance.itemList[2][j])
{
gameObj = (GameObject)Instantiate(Resources.Load("Prefabs/equip/" + ItemsRefresh.Instance.itemList[2][j].name));
gameObj.name = ItemsRefresh.Instance.itemList[2][j].name;
gameObj.transform.position = items.transform.GetChild(j).position;
gameObj.transform.SetParent(items.transform.GetChild(j));
items.transform.GetChild(j).GetChild(1).GetComponent<Text>().text = "$" + ItemsRefresh.Instance.itemList[2][j].worth.ToString();
Debug.Log(gameObj.name);
}
}
break;
default:
break;
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace TheMinepack.Projectiles
{
public class StarScytheProjectile : ModProjectile
{
public override void SetDefaults()
{
projectile.CloneDefaults(ProjectileID.IceSickle);
projectile.name = "Starry Scythe";
projectile.width = 32;
projectile.scale = 1.15f;
projectile.height = 32;
projectile.aiStyle = 18;
aiType = 274;
}
public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
Projectile.NewProjectile(target.position.X + (float)target.velocity.X, target.position.Y - 500, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
Projectile.NewProjectile(target.position.X - 20 + (float)target.velocity.X, target.position.Y - 470, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
Projectile.NewProjectile(target.position.X + 40 + (float)target.velocity.X, target.position.Y - 580, 0, 20, ProjectileID.Starfury, 30, 0f, Main.myPlayer, 0f, 1f);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[System.Serializable]
public class MouseController
{
//MOUSE EVENT
public Transform controller;
//public Texture textureRect; //textura de nuestro marco
private Vector2 firstPoint; //primer punto del marco
private Vector2 secondPoint; //segundo punto del marco
private Rect rect; //el marco en si
private Rect backRect; //fix del marco (por los valores negativos que toma)
private float time;
private List<GameObject> objectsRect; //lista de los objetos del marco
public string tagPlayer; //para seleccion solamente de nuestras unidades
public string layerBuild; //categoria de construcciones
public string layerUnit; //categoria de unidades
public string layerWorld; //categoria ajena
public Camera camera;
private Vector3 clickRigth; //click derecho, movimiento de player
public List<GameObject> unitSelected = new List<GameObject>(); //lista que contendra los objetos seleccionados
private KeysController key;
public Transform CursorUI; //gui de seguimiento
public RectTransform selectionBox;
public bool inGUI; //para detectar si se esta o no dentro de la interfaz
private Vector2 initialClickPosition = Vector2.zero;
//Optimizacion de codigo
private string layerController;
private Ray rayInfo;
private RaycastHit hitInfo;
private Ray ray;
private RaycastHit hit;
GameObject go;
GameObject attack;
float _invertedY;
void Start()
{
key = controller.GetComponent<GameController>().keysController; //obtenesmos las teclas configuradas
}
public void Update()
{
controller.GetComponent<GameController>().interfaceController.UpdateInterface(unitSelected);
if (!inGUI) //cuando esta en la interfaz omite las opciones de raycast, etc
{
ClickEvents();
rect = new Rect(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
}
}
void ClickEvents()
{
//Cuando se selecciona alguna unidad o varias, se comprueba el tipo y se mandas las acciones a la interfaz, mediante la clase "interfaceController";
if(Input.GetMouseButtonDown(0)) //detectamos click izquierdo, bool al detectar la tecla de seleccion multiple
{
_invertedY = Screen.height - Input.mousePosition.y;
firstPoint = new Vector2(Input.mousePosition.x, _invertedY); //invertimos el valor de y, para seleccion de arrrastre
initialClickPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
selectionBox.anchoredPosition = initialClickPosition;
ray = camera.ScreenPointToRay(Input.mousePosition); //creamos un rayo (el cual obtendra los objetos "clickeados"
if (Physics.Raycast(ray, out hit)) //si nuestro rayo detecta alguna colision
{
//if(Input.GetKey(key.multSelect)) //Multiple seleccion, con Tab(tecla especial) no funciona
if(Input.GetKey(KeyCode.Tab))
{
if(hit.collider.gameObject.layer == LayerMask.NameToLayer(layerUnit)) //si detecta que la colision es de una unidad
{
if(hit.collider.tag == tagPlayer) //y ademas que es de la familia "Player" o sea nuestra, continua con el codigo
//se puede agregar arriba junto con layerUnit (por comodidad y comprension se genera asi
{
bool repeat = false; //para no repetir la seleccion de unidades (lo cual no agrega el mismo objeto al...
//array(lista de unidades seleccionadas
if(unitSelected == null) //si no hay nada en nuestro array, agregamos nuestro objecto
{
unitSelected.Add(hit.collider.gameObject);
hit.collider.gameObject.transform.GetChild(0).GetComponent<Projector>().enabled = true;
}
else //al contrario asigna un espacio a cada una de las unidades en nuestro array de unidades
{
for(int i = 0; unitSelected.Count > i; i++) if(unitSelected[i] == hit.collider.gameObject) repeat = true; //al igual que el anterior preevemos que se repitan las selecciones
if(repeat == false) //si no esta en nuestro array, se agrega a la lista
{
unitSelected.Add(hit.collider.gameObject);
hit.collider.gameObject.transform.GetChild(0).GetComponent<Projector>().enabled = true;
}
if(repeat == true) //caso contrario se deselecciona y se elimina de nuestro array
{
unitSelected.Remove(hit.collider.gameObject); //eliminacion
hit.collider.gameObject.transform.GetChild(0).GetComponent<Projector>().enabled = false;
}
}
}
}
}
else //unica seleccion
{
if(hit.collider.gameObject.layer == LayerMask.NameToLayer(layerUnit)) //si es una unidad continua
{
if(hit.collider.tag == tagPlayer) //si es nuestra continua
{
Clear(); //vease mas abajo
unitSelected.Clear (); //limpiamos nuestro array de unidades
unitSelected.Add(hit.collider.gameObject); //agregamos esta unidad al array
hit.collider.transform.GetChild(0).GetComponent<Projector>().enabled = true;
//La interfaz se da por el contador de InterdaceController
}
else //para seleccionar unidades (enemigas/aliadas) y mostrar informacion de las mismas
{
Clear();
unitSelected.Clear (); //limpiamos nuestro array de unidades
}
}
else //no unidades
{
if(hit.collider.gameObject.layer != LayerMask.NameToLayer("UI"))
{
if(hit.collider.gameObject.layer == LayerMask.NameToLayer(layerWorld)) //si clickeamos un lugar vacio, o del mundo (no unidad, no contruccion)
{
Clear(); //vease mas abajo
}
if(hit.collider.gameObject.layer == LayerMask.NameToLayer(layerBuild)) //si es una contruccion continua
{
if(hit.collider.tag == tagPlayer) //si es nuetra continua
{
Clear();
unitSelected.Clear ();
//INTERFACECONTROLLER
controller.GetComponent<GameController>().interfaceController.ViewBuildSelected(hit.transform);
}
else //para obtener informacion de contrucciones aliadas/enemigas/del mundo
{
}
}
}
}
}
}
//Debug.Log("ClickRigthTag: " + hit.collider.tag);
}
if (Input.GetMouseButton(0))
{
Vector2 currentMousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 difference = currentMousePosition - initialClickPosition;
Vector2 startPoint = initialClickPosition;
if (difference.x < 0)
{
startPoint.x = currentMousePosition.x;
difference.x = -difference.x;
}
if (difference.y < 0)
{
startPoint.y = currentMousePosition.y;
difference.y = -difference.y;
}
selectionBox.anchoredPosition = startPoint;
selectionBox.sizeDelta = difference;
}
if(Input.GetMouseButtonDown(1)) //click derecho //acciones de las unidades
{
ray = camera.ScreenPointToRay(Input.mousePosition); //..//
if (Physics.Raycast(ray, out hit)) //..//
{
if(hit.collider.gameObject.layer == LayerMask.NameToLayer(layerWorld)) //si clickeamos en un lugar vacio continuamos a mover la unidad
{
if(unitSelected != null)
{
for(int i = 0; unitSelected.Count > i; i++)
{
CursorUI.position = new Vector3(hit.point.x, hit.point.y + 1, hit.point.z); //movemos al luegar del hitpoint
ResetCursorUI();
go = unitSelected[i] as GameObject;
go.transform.GetComponent<MovementController>().SetDestination(hit.point);
if(go.transform.GetComponent<UnitIA>().estate == UnitIA.Estate.building) //si la unidad esta construyendo detenemos la accion de construir
{
go.transform.GetComponent<Constructor>().targetBuild.GetComponent<BuildConfiguration>().constructor = null; //reseteamos en la construccion
go.transform.GetComponent<Constructor>().targetBuild = null; //reseteamos en el constructor
}
go.transform.GetComponent<UnitIA>().estate = UnitIA.Estate.moving;
}
}
}
else //otras funciones//opciones de la unidad misma
{
if(hit.collider.tag != tagPlayer) //si no es una unidad nuestra
{
if(unitSelected != null)
{
for(int i = 0; unitSelected.Count > i; i++)
{
attack = unitSelected[i] as GameObject;
attack.transform.GetComponent<UnitIA>().targetGameObject = hit.collider.gameObject;
attack.transform.GetComponent<UnitIA>().estateTarget = UnitIA.EstateTarget.aT_Selected;
}
}
}
}
if((hit.collider.gameObject.layer == LayerMask.NameToLayer(layerUnit)) || (hit.collider.gameObject.layer == LayerMask.NameToLayer(layerBuild))) //accion de ataque
{ //si es una unidad o una contruccion
if(hit.collider.tag == tagPlayer) //si es diferente a una unidad/contruccion nuestra
{
for(int i = 0; unitSelected.Count > i; i++)
{
Transform go = unitSelected[i].transform;
if (go.GetComponent<Constructor>())
{
go.GetComponent<Constructor>().actionBulding(hit.transform); //iniciamos la contruccion
}
else
{
//no hacemos nada, creo..
}
}
}
}
}
rect = new Rect(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y); //!!!
}
if(Input.GetMouseButtonUp(0)) //limpiados el anterior recuadro/GUI RECT
{
//reseteamos el marco
rect.width = 0;
rect.height = 0;
backRect.width = 0;
backRect.height = 0;
secondPoint = Vector2.zero;
time = 0;
initialClickPosition = Vector2.zero;
selectionBox.anchoredPosition = Vector2.zero;
selectionBox.sizeDelta = Vector2.zero;
}
if(Input.GetMouseButton(0)) //seleccion por drag/recuadro
{
time = time + Time.deltaTime;
if(time > 0.15f) //test
{
objectsRect = new List<GameObject>(GameObject.FindGameObjectsWithTag(tagPlayer)); //test //agregamos a una lista todos los objetos que se puedan seleccionar
_invertedY = Screen.height - Input.mousePosition.y; //invertimos la posicion y
secondPoint = new Vector2(Input.mousePosition.x - firstPoint.x, (firstPoint.y - _invertedY) * -1);
//Rect negativo, fix para los valores negativos
if (rect.width < 0)
{
backRect = new Rect(rect.x - Mathf.Abs(rect.width), rect.y, Mathf.Abs(rect.width), rect.height);
}
else if (rect.height < 0)
{
backRect = new Rect(rect.x, rect.y - Mathf.Abs(rect.height), rect.width, Mathf.Abs(rect.height));
}
if (rect.width < 0 && rect.height < 0)
{
backRect = new Rect(rect.x - Mathf.Abs(rect.width), rect.y - Mathf.Abs(rect.height), Mathf.Abs(rect.width), Mathf.Abs(rect.height));
}
//Posicion del marco, dependiendo la ubicacion donde se hace el recuadro
foreach (GameObject unit in objectsRect) //hacemos una busqueda por _objectsDrag
{
Vector3 _screenPos = camera.WorldToScreenPoint(unit.transform.position); //
Vector2 _screenPoint = new Vector2(_screenPos.x, Screen.height - _screenPos.y);
if (!rect.Contains(_screenPoint) || !backRect.Contains(_screenPoint)) //fuera de los limites del marco
{
if ((unit.gameObject.layer == LayerMask.NameToLayer(layerUnit)) && (unit.gameObject.tag == tagPlayer)) //si es una unidad
{
unitSelected.Remove(unit.gameObject); //se deselecciona
unit.transform.GetChild(0).GetComponent<Projector>().enabled = false;
}
}
if (rect.Contains(_screenPoint) || backRect.Contains(_screenPoint)) //si se encuentra dentro de los limites del marco
{
if ((unit.gameObject.layer == LayerMask.NameToLayer(layerUnit)) && (unit.gameObject.tag == tagPlayer))
{
unitSelected.Add(unit.gameObject); //se agrega a la lista (array)
unit.transform.GetChild(0).GetComponent<Projector>().enabled = true;
}
}
}
}
}
}
void ResetCursorUI()
{
CursorUI.GetComponent<CursorUI>().enabled = false; //lo desactivamos, por si esta en animacion
CursorUI.GetComponent<Projector>().enabled = false;
CursorUI.GetComponent<CursorUI>().enabled = true; //lo activamos para que vuelva a reproducir la animacion
CursorUI.GetComponent<Projector>().enabled = true;
}
private void Clear()
{
controller.GetComponent<GameController> ().interfaceController.ClearView ();
GameObject clearObject; //objecto ayuda
for(int i = 0; unitSelected.Count > i; i++) //vamos por cada objecto del array(lista de unidades)
{
clearObject = unitSelected[i] as GameObject; //del array lo agremos al objeto ayuda
clearObject.transform.GetChild(0).GetComponent<Projector>().enabled = false;
}
unitSelected.Clear (); //limpiamos la lista
}
//public void internalOnGUI() //mostamos el marco/rectangulo de seleccion
//{
// //RECT
// //rect = new Rect(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
//}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameUIManager : Singleton<GameUIManager>
{
[SerializeField]
private PlayerSettings settings;
[SerializeField]
private Image cursor;
[SerializeField]
private Slider treeLifeSlider;
[SerializeField]
private Image treeLifeFillColor;
[SerializeField]
private Color colorLife;
[SerializeField]
private Color colorDeath;
[SerializeField]
private Image flowerWarningImg;
[SerializeField]
private Image flyWarningImg;
private void Update()
{
cursor.color = new Color(cursor.color.r, cursor.color.g, cursor.color.b, settings.cursorOpacity);
if(treeLifeSlider.value <= 0.25f)
{
flowerWarningImg.color = new Color(flowerWarningImg.color.r, flowerWarningImg.color.g, flowerWarningImg.color.b, Mathf.PingPong(Time.time, 1f));
flyWarningImg.color = new Color(flyWarningImg.color.r, flyWarningImg.color.g, flyWarningImg.color.b, Mathf.PingPong(Time.time, 1f));
}
else
{
if(flowerWarningImg.color.a<=0)
{
return;
}
flowerWarningImg.color = new Color(flowerWarningImg.color.r, flowerWarningImg.color.g, flowerWarningImg.color.b, 0f);
flyWarningImg.color = new Color(flyWarningImg.color.r, flyWarningImg.color.g, flyWarningImg.color.b, 0f);
}
}
public void UpdateTreeLifeUI(float newSliderValue)
{
treeLifeSlider.value = newSliderValue;
treeLifeFillColor.color = Color.Lerp(colorDeath, colorLife, newSliderValue);
}
}
|
using ProConstructionsManagment.Desktop.Commands;
using ProConstructionsManagment.Desktop.Enums;
using ProConstructionsManagment.Desktop.Managers;
using ProConstructionsManagment.Desktop.Messages;
using ProConstructionsManagment.Desktop.Services;
using ProConstructionsManagment.Desktop.Views.Base;
using Serilog;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace ProConstructionsManagment.Desktop.Views.Employee
{
public class EmployeeNavigationViewModel : ViewModelBase
{
private readonly IEmployeesService _employeesService;
private readonly IMessengerService _messengerService;
private readonly IShellManager _shellManager;
private string _employeeId;
public EmployeeNavigationViewModel(IEmployeesService employeesService, IMessengerService messengerService, IShellManager shellManager)
{
_employeesService = employeesService;
_messengerService = messengerService;
_shellManager = shellManager;
messengerService.Register<EmployeeIdMessage>(this, msg => EmployeeId = msg.EmployeeId);
}
public string EmployeeId
{
get => _employeeId;
set => Set(ref _employeeId, value);
}
public ICommand NavigateToEmployeesViewCommand => new AsyncRelayCommand(NavigateToEmployeesView);
private async Task NavigateToEmployeesView()
{
_messengerService.Send(new ChangeViewMessage(ViewTypes.Employees));
_messengerService.Send(new ChangeViewMessage(ViewTypes.EmployeesNavigation));
}
public ICommand HireEmployeeCommand => new AsyncRelayCommand(HireEmployee);
private async Task HireEmployee()
{
try
{
MessageBoxResult messageBoxResult = MessageBox.Show("Czy jesteś pewien że chcesz zatrudnić tego pracownika?", "", MessageBoxButton.YesNo);
switch (messageBoxResult)
{
case MessageBoxResult.Yes:
_shellManager.SetLoadingData(true);
var employee = await _employeesService.GetEmployeeById(EmployeeId);
var data = new Models.Employee
{
Id = EmployeeId,
Name = employee.Name,
SecondName = employee.SecondName,
LastName = employee.LastName,
DateOfBirth = employee.DateOfBirth,
Nationality = employee.Nationality,
IsForeman = employee.IsForeman,
ReadDrawings = employee.ReadDrawings,
Status = 1
};
var result = _employeesService.UpdateEmployee(data, EmployeeId);
if (result.IsSuccessful)
{
Log.Information($"Successfully changed employee status to hired ({data.Id})");
MessageBox.Show("Pomyślnie zatrudniono pracownika");
}
break;
case MessageBoxResult.No:
return;
}
}
catch (Exception e)
{
Log.Error(e, "Failed updating employee");
MessageBox.Show(
"Coś poszło nie tak podczas zapisywania zmian, proszę spróbować jeszcze raz. Jeśli problem nadal występuje, skontakuj się z administratorem oprogramowania");
}
finally
{
_shellManager.SetLoadingData(false);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SalesApplication
{
class DataEntry
{
public DataEntry()
{
Console.WriteLine("Enter product name:");
string product_Name = Console.ReadLine();
bool retry = true;
int quantity = 0;
while (retry)
{
Console.WriteLine("Enter quantity sold:");
if (int.TryParse(Console.ReadLine(), out quantity))
{
retry = false;
}
else
{
Console.WriteLine("That was not a valid quantity. Press any key to try again");
Console.ReadKey();
}
}
retry = true;
decimal price = 0;
while (retry)
{
Console.WriteLine("Enter price:");
if (decimal.TryParse(Console.ReadLine(), out price))
{
price = Math.Round(price, 2);
retry = false;
}
else
{
Console.WriteLine("That was not a valid price. Press any key to try again");
Console.ReadKey();
}
}
retry = true;
DateTime sales_Date = DateTime.Now;
string formatted_sales_Date = "";
while (retry)
{
Console.WriteLine("Enter sale date in any valid date format or leave blank for todays date:");
string dateInput = Console.ReadLine();
if (dateInput != "")
{
if (DateTime.TryParse(dateInput, out sales_Date))
{
formatted_sales_Date = sales_Date.ToString("yyyy/MM/dd");
retry = false;
}
else
{
Console.WriteLine("That was not a valid date. Press any key to try again");
Console.ReadKey();
}
}
else
{
formatted_sales_Date = sales_Date.ToString("yyyy/MM/dd");
retry = false;
}
}
Console.Clear();
Console.WriteLine("---------- Sale Record Details ----------");
Console.WriteLine("Product Name: " + product_Name);
Console.WriteLine("Quantity: " + quantity);
Console.WriteLine("Price: " + price.ToString("C2"));
Console.WriteLine("Date of Sale: " + formatted_sales_Date + "\n");
Console.WriteLine("Press Enter to save this record to the database, or any key to quit without making changes");
//var menuOption = Console.ReadKey();
if(Console.ReadKey().Key == ConsoleKey.Enter)
{
MySQLService db = new MySQLService();
db.InsertSalesData(product_Name, quantity, price, formatted_sales_Date);
}
else
{
Console.WriteLine("ABORT!");
}
//
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Cosmos DB specific extension methods for LINQ queries.
/// </summary>
public static class CosmosQueryableExtensions
{
internal static readonly MethodInfo WithPartitionKeyMethodInfo
= typeof(CosmosQueryableExtensions).GetRequiredDeclaredMethod(nameof(WithPartitionKey));
/// <summary>
/// Specify the partition key for partition used for the query. Required when using
/// a resource token that provides permission based on a partition key for authentication,
/// </summary>
/// <typeparam name="TEntity"> The type of entity being queried. </typeparam>
/// <param name="source"> The source query. </param>
/// <param name="partitionKey"> The partition key. </param>
/// <returns> A new query with the set partition key. </returns>
public static IQueryable<TEntity> WithPartitionKey<TEntity>(
this IQueryable<TEntity> source,
[NotParameterized] string partitionKey)
where TEntity : class
{
Check.NotNull(source, nameof(source));
Check.NotNull(partitionKey, nameof(partitionKey));
return
source.Provider is EntityQueryProvider
? source.Provider.CreateQuery<TEntity>(
Expression.Call(
instance: null,
method: WithPartitionKeyMethodInfo.MakeGenericMethod(typeof(TEntity)),
source.Expression,
Expression.Constant(partitionKey)))
: source;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YoctoScheduler.Core.Database.tsql
{
public class Extractor
{
public const string PREFIX = "YoctoScheduler.Core.Database.tsql.";
public const string SUFFIX = ".sql";
private Extractor() { }
public static string Get(string name)
{
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(PREFIX + name + SUFFIX))
{
if(stream == null)
throw new Exceptions.TSQLNotFoundException(name);
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{
return sr.ReadToEnd();
}
}
}
}
}
|
/*
DotNetMQ - A Complete Message Broker For .NET
Copyright (C) 2011 Halil ibrahim KALKAN
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using MDS.Communication.Events;
using MDS.Exceptions;
using MDS.Organization.Routing;
using MDS.Settings;
using MDS.Storage;
using MDS.Threading;
using MDS.Communication;
using MDS.Communication.Messages;
namespace MDS.Organization
{
/// <summary>
/// This class represents organization layer of MDS Server. It handles, stores, routes and delivers messages.
/// </summary>
public class OrganizationLayer : IRunnable
{
#region Private fields
/// <summary>
/// Reference to logger.
/// </summary>
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Reference to settings.
/// </summary>
private readonly MDSSettings _settings;
/// <summary>
/// Reference to communication layer.
/// </summary>
private readonly CommunicationLayer _communicationLayer;
/// <summary>
/// Reference to storage manager.
/// </summary>
private readonly IStorageManager _storageManager;
/// <summary>
/// Routing table.
/// </summary>
private readonly RoutingTable _routingTable;
/// <summary>
/// Reference to server graph.
/// </summary>
private readonly MDSServerGraph _serverGraph;
/// <summary>
/// Reference to application list.
/// </summary>
private readonly MDSClientApplicationList _clientApplicationList;
/// <summary>
/// Reference to all MDS Manager. It contains communicators to all instances of MDS manager.
/// So, there is only one MDSController object in MDS.
/// </summary>
private readonly MDSController _mdsManager;
/// <summary>
/// This collection is used to send message and get response in SendMessageDirectly method.
/// SendMessageDirectly method must wait until response received. It waits using this collection.
/// Key: Message ID to wait response.
/// Value: ManualResetEvent to wait thread until response received.
/// </summary>
private readonly SortedList<string, WaitingMessage> _waitingMessages;
#endregion
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="communicationLayer">Reference to the Communication Layer</param>
/// <param name="storageManager">Reference to the Storage Manager</param>
/// <param name="routingTable">Reference to the routing table</param>
/// <param name="serverGraph">Reference to server graph</param>
/// <param name="clientApplicationList">Reference to application list</param>
/// <param name="mdsManager">Reference to MDS Manager object</param>
public OrganizationLayer(CommunicationLayer communicationLayer, IStorageManager storageManager, RoutingTable routingTable, MDSServerGraph serverGraph, MDSClientApplicationList clientApplicationList, MDSController mdsManager)
{
_settings = MDSSettings.Instance;
_communicationLayer = communicationLayer;
_storageManager = storageManager;
_routingTable = routingTable;
_serverGraph = serverGraph;
_clientApplicationList = clientApplicationList;
_mdsManager = mdsManager;
_waitingMessages = new SortedList<string, WaitingMessage>();
PrepareCommunicationLayer();
}
#endregion
#region Public methods
#region Starting / Stopping to Organization layer
/// <summary>
/// Starts the organization layer.
/// </summary>
public void Start()
{
_clientApplicationList.Start();
_serverGraph.Start();
_mdsManager.Start();
}
/// <summary>
/// Stops the organization layer.
/// </summary>
/// <param name="waitToStop">True, if caller thread must be blocked until organization layer stops.</param>
public void Stop(bool waitToStop)
{
_mdsManager.Stop(waitToStop);
_serverGraph.Stop(waitToStop);
_clientApplicationList.Stop(waitToStop);
}
/// <summary>
/// Waits to stop of organization layer.
/// </summary>
public void WaitToStop()
{
_mdsManager.WaitToStop();
_serverGraph.WaitToStop();
_clientApplicationList.WaitToStop();
}
#endregion
#region Other public methods
#region Client Application related methods
/// <summary>
/// Gets a list of all client applications as an array.
/// </summary>
/// <returns>Client applications array</returns>
public MDSClientApplication[] GetClientApplications()
{
lock (_clientApplicationList.Applications)
{
return _clientApplicationList.Applications.Values.ToArray();
}
}
/// <summary>
/// This method is used to add a new client application to MDS while MDS is running.
/// Used by MDSController to allow user to add a new application from MDSManager GUI.
/// It does all necessary tasks to add new application (Updates XML file, adds application to needed
/// collections of system...).
/// </summary>
/// <param name="name">Name of the new application</param>
public MDSClientApplication AddApplication(string name)
{
//Add to settings
lock (_settings.Applications)
{
_settings.Applications.Add(
new ApplicationInfoItem
{
Name = name
});
_settings.SaveToXml();
}
//Add to applications list
lock (_clientApplicationList.Applications)
{
var newApplication = new MDSClientApplication(name);
newApplication.Settings = _settings;
newApplication.StorageManager = _storageManager;
newApplication.MessageReceived += RemoteApplication_MessageReceived;
_clientApplicationList.Applications.Add(name, newApplication);
_communicationLayer.AddRemoteApplication(newApplication);
newApplication.Start();
return newApplication;
}
}
/// <summary>
/// This method is used to delete a client application from MDS while MDS is running.
/// Used by MDSController to allow user to remove an application from MDSManager GUI.
/// It does all necessary tasks to remove application (Updates XML file, removes application from needed
/// collections of system...).
/// </summary>
/// <param name="name">Name of the application to remove</param>
/// <returns>Removed client application</returns>
public MDSClientApplication RemoveApplication(string name)
{
//Remove from application list and communicaton layer
MDSClientApplication clientApplication = null;
lock (_clientApplicationList.Applications)
{
if (_clientApplicationList.Applications.ContainsKey(name))
{
clientApplication = _clientApplicationList.Applications[name];
if (clientApplication.ConnectedCommunicatorCount > 0)
{
throw new MDSException("Client application can not be removed. It has " +
clientApplication.ConnectedCommunicatorCount +
" communicators connected. Please stop theese communicators first.");
}
clientApplication.MessageReceived -= RemoteApplication_MessageReceived;
_communicationLayer.RemoveRemoteApplication(clientApplication);
_clientApplicationList.Applications.Remove(name);
}
}
if (clientApplication == null)
{
throw new MDSException("There is no client application with name " + name);
}
clientApplication.Stop(true);
//Remove from settings
lock (_settings.Applications)
{
for (var i = 0; i < _settings.Applications.Count;i++ )
{
if (_settings.Applications[i].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
_settings.Applications.RemoveAt(i);
_settings.SaveToXml();
break;
}
}
}
return clientApplication;
}
#endregion
#endregion
#endregion
#region Private methods
#region Initializing part
/// <summary>
/// Adds server and applications to communication layer and registers their MessageReceived events.
/// </summary>
private void PrepareCommunicationLayer()
{
//Add MDS servers to communication layer, set needed objects and register events
foreach (var adjacentServer in _serverGraph.AdjacentServers.Values)
{
adjacentServer.Settings = _settings;
_communicationLayer.AddRemoteApplication(adjacentServer);
adjacentServer.StorageManager = _storageManager;
adjacentServer.MessageReceived += RemoteApplication_MessageReceived;
}
//Add applications to communication layer, set needed objects and register events
foreach (var clientApplication in _clientApplicationList.Applications.Values)
{
clientApplication.Settings = _settings;
_communicationLayer.AddRemoteApplication(clientApplication);
clientApplication.StorageManager = _storageManager;
clientApplication.MessageReceived += RemoteApplication_MessageReceived;
}
_mdsManager.Settings = _settings;
_communicationLayer.AddRemoteApplication(_mdsManager);
}
#endregion
#region Incoming message handling
#region Incoming message handling from MDS Serves / Client Applications
/// <summary>
/// This method is handles all adjacent server's and client application's MessageReceived events.
/// </summary>
/// <param name="sender">Creator of event</param>
/// <param name="e">Event arguments</param>
private void RemoteApplication_MessageReceived(object sender, MessageReceivedFromRemoteApplicationEventArgs e)
{
try
{
//Incoming data transfer message request
if (e.Message.MessageTypeId == MDSMessageFactory.MessageTypeIdMDSDataTransferMessage)
{
//Get, check and process message
var dataTransferMessage = e.Message as MDSDataTransferMessage;
ProcessDataTransferMessage(e.Application as MDSPersistentRemoteApplicationBase, e.Communicator, dataTransferMessage);
}
//Incoming delivery result (ACK/Reject message)
else if ((e.Message.MessageTypeId == MDSMessageFactory.MessageTypeIdMDSOperationResultMessage) &&
(!string.IsNullOrEmpty(e.Message.RepliedMessageId)))
{
//Find and send signal/pulse to waiting thread for this message
WaitingMessage waitingMessage = null;
lock (_waitingMessages)
{
if (_waitingMessages.ContainsKey(e.Message.RepliedMessageId))
{
waitingMessage = _waitingMessages[e.Message.RepliedMessageId];
}
}
if(waitingMessage != null)
{
waitingMessage.ResponseMessage = e.Message as MDSOperationResultMessage;
waitingMessage.WaitEvent.Set();
}
}
//Incoming Ping message
else if ((e.Message.MessageTypeId == MDSMessageFactory.MessageTypeIdMDSPingMessage) &&
string.IsNullOrEmpty(e.Message.RepliedMessageId))
{
//Reply ping message
e.Application.SendMessage(new MDSPingMessage {RepliedMessageId = e.Message.MessageId},
e.Communicator);
}
}
catch (Exception ex)
{
Logger.Warn(ex.Message, ex);
}
}
#endregion
#endregion
#region Processing MDSDataTransferMessage message
/// <summary>
/// This method is used to process a MDSDataTransferMessage that is gotten from a mds server or client application.
/// Message is sent to destination or next server in one of these three conditions:
/// - Destination server is this server and application exists on this server
/// - Destination server is an adjacent server of this server
/// - Destination server in server graph and there is a path from this server to destination server
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="senderCommunicator">Sender communicator</param>
/// <param name="message">Message</param>
private void ProcessDataTransferMessage(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
{
//Check for duplicate messages
if (senderApplication.LastAcknowledgedMessageId == message.MessageId)
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, true, "Duplicate message.");
return;
}
try
{
AddThisServerToPassedServerList(message);
FillEmptyMessageFields(message, senderApplication, senderCommunicator);
_routingTable.ApplyRouting(message);
//If Destination server is this server then deliver message to the destination application
if (message.DestinationServerName.Equals(_settings.ThisServerName, StringComparison.OrdinalIgnoreCase))
{
SentToClientApplication(senderApplication, senderCommunicator, message);
}
//Else, if destination server is an adjacent of this server (so they can communicate directly)
else if (_serverGraph.AdjacentServers.ContainsKey(message.DestinationServerName))
{
SentToAdjacentServer(senderApplication, senderCommunicator, message);
}
//Else, if destination server is not adjacent but in server graph (so, send message to next server)
else if (_serverGraph.ServerNodes.ContainsKey(message.DestinationServerName))
{
SendToNextServer(senderApplication, senderCommunicator, message);
}
else
{
//return error to sender
SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Destination does not exists.");
}
}
catch (Exception ex)
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, false, ex.Message);
}
}
/// <summary>
/// Adds this server to the list of passed servers of message.
/// </summary>
/// <param name="message">Message object</param>
private void AddThisServerToPassedServerList(MDSDataTransferMessage message)
{
//Create new transmit report for this server
var transmitReport = new ServerTransmitReport
{
ArrivingTime = DateTime.Now,
ServerName = _settings.ThisServerName
};
if (message.PassedServers == null)
{
//Create array
message.PassedServers = new ServerTransmitReport[1];
}
else
{
//Create new array (that has item one more than original array)
var newArray = new ServerTransmitReport[message.PassedServers.Length + 1];
//Copy old items to new array
if (message.PassedServers.Length > 1)
{
Array.Copy(message.PassedServers, 0, newArray, 0, message.PassedServers.Length);
}
//Replace old array by new array
message.PassedServers = newArray;
}
//Add transmit report to array
message.PassedServers[message.PassedServers.Length - 1] = transmitReport;
}
/// <summary>
/// Checks a MDSDataTransferMessage and fills it's empty fields by default values.
/// </summary>
/// <param name="dataTransferMessage">Message</param>
/// <param name="senderApplication">Sender application</param>
/// <param name="communicator">Sender communicator of application</param>
private void FillEmptyMessageFields(MDSDataTransferMessage dataTransferMessage, MDSRemoteApplication senderApplication, ICommunicator communicator)
{
//Default SourceApplicationName: Name of the sender application.
if (string.IsNullOrEmpty(dataTransferMessage.SourceApplicationName))
{
dataTransferMessage.SourceApplicationName = senderApplication.Name;
}
//Default SourceServerName: Name of this server.
if (string.IsNullOrEmpty(dataTransferMessage.SourceServerName))
{
dataTransferMessage.SourceServerName = _settings.ThisServerName;
}
//Default DestinationApplicationName: Name of the sender application.
if (string.IsNullOrEmpty(dataTransferMessage.DestinationApplicationName))
{
dataTransferMessage.DestinationApplicationName = senderApplication.Name;
}
//Default DestinationServerName: Name of this server.
if (string.IsNullOrEmpty(dataTransferMessage.DestinationServerName))
{
dataTransferMessage.DestinationServerName = _settings.ThisServerName;
}
if (dataTransferMessage.SourceServerName == _settings.ThisServerName)
{
//Sender communicator id is being set.
dataTransferMessage.SourceCommunicatorId = communicator.ComminicatorId;
}
}
/// <summary>
/// This method is called by ProcessDataTransferMessage when a message must be sent to a aclient application
/// that is running on this server.
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="senderCommunicator">Sender communicator</param>
/// <param name="message">Message</param>
private void SentToClientApplication(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
{
MDSClientApplication destinationApplication = null;
//If application exists on this server, get it
lock (_clientApplicationList.Applications)
{
if (_clientApplicationList.Applications.ContainsKey(message.DestinationApplicationName))
{
destinationApplication = _clientApplicationList.Applications[message.DestinationApplicationName];
}
}
//If application doesn't exist on this server...
if (destinationApplication == null)
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Application does not exists on this server (" + _settings.ThisServerName + ").");
return;
}
//Send message according TransmitRule
switch (message.TransmitRule)
{
case MessageTransmitRules.DirectlySend:
SendMessageDirectly(
senderApplication,
senderCommunicator,
destinationApplication,
message
);
break;
default:
// case MessageTransmitRules.StoreAndForward:
// case MessageTransmitRules.NonPersistent:
EnqueueMessage(
senderApplication,
senderCommunicator,
destinationApplication,
message
);
break;
}
}
/// <summary>
/// This method is called by ProcessDataTransferMessage when a message must be sent to an adjacent server of this server.
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="senderCommunicator">Sender communicator</param>
/// <param name="message">Message</param>
private void SentToAdjacentServer(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
{
/* On one of these conditions, message is stored:
* - TransmitRule = StoreAndForward
* - (TransmitRule = StoreOnSource OR StoreOnEndPoints) AND (This server is the source server)
*/
if (message.TransmitRule == MessageTransmitRules.StoreAndForward ||
message.TransmitRule == MessageTransmitRules.NonPersistent)
{
EnqueueMessage(
senderApplication,
senderCommunicator,
_serverGraph.AdjacentServers[message.DestinationServerName],
message
);
}
/* Else, message is not stored in these conditions:
* - TransmitRule = DirectlySend OR StoreOnDestination (this server can not be destination because message is being sent to another server right now)
* - All Other conditions
*/
else
{
SendMessageDirectly(
senderApplication,
senderCommunicator,
_serverGraph.AdjacentServers[message.DestinationServerName],
message
);
}
}
/// <summary>
/// This method is called by ProcessDataTransferMessage when a message must be sent to a server
/// that is not an adjacent of this server. Message is forwarded to next server.
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="senderCommunicator">Sender communicator</param>
/// <param name="message">Message</param>
private void SendToNextServer(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
{
//If there is a path from this server to destination server...
if (_serverGraph.ThisServerNode.BestPathsToServers.ContainsKey(message.DestinationServerName))
{
//Find best path to destination server
var bestPath = _serverGraph.ThisServerNode.BestPathsToServers[message.DestinationServerName];
//If path is regular (a path must consist of 2 nodes at least)...
if (bestPath.Count > 1)
{
//Next server
var nextServerName = bestPath[1].Name;
/* On one of these conditions, message is stored:
* - TransmitRule = StoreAndForward
* - (TransmitRule = StoreOnSource OR StoreOnEndPoints) AND (This server is the source server)
*/
if (message.TransmitRule == MessageTransmitRules.StoreAndForward ||
message.TransmitRule == MessageTransmitRules.NonPersistent)
{
EnqueueMessage(
senderApplication,
senderCommunicator,
_serverGraph.AdjacentServers[nextServerName],
message
);
}
/* Else, message is not stored in these conditions:
* - TransmitRule = DirectlySend OR StoreOnDestination (this server can not be destination because message is being sent to another server right now)
* - All Other conditions
*/
else
{
SendMessageDirectly(
senderApplication,
senderCommunicator,
_serverGraph.AdjacentServers[nextServerName],
message
);
}
}
//Server graph may be wrong (this is just for checking case, normally this situation must not become)
else
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Server graph is wrong.");
}
}
//No path from this server to destination server
else
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "There is no path from this server to destination.");
}
}
/// <summary>
/// Sends message directly to application (not stores) and waits ACK.
/// This method adds message to queue by MDSPersistentRemoteApplicationBase.AddMessageToHeadOfQueue method
/// and waits a signal/pulse from RemoteApplication_MessageReceived method to get ACK/Reject.
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="senderCommunicator">Sender communicator</param>
/// <param name="destApplication">Destination application/server</param>
/// <param name="message">Message</param>
private void SendMessageDirectly(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSPersistentRemoteApplicationBase destApplication, MDSDataTransferMessage message)
{
//Create a WaitingMessage to wait and get ACK/Reject message and add it to waiting messages
var waitingMessage = new WaitingMessage();
lock (_waitingMessages)
{
_waitingMessages[message.MessageId] = waitingMessage;
}
try
{
//Add message to head of queue of remote application
destApplication.AddMessageToHeadOfQueue(message);
//Wait until thread is signalled by another thread to get response (Signalled by RemoteApplication_MessageReceived method)
waitingMessage.WaitEvent.WaitOne((int) (_settings.MessageResponseTimeout*1.2));
//Evaluate response
if (waitingMessage.ResponseMessage.Success)
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, true, "Success.");
}
else
{
SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Message is not acknowledged. Reason: " + waitingMessage.ResponseMessage.ResultText);
}
}
finally
{
//Remove message from waiting messages
lock (_waitingMessages)
{
_waitingMessages.Remove(message.MessageId);
}
}
}
/// <summary>
/// Adds message to destination's send queue.
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="senderCommunicator">Sender communicator</param>
/// <param name="destApplication">Destination application/server</param>
/// <param name="message">Message</param>
private static void EnqueueMessage(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSPersistentRemoteApplicationBase destApplication, MDSDataTransferMessage message)
{
destApplication.EnqueueMessage(message);
SendOperationResultMessage(senderApplication, senderCommunicator, message, true, "Success.");
}
/// <summary>
/// To send a MDSOperationResultMessage to remote application's spesific communicator.
/// </summary>
/// <param name="senderApplication">Sender application/server</param>
/// <param name="communicator">Communicator to send message</param>
/// <param name="repliedMessage">Replied Message</param>
/// <param name="success">Operation result</param>
/// <param name="resultText">Details</param>
private static void SendOperationResultMessage(MDSRemoteApplication senderApplication, ICommunicator communicator, MDSDataTransferMessage repliedMessage, bool success, string resultText)
{
try
{
if (success)
{
//Save MessageId of acknowledged message to do not receive same message again
senderApplication.LastAcknowledgedMessageId = repliedMessage.MessageId;
}
senderApplication.SendMessage(new MDSOperationResultMessage
{
RepliedMessageId = repliedMessage.MessageId,
Success = success,
ResultText = resultText
}, communicator);
}
catch (Exception ex)
{
Logger.Warn(ex.Message, ex);
}
}
#endregion
#endregion
#region Sub classes
/// <summary>
/// This class is used as item in _waitingMessages collection.
/// Key: Message ID to wait response.
/// Value: ManualResetEvent to wait thread until response received.
/// </summary>
/// </summary>
private class WaitingMessage
{
/// <summary>
/// ManualResetEvent to wait thread until response received.
/// </summary>
public ManualResetEvent WaitEvent { get; private set; }
/// <summary>
/// Response message received as ACK/Reject for sent message
/// </summary>
public MDSOperationResultMessage ResponseMessage { get; set; }
/// <summary>
/// Creates a new WaitingMessage.
/// </summary>
public WaitingMessage()
{
WaitEvent = new ManualResetEvent(false);
}
}
#endregion
}
}
|
using System;
using System.Collections;
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.Web.Configuration;
using System.Windows.Forms;
using ResourceTranslator.Abs;
using ResourceTranslator.Data;
using ResourceTranslator.Impl;
using ResourceTranslator.Static;
namespace ResourceTranslator
{
public partial class TranslatorWinForm : Form, TranslatorForm
{
private ResourceTranslator.Impl.ResourceTranslator _app;
public TranslatorWinForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Error.Clear();
if(textBox1.Text == String.Empty)
Error.SetError(this.textBox1, "Please enter string to translate");
else if (textBox2.Text == String.Empty)
Error.SetError(this.textBox2, "Please enter resource key to write");
else
{
try
{
_app = new Impl.ResourceTranslator(new GbrFilesInfo(new GbrLanguages()), new ResxInputValidator());
_app.ValidateResources(textBox2.Text, chkWriteToDefault.Checked);
var translations =_app.Translate(new BingTranslator(), textBox1.Text);
if (chkWriteToDefault.Checked)
Helper.UpdateResourceFile(new Hashtable() {{textBox2.Text, textBox1.Text}}, "c:\\translationtemp\\gbr.resx", this );
_app.WriteToFile(new ResxWriter(), translations, this);
}
catch(Exception ex)
{
Error.SetError(textBox2, ex.Message);
}
}
}
public string TextOutput
{
get { return txtOutput.Text; }
set { txtOutput.AppendText(value + Environment.NewLine); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace ShootemUp
{
class JatekTerulet : FrameworkElement
{
List<Kor> korok = new List<Kor>();
DispatcherTimer timer = new DispatcherTimer();
Quadtree<Kor> quad = new Quadtree<Kor>(0, new Rect(0, 0, 600, 400));
Random rand = new Random();
public JatekTerulet()
{
this.Loaded += JatekTerulet_Loaded;
}
void JatekTerulet_Loaded(object sender, RoutedEventArgs e)
{
Window.GetWindow(this).KeyDown += JatekTerulet_KeyDown;
for (int i = 0; i < 100; i++)
{
int tsize = rand.Next(5, 6);
Kor temp = new Kor(rand.Next(tsize,(int)this.Width-tsize), rand.Next(tsize,(int)this.Height), new Vektor(rand.Next(-5, 5), rand.Next(-5,5)),tsize);
korok.Add(temp);
}
timer.Interval = new TimeSpan(0, 0, 0, 0, 16);
timer.Tick += Timer_Tick;
timer.Start();
InvalidateVisual();
}
private void Timer_Tick(object sender, EventArgs e)
{
quad.Clear();
foreach (Kor item in korok)
{
item.Move((int)this.ActualHeight, (int)this.ActualWidth);
item.Brush = Brushes.Black;
quad.Insert(item);
}
//collision detecting
List<Kor> returnedList = new List<Kor>();
foreach (var item in korok)
{
returnedList.Clear();
quad.Retrieve(returnedList, item);
foreach (var item2 in returnedList)
{
//nagyon lassu
/* intersection = Geometry.Combine(item.Geometria, item2.Geometria,
GeometryCombineMode.Intersect, null);*/
/* if (intersection.GetArea() != 0 && item!=item2)*/
int nagyX = (int)Math.Abs(item.X - item2.X);
int nagyY = (int)Math.Abs(item.Y - item2.Y);
if (Math.Sqrt((nagyX*nagyX+nagyY*nagyY))<=item.Size+item2.Size && item!=item2)
{
item.Brush = Brushes.Red;
item2.Brush = Brushes.Red;
}
}
}
InvalidateVisual();
}
private void JatekTerulet_KeyDown(object sender, KeyEventArgs e)
{
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
foreach (Kor item in korok)
{
drawingContext.DrawGeometry(item.Brush, new Pen(Brushes.Green, 2), item.Geometria);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Sunny.HttpRequestClientConsole.Interface
{
public class BalanceStatusBatchUpdateRequest
{
[JsonProperty("balanceStatusBatchUpdateInputParamsList")]
public List<BalanceRequiredToUpdate> BalancesToUpdate { get; set; }
}
public class BalanceRequiredToUpdate
{
[JsonProperty("payoutAccountId")]
public string AccountId { get; set; }
[JsonProperty("balanceId")]
public Guid BalanceId { get; set; }
[JsonProperty("balanceStatus")]
public string ToStatus { get; set; }
public string GetResourceInfo()
{
return string.Format("AccountId Guid={0}; BalanceId={1}; ToStatus={2}",
this.AccountId,
this.BalanceId,
this.ToStatus);
}
public string GetExtendedInfo()
{
return string.Empty;
}
}
public class BalanceStatusBatchUpdateResponse
{
[JsonProperty("balanceStatusBatchUpdateResultTupleList")]
public List<UpdatedBalance> UpdatedBalance { get; set; }
}
public class UpdatedBalance
{
[JsonProperty("balanceId")]
public Guid BalanceId { get; set; }
[JsonProperty("balanceItemResult")]
public string BalanceItemResult { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SupercapController
{
class MultiDownloader
{
public static bool busy = false; // When downloading is in progress set this flag
private static int currentIndex = 0;
private static int targetIndex = 0;
static List<Tuple<int, int>> _adrList;
static Action<List<byte[]>> _sucCb;
static Action _fCb;
static List<byte[]> finalDataList;
public static bool Download(List<Tuple<int, int>> adrList, Action<List<byte[]>> sucCb, Action fCb)
{
if (busy)
{
return false; // Downloader is busy, abort request
}
busy = true;
finalDataList = new List<byte[]>();
_adrList = adrList;
currentIndex = 0;
targetIndex = adrList.Count;
_sucCb = sucCb;
_fCb = fCb;
// Bootstrap
CommandFormerClass cm = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr);
cm.AppendReadFromAddress(_adrList[currentIndex].Item1, _adrList[currentIndex].Item2);
var data = cm.GetFinalCommandList();
if (SerialDriver.Send(data, Fetcher, FailCallback))
{
currentIndex++;
return true;
}
else
{
// Serial driver is busy
return false;
}
}
private static void FailCallback()
{
// Something gone wrong
_fCb(); // Call failcallback
busy = false;
return;
}
private static void Fetcher(byte[] b)
{
finalDataList.Add(b); // First add received data to list (we had bootstrap)
if (currentIndex >= targetIndex)
{
// All went well, call successful callback with results
_sucCb(finalDataList);
busy = false;
return;
}
Thread.Sleep(10); // Device cant manage requests so fast
// Send command to get measurement header + data
CommandFormerClass cm = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr);
cm.AppendReadFromAddress(_adrList[currentIndex].Item1, _adrList[currentIndex].Item2);
var data = cm.GetFinalCommandList();
SerialDriver.Send(data, Fetcher, FailCallback);
currentIndex++;
}
}
}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD20
{
/// <summary>
/// LD2091 的摘要说明。
/// </summary>
public class LD20E510 : BasePage
{
protected System.Web.UI.WebControls.Button BT_ASK;
protected System.Web.UI.WebControls.Label Label_headLine;
protected Infragistics.WebUI.UltraWebGrid.UltraWebGrid DataGrid2;
protected System.Web.UI.WebControls.Label Label_second;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
string FKPZH = this.Request.QueryString["FKPZH"];
if(FKPZH != null)
{
this.Label_second.Text = FKPZH;
query();
}
else
{
this.Label_headLine.Text = "没有对账单号!";
}
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.BT_ASK.Click += new System.EventHandler(this.BT_ASK_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
public void query()
{
// 查询对账单数据
string strSQL = @"
SELECT *
FROM F_FKPZ
WHERE FKPZH = @FKPZH
";
SqlParameter[] paras = new SqlParameter[] {
new SqlParameter("@FKPZH", this.Label_second.Text.Trim())
};
SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,paras);
if(sdr.Read())
{
this.Label_headLine.Text = sdr["DESCRIPTION"]+"";
this.DataGrid2.Columns.FromKey("SL").Footer.Caption = sdr["JSZL"]+"";
this.DataGrid2.Columns.FromKey("JE").Footer.Caption = sdr["JE"]+"";
query1(); // 查询明细数据
}
else
{
this.Label_headLine.Text = "查询不到数据!";
}
}
private void query1()
{
// 查询对账单的费用明细数据
string strSQL = @"
SELECT T1.*, T2.TDH, T2.ZYRQ, T2.PM, T2.ZHD, T2.XHD, T2.JZHJ, T2.MZHJ, T2.JSHJ
FROM F_FY T1, B_YSFS T2
WHERE T2.YSLSH = T1.YWLSH AND T1.YSYF = '20' AND T1.SC = 'N'
AND T1.JSYSFS = '1'
AND T1.FKPZH = @FKPZH
ORDER BY T2.ZYRQ
";
SqlParameter[] paras = new SqlParameter[] {
new SqlParameter("@FKPZH", this.Label_second.Text.Trim())
};
this.DataGrid2.Rows.Clear();
this.DataGrid2.DataSource=SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,paras);
this.DataGrid2.DataBind();
}
private void BT_ASK_Click(object sender, System.EventArgs e)
{
// 查询
query();
}
}
}
|
using System.Collections.Generic;
using System.Text;
using GameLoanManager.Data;
using GameLoanManager.Domain.Security;
using GameLoanManager.Helpers.DependencyInjection;
using GameLoanManager.Helpers.Extensions;
using GameLoanManager.Helpers.Mapping;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GameLoanManager.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Context>(options =>
{
options.UseNpgsql(Configuration.GetConnectionString("WebApiConnection"));
}
);
services.AddCors(c =>
{
c.AddDefaultPolicy(options => options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddControllers().AddNewtonsoftJson(o =>
{
o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
o.SerializerSettings.Converters.Add(new StringEnumConverter());
}
);
services.ConfigureProblemDetailsModelState();
ServicesConfiguration.ConfigureDependencies(services);
RepositoriesConfiguration.ConfigureDependencies(services);
services.AddSingleton(MapperConfiguration.Configure());
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var tokenConfigurations = new TokenConfigurations();
new ConfigureFromConfigurationOptions<TokenConfigurations>(Configuration.GetSection("TokenConfigurations"))
.Configure(tokenConfigurations);
services.AddSingleton(tokenConfigurations);
var key = Encoding.ASCII.GetBytes(tokenConfigurations.Key);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(a =>
{
a.AddPolicy("Authorization", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Api para gerenciamento de empréstimo de Jogos",
Description = "Gerenciar empréstimos dos jogos para os amigos"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Entre com 'Bearer', espaço e Token JWT",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
}, new List<string>()
}
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Context context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
context.Database.Migrate();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Gerenciamento de empréstimo de Jogos API V1");
});
// Redirecionando para a página do swagger
var option = new RewriteOptions();
option.AddRedirect("^$", "swagger");
app.UseRewriter(option);
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.Use(async (context, next) =>
{
// Add Header
context.Response.Headers["Access-Control-Allow-Origin"] = "*";
// Call next middleware
await next.Invoke();
});
app.UseAuthentication();
app.UseAuthorization();
app.UseProblemDetailsExceptionHandler(env.IsDevelopment());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Serialization
{
class Program
{
private static void Serialize(Person sp)
{
// Create file to save the data to
FileStream fs = new FileStream("Person.Dat", FileMode.Create);
// Create a BinaryFormatter object to perform the serialization
BinaryFormatter bf = new BinaryFormatter();
// Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(fs, sp);
// Close the file
fs.Close();
}
private static Person Deserialize()
{
Person dsp;
// Open file to read the data from
FileStream fs = new FileStream("Person.Dat", FileMode.Open);
// Create a BinaryFormatter object to perform the deserialization
BinaryFormatter bf = new BinaryFormatter();
// Use the BinaryFormatter object to deserialize the data from the file
dsp = (Person)bf.Deserialize(fs);
// Close the file
fs.Close();
return dsp;
}
static void Main(string[] args)
{
Person mate = new Person("name", 22);
Serialize(mate);
Console.WriteLine(Deserialize());
}
}
}
|
using NUnit.Framework;
using RollingStones;
using System.Collections.Generic;
using System.Linq;
namespace TestsForGameOfStones
{
public class Tests
{
Tasks actual = new Tasks();
[TestCase(24, new int[] {1, 2, 2}, new string[] {"+", "+", "*"}, ExpectedResult = 11)]
[TestCase(44, new int[] {1, 2, 2}, new string[] {"+", "+", "*"}, ExpectedResult = 21)]
[TestCase(42, new int[] {1, 5, 3}, new string[] {"+", "+", "*"}, ExpectedResult = 13)]
public int FindBadNumberTest(int k, int[] a, string[] b)
{
return actual.FindBadValue(k, a, b);
}
[TestCase(24, new int[] { 1, 2, 2 }, new string[] { "+", "+", "*" }, ExpectedResult = new int[] { 9, 10})]
[TestCase(44, new int[] { 1, 2, 2 }, new string[] { "+", "+", "*" }, ExpectedResult = new int[] { 19, 20})]
[TestCase(42, new int[] { 1, 5, 3 }, new string[] { "+", "+", "*" }, ExpectedResult = new int[] { 8, 12})]
public int[] CreateGraphTest(int k, int[] a, string[] b)
{
List<int> stone = new List<int>();
for (int i = 1; i < k - 1; i++)
{
stone.Add(i);
}
Turns.listOfSForWin = new List<int>();
Turns.listOfVasyaFirst = new List<int>();
Node node = new Node();
node.CreateBranchesOfTurns(stone, k, a, b);
node.CreateListsOfStoneNumber(FindBadNumberTest(k, a, b));
return Turns.listOfSForWin.ToArray();
}
}
} |
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;
/// <summary>
/// This program is a GUI of the client spreadsheet for a multi-client Spreadsheet Server.
///
/// 3505 version of ClientGUI by Rebekah Peterson, Jacqulyn Machardy, Anastasia Gonzalez, Michael Raleigh
/// 3500 version of SpreadsheetGUI by Anastasia Gonzalez, Aaron Bellis
/// </summary>
namespace SpreadsheetGUI
{
public partial class Form3 : Form
{
public Form3(string[] sheets)
{
InitializeComponent();
comboBox.Items.AddRange(sheets);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KT.DTOs.Objects;
using KT.ServiceInterfaces;
using KnowledgeTester.Helpers;
using KnowledgeTester.Models;
using KnowledgeTester.Ninject;
using KT.ExcelImporter;
namespace KnowledgeTester.Controllers
{
public class SubcategoryController : BaseController
{
//
// GET: /Subcategory/
private Guid _subcatId;
public ActionResult Index(Guid? id)
{
// user rights
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
if (id == null)
{
ViewBag.Message = "Please select a valid subcategory!";
return RedirectToAction("Index", "Category", new { id = SessionWrapper.CurrentCategoryId });
}
var catName = ServicesFactory.GetService<IKtCategoriesService>().GetById(SessionWrapper.CurrentCategoryId).Name;
if (id.Value.Equals(Guid.Empty))
{
var m = new SubcategoryModel(catName);
return View(m);
}
var subCat = ServicesFactory.GetService<IKtSubcategoriesService>().GetById(id.Value);
if (subCat != null)
{
var m = new SubcategoryModel(subCat, catName);
_subcatId = m.Id;
ViewBag.IsExistingSubcategory = true;
SessionWrapper.CurrentSubcategoryId = subCat.Id;
return View(m);
}
ViewBag.Message = "Category does not exists!";
return View();
}
[HttpPost]
public ActionResult Save(SubcategoryModel model)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
{
return View("Index", model);
}
_subcatId = model.Id.Equals(Guid.Empty) ?
ServicesFactory.GetService<IKtSubcategoriesService>().Save(model.Name, SessionWrapper.CurrentCategoryId) :
ServicesFactory.GetService<IKtSubcategoriesService>().Save(model.Name, SessionWrapper.CurrentCategoryId, model.Id);
return RedirectToAction("Index", "Subcategory", new { id = _subcatId });
}
[HttpPost]
public ActionResult DeleteQuestion(Guid id)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
ServicesFactory.GetService<IKtQuestionsService>().Delete(id);
return Json("Question is deleted!", JsonRequestBehavior.AllowGet);
}
public ActionResult GetQuestions(string text)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
var s = new List<QuestionDto>();
if (!SessionWrapper.CurrentSubcategoryId.Equals(Guid.Empty))
{
s = ServicesFactory.GetService<IKtQuestionsService>().GetBySubcategory
(SessionWrapper.CurrentSubcategoryId).ToList();
}
if (!String.IsNullOrEmpty(text))
{
s = s.Where(a => a.Text.Contains(text)).ToList();
}
var result = new
{
total = (int)Math.Ceiling((double)s.Count / 10),
page = 1,
records = s.Count,
rows = (from row in s
orderby ServicesFactory.GetService<IKtQuestionsService>().GetUsability(row.Id) descending
select new
{
Id = row.Id,
Text = row.Text.Substring(0, row.Text.Length < 75 ? row.Text.Length : 75) + (row.Text.Length < 75 ? string.Empty : "..."),
Multiple = row.MultipleResponse.ToString().ToLower(),
Usability = ServicesFactory.GetService<IKtQuestionsService>().GetUsability(row.Id) + " %"
}).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
if (file != null)
{
if (file.ContentLength > 0)
{
var fileStream = new StreamReader(file.InputStream);
var dtos = ServicesFactory.GetService<IExcelParser>().Parse(fileStream);
foreach (var dto in dtos)
{
//save question
var id = ServicesFactory.GetService<IKtQuestionsService>()
.Save(dto.Text, SessionWrapper.CurrentSubcategoryId,
null, dto.MultipleResponse, dto.Argument);
foreach (var ans in dto.Answers)
{
//saving answers
ServicesFactory.GetService<IKtAnswersService>().Save(ans.Id, id, ans.Text, ans.IsCorrect);
}
}
}
}
return RedirectToAction("Index", "Subcategory", new { id = SessionWrapper.CurrentSubcategoryId });
}
public FileResult DownloadTemplate()
{
var bytearray = System.IO.File.ReadAllBytes(HttpContext.Server.MapPath("~/KT Template.xlsx"));
return File(bytearray, "application/force-download", "KT Template.xlsx");
}
}
}
|
using Com.Aote.Logs;
using System;
using Com.Aote.ObjectTools;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices.Automation;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Com.Aote.GoldenTax
{
//金税盘
public class GoldenTax : GeneralObject
{
private static Log Log = Log.GetInstance("Com.Aote.GoldenTax.GoldenTax");
private static dynamic obj = null;
//金税系统ip
public static string TaxIp { get; set; }
/**
* 金税盘数字证书密码
**/
public static string CertPassWord { get; set; }
public GoldenTax()
{
}
public GoldenTax(string ip, string certPass)
{
if (ip != null && !ip.Equals(""))
{
TaxIp = ip;
}
if (certPass != null && !certPass.Equals(""))
{
CertPassWord = certPass;
}
}
public void Init()
{
try
{
if (TaxIp == null || TaxIp.Equals(""))
{
MessageBox.Show("未设置金税ip地址");
return;
}
Log.Debug("开始初始化金税盘");
if (obj == null)
{
obj = AutomationFactory.CreateObject("TaxCardX.GoldTax");
//开启
obj.CertPassWord = CertPassWord;
obj.OpenCard();
obj.CertPassWord = TaxIp;
obj.OpenCard();
if (obj.RetCode != 1011)
{
Log.Debug("初始化金税盘失败-" + obj.RetCode + obj.RetMsg);
MessageBox.Show(obj.RetMsg);
}
else
{
Log.Debug("初始化金税盘成功-" + obj.RetCode);
MessageBox.Show("初始化金税盘成功");
}
}
}
catch (Exception ee)
{
Log.Debug("初始化金税盘异常-" + ee.Message);
MessageBox.Show("初始化金税盘异常" + ee.Message);
}
}
private bool isinit = false;
//是否初始化
public bool IsInit
{
get { return this.isinit; }
set
{
this.isinit = value;
if (isinit)
{
//初始化金税盘,开启金税盘
Init();
}
}
}
//关闭金税盘
public void Close()
{
if (obj != null)
{
obj.CloseCard();
}
}
/// <summary>
/// 查询库存发票
/// </summary>
public bool HasInvoice()
{
//没有初始化,不予执行
if (!IsInit) return true;
try
{
Log.Debug("查询库存发票");
//查询库存发票
obj.InfoKind = 2;
obj.GetInfo();
if (obj.RetCode != 3011)
{
Log.Debug("查询库存发票失败-" + obj.RetCode + obj.RetMsg);
MessageBox.Show(obj.RetMsg);
return false;
}
else
{
//十位发票代码
InfoTypeCode = obj.InfoTypeCode;
//发票号码
InfoNumber = obj.InfoNumber;
Log.Debug("查询库存发票成功-(十位发票代码)InfoTypeCode=" + InfoTypeCode);
Log.Debug("查询库存发票成功-(发票号码)InfoNumber=" + InfoNumber);
}
}
catch (Exception ee)
{
Log.Debug("查询库存发票异常-" + ee.Message);
return false;
}
return true;
}
/// <summary>
/// 开具发票,打印
/// </summary>
public void Print()
{
//没有初始化,不予执行
if (!IsInit) return;
this.State = State.Start;
Log.Debug("开始开具发票");
Log.Debug("InfoClientName(开票名称)-" + InfoClientName + ",InfoClientAddressPhone(开票地址,电话)-"
+ InfoClientAddressPhone + ",InfoTaxRate(税率)-" + InfoTaxRate + ",ListGoodsName(服务名称)-"
+ ListGoodsName + ",ListAmount(金额)-" + ListAmount + ",ListPrice(单价)-" + ListPrice
+ ",ListUnit(单位)-" + ListUnit + ",ListNumber(数量)-" + ListNumber + ",InfoCashier(收款人)-"
+ InfoCashier + ",InfoChecker(复核人)-" + InfoChecker + ",InfoNotes(备注)-" + InfoNotes);
obj.InvInfoInit();
//增值税普通发票
obj.InfoKind = 2;
//开票名称
obj.InfoClientName = InfoClientName;
//售方地址及电话
obj.InfoSellerAddressPhone = InfoSellerAddressPhone;
//售方开户行及账号
obj.InfoSellerBankAccount = InfoSellerBankAccount;
//开票地址,电话
obj.InfoClientAddressPhone = InfoClientAddressPhone;
//税率
obj.InfoTaxRate = InfoTaxRate;
char[] c = new char[] { '|' };
//服务名称
string[] names = ListGoodsName.Split(c);
//金额
//string[] amounts = ListAmount.Split(c);
string[] prices = ListPrice.Split(c);
//单位
string[] units = ListUnit.Split(c);
//数量
string[] numbers = ListNumber.Split(c);
//含税价标志
string[] pricekind = ListPriceKind.Split(c);
obj.ClearInvList();
for (int i = 0; i < names.Length; i++)
{
if (names[i].Equals("滞纳金") && double.Parse(prices[i]) <= 0)
{
continue;
}
//设置开票内容
obj.InvListInit();
//服务名称
obj.ListGoodsName = names[i];
//double amount = double.Parse(amounts[i]) / (InfoTaxRate *0.01 + 1);
//obj.ListAmount = Math.Round(amount, 2);
//obj.ListTaxAmount = amount * InfoTaxRate * 0.01;
//double price = double.Parse(prices[i]) / (InfoTaxRate * 0.01 + 1);
obj.ListPrice = double.Parse(prices[i]);
obj.ListUnit = units[i];
obj.ListNumber = double.Parse(numbers[i]);
obj.ListPriceKind = Int32.Parse(pricekind[i]);
obj.AddInvList();
}
//收款人
obj.InfoCashier = InfoCashier;
//复核人
obj.InfoChecker = InfoChecker;
//开票人
obj.InfoInvoicer = InfoChecker;
//备注
obj.InfoNotes = InfoNotes;
obj.Invoice();
if (obj.RetCode != 4011)
{
Log.Debug("开具发票失败-" + obj.RetCode + obj.RegMsg);
MessageBox.Show(obj.RetMsg);
}
else
{
Log.Debug("开具发票成功-开始打印");
//打印
obj.PrintInv();
State = State.End;
OnCompleted(null);
}
}
/// <summary>
/// 工作完成事件
/// </summary>
public event AsyncCompletedEventHandler Completed;
public void OnCompleted(AsyncCompletedEventArgs args)
{
if (Completed != null)
{
Completed(this, args);
}
}
/// <summary>
/// 名称
/// </summary>
public string InfoClientName { get; set; }
/// <summary>
/// 电话地址
/// </summary>
public string InfoClientAddressPhone { get; set; }
/// <summary>
/// 售方电话地址
/// </summary>
public string InfoSellerAddressPhone { get; set; }
/// <summary>
/// 售方开户银行及账号
/// </summary>
public string InfoSellerBankAccount { get; set; }
/// <summary>
/// 收款人
/// </summary>
public string InfoCashier { get; set; }
/// <summary>
/// 复核人
/// </summary>
public string InfoChecker { get; set; }
/// <summary>
/// 税率,(5%传5)
/// </summary>
public int InfoTaxRate { get; set; }
private string typecode;
/// <summary>
/// 十位发票代码
/// </summary>
public string InfoTypeCode
{
get { return this.typecode; }
set
{
this.typecode = value;
OnPropertyChanged("InfoTypeCode");
}
}
private int infonumber;
/// <summary>
/// 发票号码
/// </summary>
public int InfoNumber
{
get { return this.infonumber; }
set
{
this.infonumber = value;
OnPropertyChanged("InfoNumber");
}
}
/// <summary>
/// 服务名称,可以设置多个,用"|"分隔开
/// </summary>
public string ListGoodsName { get; set; }
/// <summary>
/// 金额(不含税),可以设置多个,用"|"分隔开
/// </summary>
public string ListAmount { get; set; }
/// <summary>
/// 单价,可以设置多个,用"|"分隔开
/// </summary>
public string ListPrice { get; set; }
/// <summary>
/// 单位,可以设置多个,用"|"分隔开
/// </summary>
public string ListUnit { get; set; }
/// <summary>
/// 数量,可以设置多个,用"|"分隔开
/// </summary>
public string ListNumber { get; set; }
/// <summary>
/// 含税价标志,单价和金额的种类。0为不含税价,1为含税价
/// </summary>
public string ListPriceKind { get; set; }
/// <summary>
/// 备注信息
/// </summary>
public string InfoNotes { get; set; }
#region State 卡状态
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register("State", typeof(State), typeof(GoldenTax), null);
public State State
{
get { return (State)GetValue(StateProperty); }
set
{
SetValue(StateProperty, value);
}
}
#endregion
}
}
|
using System.Threading.Tasks;
using Entities.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Services.Services;
using WeddingRental.Models.Product.From;
namespace WeddingRental.Controllers
{
[Route("api/[controller]")]
public class OrderController: Controller
{
private readonly IOrderService _orderService;
private readonly UserManager<User> _userManager;
public OrderController(
IOrderService orderService,
UserManager<User> userManager)
{
_orderService = orderService;
_userManager = userManager;
}
[HttpGet]
[Route("[action]")]
public async Task<JsonResult> Get()
{
var user = await _userManager.GetUserAsync(User);
var views = await _orderService.GetOrderViewsAsync(user.Id);
return Json(views);
}
[HttpPut]
[Route("[action]")]
public async Task<IActionResult> Put([FromBody] ProductModel model)
{
var user = await _userManager.GetUserAsync(User);
var orderId = await _orderService
.AddProductToOrderAsync(model.ProductId, user.Id);
return Ok(orderId);
}
[HttpPost]
[Route("[action]")]
public async Task<IActionResult> Submit([FromBody] SubmitModel model)
{
await _orderService.SubmitAsync(model.OrderId);
return Ok();
}
}
} |
namespace UmbracoMapperified.Web.ViewModels
{
using System.Collections.Generic;
public class PagedCollection
{
public int TotalItems { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public bool IsFirstPage => PageNumber <= 1;
public bool IsLastPage => PageNumber >= TotalPages;
}
public class PagedCollection<T> : PagedCollection
{
public PagedCollection()
{
Items = new List<T>();
}
public IList<T> Items { get; set; }
}
} |
using Core.Internal.Dependency;
using Core.Utils.Linq2Db;
using LightInject;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.MSTest.FakeContext
{
[TestClass]
public class LoadWithTest
{
Scope _scope;
public TaxRateForBankEntityService Service { get; set; }
/// <summary>
/// Обычная инициализация IoC
/// </summary>
[TestInitialize]
public void Init()
{
//нужен Ioc
new DependencyInitializer()
.TestMode(true)
.ForAssembly(GetType().Assembly)
.Init((dbConfig, container) =>
{
dbConfig["Core.MSTest"] = "CN";
_scope = container.BeginScope();
container.InjectProperties(this);
});
}
[TestCleanup]
public void Dispose()
{
_scope.Dispose();
}
/// <summary>
/// Метод не относится к фейкам, а тестирует расширение LoadWith
/// </summary>
[TestMethod]
public void SelectLoadWithTest()
{
//Без LoadWith
var TaxRate = Service.GetQuery().FirstOrDefault();
Assert.IsNull(TaxRate.Bank);
//С LoadWith
var TaxRate2 = Service.GetQuery().LoadWith(e => e.Bank).FirstOrDefault();
Assert.IsNotNull(TaxRate2.Bank);
}
}
}
|
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.Diagnostics;
using System.IO;
namespace GameOfLife_AlexKing
{
public partial class GOLForm : Form
{
struct cell
{
public bool isOn;
public int liveNeighborCount;
}
//Various settings
int seed, univX, univY, timeInt;
Random rand = new Random();
bool toroidalUniverse = true;
bool gridOn = true;
bool HUDon = true;
bool neighborCountOn = true;
bool tenGridOn = true;
// The universe array
cell[,] universe;
cell[,] scratchPad;
// Drawing colors
Color gridColor, cellColor, backgroundColor, tenGridColor;
// The Timer class
Timer timer = new Timer();
// Generation count
ushort generations = 0;
ushort cellsAlive = 0;
public GOLForm()
{
InitializeComponent();
timeInt = Properties.Settings.Default.timerInterval;
seed = Properties.Settings.Default.seed;
tenGridColor = Properties.Settings.Default.tenGridColor;
gridColor = Properties.Settings.Default.gridColor;
cellColor = Properties.Settings.Default.cellColor;
backgroundColor = Properties.Settings.Default.backgroundColor;
univX = Properties.Settings.Default.universeX;
univY = Properties.Settings.Default.universeY;
universe = new cell[univX, univY];
scratchPad = new cell[univX, univY];
graphicsPanel1.BackColor = backgroundColor;
// Setup the timer
timer.Interval = timeInt; // milliseconds
timer.Tick += Timer_Tick;
timer.Enabled = false; // start timer running
}
// Calculate the next generation of cells
private void NextGeneration()
{
cell[,] tmp = universe;
scratchPad = tmp;
for (int y = 0; y < universe.GetLength(1); y++)
{
for (int x = 0; x < universe.GetLength(0); x++)
{
if (((universe[x, y].liveNeighborCount == 2 || tmp[x, y].liveNeighborCount == 3) && tmp[x, y].isOn == true) || (tmp[x, y].liveNeighborCount == 3 && tmp[x, y].isOn == false))
{
scratchPad[x, y].isOn = true;
}
if (tmp[x, y].liveNeighborCount < 2 || tmp[x, y].liveNeighborCount > 3)
{
scratchPad[x, y].isOn = false;
cellsAlive--;
}
scratchPad[x, y].liveNeighborCount = CountNeighborsToroidal(x, y, tmp);
}
}
//Setting universe to updated universe(scratchPad)
universe = scratchPad;
// Increment generation count
generations++;
// Update status strip generations
toolStripStatusLabelGenerations.Text = "Generations = " + generations.ToString();
graphicsPanel1.Invalidate();
}
// The event called by the timer every Interval milliseconds.
private void Timer_Tick(object sender, EventArgs e)
{
NextGeneration();
}
private void graphicsPanel1_Paint(object sender, PaintEventArgs e)
{
// Calculate the width and height of each cell in pixels
// CELL WIDTH = WINDOW WIDTH / NUMBER OF CELLS IN X
float cellWidth = graphicsPanel1.ClientSize.Width / (float)universe.GetLength(0);
// CELL HEIGHT = WINDOW HEIGHT / NUMBER OF CELLS IN Y
float cellHeight = graphicsPanel1.ClientSize.Height / (float)universe.GetLength(1);
// A Pen for drawing the grid lines (color, width)
Pen gridPen = new Pen(gridColor, 1);
Pen tenGridPen = new Pen(tenGridColor, 2);
// A Brush for filling living cells interiors (color)
Brush cellBrush = new SolidBrush(cellColor);
Brush numberBrush = new SolidBrush(Color.Black);
Brush textBrush = new SolidBrush(Color.FromArgb(128, Color.Red));
//Font format for neighborCount
Font font = new Font("Courier New", 10);
StringFormat strFormat = new StringFormat();
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Alignment = StringAlignment.Center;
// Iterate through the universe in the y, top to bottom
for (int y = 0; y < universe.GetLength(1); y++)
{
// Iterate through the universe in the x, left to right
for (int x = 0; x < universe.GetLength(0); x++)
{
if (toroidalUniverse == true)
{
universe[x, y].liveNeighborCount = CountNeighborsToroidal(x, y, universe);
} else universe[x, y].liveNeighborCount = CountNeighborsFinite(x, y, universe);
// A rectangle to represent each cell in pixels
RectangleF cellRect = RectangleF.Empty;
cellRect.X = x * cellWidth;
cellRect.Y = y * cellHeight;
cellRect.Width = cellWidth;
cellRect.Height = cellHeight;
// Fill the cell with a brush if alive
if (universe[x, y].isOn == true)
{
e.Graphics.FillRectangle(cellBrush, cellRect);
}
// Outline the cell with a pen
if (gridOn == true)
{
e.Graphics.DrawRectangle(gridPen, cellRect.X, cellRect.Y, cellRect.Width, cellRect.Height);
}
//Pen color changes for cells to be alive next gen(green) or die/wont be alive yet(if not populated) next gen(red)
if (((universe[x, y].liveNeighborCount == 2 || universe[x, y].liveNeighborCount == 3) && universe[x, y].isOn == true) || (universe[x, y].liveNeighborCount == 3 && universe[x, y].isOn == false))
{
numberBrush = new SolidBrush(Color.Green);
}
else numberBrush = new SolidBrush(Color.Red);
if (neighborCountOn == true)
{
if (universe[x, y].liveNeighborCount > 0)
{
//Debug.WriteLine(universe[x, y].liveNeighborCount); //to make sure neighborCount is being counted properly
e.Graphics.DrawString(universe[x, y].liveNeighborCount.ToString(), font, numberBrush, cellRect, strFormat);
}
}
}
}
//Total cell count
cellsAlive = 0;
for (int y = 0; y < universe.GetLength(1); y++)
{
for (int x = 0; x < universe.GetLength(0); x++)
{
if (universe[x, y].isOn == true)
{
cellsAlive++;
}
}
}
//x10 line drawings
if (tenGridOn == true)
{
for (int i = 1; i < universe.GetLength(0); i++)
{
if (i % 10 == 0)
{
e.Graphics.DrawLine(tenGridPen, i * cellWidth, 0, i * cellWidth, graphicsPanel1.ClientSize.Height);
e.Graphics.DrawLine(tenGridPen, 0, i * cellHeight, graphicsPanel1.ClientSize.Width, i * cellHeight);
}
}
}
//HUD drawing
if (HUDon == true)
{
Font hudFont = new Font("Courier", 20);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Far;
string hud = "Generation = " + generations + "\nInterval = " + timeInt + " ms/generation\nCells Alive = " + cellsAlive + "\nToroidal universe = " + toroidalUniverse.ToString() + "\nUniverse Size = [" + univX + ", " + univY + "]";
e.Graphics.DrawString(hud, hudFont, textBrush, graphicsPanel1.ClientRectangle, stringFormat);
}
//toolStrip labels
toolStripStatusLabelcellsAlive.Text = "Cells Alive = " + cellsAlive.ToString();
toolStripStatusLabelTorodial.Text = "Toridial Boundary = " + toroidalUniverse.ToString();
toolStripStatusLabelSeed.Text = "Seed = " + seed.ToString();
// Cleaning up pens and brushes
gridPen.Dispose();
tenGridPen.Dispose();
cellBrush.Dispose();
numberBrush.Dispose();
textBrush.Dispose();
}
private void graphicsPanel1_MouseClick(object sender, MouseEventArgs e)
{
// If the left mouse button was clicked
if (e.Button == MouseButtons.Left)
{
// Calculate the width and height of each cell in pixels
float cellWidth = graphicsPanel1.ClientSize.Width / (float)universe.GetLength(0);
float cellHeight = graphicsPanel1.ClientSize.Height / (float)universe.GetLength(1);
// Calculate the cell that was clicked in
// CELL X = MOUSE X / CELL WIDTH
int x = (int)(e.X / cellWidth);
// CELL Y = MOUSE Y / CELL HEIGHT
int y = (int)(e.Y / cellHeight);
// Toggle the cell's state
universe[x, y].isOn = !universe[x, y].isOn;
// Tell Windows you need to repaint
graphicsPanel1.Invalidate();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void UniverseReset()
{
for (int y = 0; y < universe.GetLength(1); y++)
{
for (int x = 0; x < universe.GetLength(0); x++)
{
universe[x, y].isOn = false;
universe[x, y].liveNeighborCount = 0;
}
}
}
//++++++++++++++++++++++++++NEIGHBOR COUNT FUNCTIONS++++++++++++++++++++++++++
private int CountNeighborsToroidal(int x, int y, cell[,] focus)
{
int count = 0;
int xLen = universe.GetLength(0);
int yLen = universe.GetLength(1);
for (int yOffset = -1; yOffset <= 1; yOffset++)
{
for (int xOffset = -1; xOffset <= 1; xOffset++)
{
int xCheck = x + xOffset;
int yCheck = y + yOffset;
if (xOffset == 0 && yOffset == 0)
{
continue;
}
if (xCheck < 0)
{
xCheck = xLen - 1;
}
if (yCheck < 0)
{
yCheck = yLen - 1;
}
if (xCheck >= xLen)
{
xCheck = 0;
}
if (yCheck >= yLen)
{
yCheck = 0;
}
if (focus[xCheck, yCheck].isOn == true) count++;
}
}
return count;
}
private int CountNeighborsFinite(int x, int y, cell[,] focus)
{
int count = 0;
int xLen = universe.GetLength(0);
int yLen = universe.GetLength(1);
for (int yOffset = -1; yOffset <= 1; yOffset++)
{
for (int xOffset = -1; xOffset <= 1; xOffset++)
{
int xCheck = x + xOffset;
int yCheck = y + yOffset;
if ((xOffset == 0 && yOffset == 0) || (xCheck < 0) || (yCheck < 0) || (xCheck >= xLen) || (yCheck >= yLen))
{
continue;
}
if (focus[xCheck, yCheck].isOn == true) count++;
}
}
return count;
}
//++++++++++++++++++++++++++TOOL STRIP BUTTONS++++++++++++++++++++++++++
private void GridClear_Click(object sender, EventArgs e)
{
timer.Stop();
UniverseReset();
generations = 0;
cellsAlive = 0;
toolStripStatusLabelGenerations.Text = "Generations = " + generations.ToString();
toolStripStatusLabelcellsAlive.Text = "Cells Alive = " + cellsAlive.ToString();
toolStripStatusLabelTorodial.Text = "Toridial Boundary = " + toroidalUniverse.ToString();
toolStripStatusLabelSeed.Text = "Seed = " + seed.ToString();
graphicsPanel1.Invalidate();
}
//pause
private void Pause_Click(object sender, EventArgs e)
{
timer.Stop();
}
//play
private void Play_Click(object sender, EventArgs e)
{
timer.Start();
}
//next gen
private void NextGen_Click(object sender, EventArgs e)
{
NextGeneration();
}
private void doubleSpeedButton_Click(object sender, EventArgs e)
{
if (timeInt <= 1)
{
return;
}
timeInt /= 2;
timer.Interval = timeInt;
graphicsPanel1.Invalidate();
}
//++++++++++++++++++++++++++VIEW FUNCTIONS++++++++++++++++++++++++++
private void gridToolStripMenuItem_Click(object sender, EventArgs e)
{
gridToolStripMenuItem.Checked = !gridToolStripMenuItem.Checked;
gridOn = gridToolStripMenuItem.Checked;
graphicsPanel1.Invalidate();
}
private void neighborCountToolStripMenuItem_Click(object sender, EventArgs e)
{
neighborCountToolStripMenuItem.Checked = !neighborCountToolStripMenuItem.Checked;
neighborCountOn = neighborCountToolStripMenuItem.Checked;
graphicsPanel1.Invalidate();
}
private void hUDToolStripMenuItem_Click(object sender, EventArgs e)
{
hUDToolStripMenuItem.Checked = !hUDToolStripMenuItem.Checked;
HUDon = hUDToolStripMenuItem.Checked;
graphicsPanel1.Invalidate();
}
private void tenGridToolStripMenuItem_Click(object sender, EventArgs e)
{
tenGridToolStripMenuItem.Checked = !tenGridToolStripMenuItem.Checked;
tenGridOn = tenGridToolStripMenuItem.Checked;
graphicsPanel1.Invalidate();
}
//++++++++++++++++++++++++++RANDOMIZATION FUNCTIONS++++++++++++++++++++++++++
private void randomUniverse()
{
UniverseReset();
for (int y = 0; y < universe.GetLength(1); y++)
{
for (int x = 0; x < universe.GetLength(0); x++)
{
if (rand.Next() % 2 == 0)
{
universe[x, y].isOn = true;
}
}
}
graphicsPanel1.Invalidate();
}
private void bySeedToolStripMenuItem_Click(object sender, EventArgs e)
{
RandomSeedDialog rsd = new RandomSeedDialog(seed);
if (DialogResult.OK == rsd.ShowDialog())
{
rand = new Random(rsd.seed);
seed = rsd.seed;
randomUniverse();
}
}
private void byCurrentSeedToolStripMenuItem_Click(object sender, EventArgs e)
{
rand = new Random(seed);
randomUniverse();
}
private void byTimeToolStripMenuItem_Click(object sender, EventArgs e)
{
seed = Environment.TickCount;
rand = new Random(seed);
randomUniverse();
}
//++++++++++++++++++++++++++SETTINGS FUNCTIONS++++++++++++++++++++++++++
private void backgroundColorToolStripMenuItem_Click_1(object sender, EventArgs e)
{
BackgroundColor();
}
private void cellColorToolStripMenuItem1_Click_1(object sender, EventArgs e)
{
CellColor();
}
private void gridColorToolStripMenuItem_Click_1(object sender, EventArgs e)
{
GridColor();
}
//Context Menu Selections
private void backgroundColorToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackgroundColor();
}
private void cellColorToolStripMenuItem_Click(object sender, EventArgs e)
{
CellColor();
}
private void gridColorToolStripMenuItem1_Click(object sender, EventArgs e)
{
GridColor();
}
//Color Functions
private void BackgroundColor()
{
ColorDialog cd = new ColorDialog();
cd.Color = graphicsPanel1.BackColor;
if (DialogResult.OK == cd.ShowDialog())
{
backgroundColor = cd.Color;
graphicsPanel1.BackColor = backgroundColor;
}
}
private void CellColor()
{
ColorDialog cd = new ColorDialog();
cd.Color = cellColor;
cd.CustomColors = new int[] { ColorTranslator.ToOle(cellColor) };
if (DialogResult.OK == cd.ShowDialog())
{
cellColor = cd.Color;
}
graphicsPanel1.Invalidate();
}
private void GridColor()
{
ColorDialog cd = new ColorDialog();
cd.Color = gridColor;
if (DialogResult.OK == cd.ShowDialog())
{
gridColor = cd.Color;
}
graphicsPanel1.Invalidate();
}
private void tenGridColorToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
cd.Color = tenGridColor;
if (DialogResult.OK == cd.ShowDialog())
{
tenGridColor = cd.Color;
}
graphicsPanel1.Invalidate();
}
private void resetToolStripMenuItem_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reset();
seed = Properties.Settings.Default.seed;
gridColor = Properties.Settings.Default.gridColor;
tenGridColor = Properties.Settings.Default.tenGridColor;
cellColor = Properties.Settings.Default.cellColor;
backgroundColor = Properties.Settings.Default.backgroundColor;
univX = Properties.Settings.Default.universeX;
univY = Properties.Settings.Default.universeY;
universe = new cell[univX, univY];
scratchPad = new cell[univX, univY];
graphicsPanel1.BackColor = backgroundColor;
timeInt = Properties.Settings.Default.timerInterval; // milliseconds
graphicsPanel1.Invalidate();
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reload();
seed = Properties.Settings.Default.seed;
gridColor = Properties.Settings.Default.gridColor;
tenGridColor = Properties.Settings.Default.tenGridColor;
cellColor = Properties.Settings.Default.cellColor;
backgroundColor = Properties.Settings.Default.backgroundColor;
univX = Properties.Settings.Default.universeX;
univY = Properties.Settings.Default.universeY;
universe = new cell[univX, univY];
scratchPad = new cell[univX, univY];
graphicsPanel1.BackColor = backgroundColor;
timeInt = Properties.Settings.Default.timerInterval; // milliseconds
graphicsPanel1.Invalidate();
}
//Options menu
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
int xAxis = universe.GetLength(0);
int yAxis = universe.GetLength(1);
OptionsDialog od = new OptionsDialog(toroidalUniverse, timeInt, universe.GetLength(0), universe.GetLength(1));
if (DialogResult.OK == od.ShowDialog())
{
if (xAxis != od.xAxis || yAxis != od.yAxis)
{
univX = od.xAxis;
univY = od.yAxis;
universe = new cell[univX, univY];
scratchPad = new cell[univX, univY];
}
timeInt = od.interval;
timer.Interval = timeInt;
toroidalUniverse = od.toroidal;
}
graphicsPanel1.Invalidate();
}
//++++++++++++++++++++++++++OPEN/SAVE FUNCTIONS++++++++++++++++++++++++++
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All Files|*.*|Cells|*.cells";
dlg.FilterIndex = 2;
if (DialogResult.OK == dlg.ShowDialog())
{
StreamReader reader = new StreamReader(dlg.FileName);
// Create a couple variables to calculate the width and height
// of the data in the file.
int maxWidth = 0;
int maxHeight = 0;
int y = 0;
// Iterate through the file once to get its size.
while (!reader.EndOfStream)
{
// Read one row at a time.
string row = reader.ReadLine();
// If the row begins with '!' then it is a comment
// and should be ignored.
if (row[0] == '!')
{
continue;
}
// If the row is not a comment then it is a row of cells.
// Increment the maxHeight variable for each row read.
// Get the length of the current row string
// and adjust the maxWidth variable if necessary.
else
{
maxHeight++;
maxWidth = row.Length;
}
}
// Resize the current universe and scratchPad
// to the width and height of the file calculated above.
universe = new cell[maxWidth, maxHeight];
// Reset the file pointer back to the beginning of the file.
reader.BaseStream.Seek(0, SeekOrigin.Begin);
// Iterate through the file again, this time reading in the cells.
while (!reader.EndOfStream)
{
// Read one row at a time.
string row = reader.ReadLine();
// If the row begins with '!' then
// it is a comment and should be ignored.
if (row[0] == '!')
{
continue;
}
else
{
// If the row is not a comment then
// it is a row of cells and needs to be iterated through.
for (int xPos = 0; xPos < row.Length; xPos++)
{
// If row[xPos] is a 'O' (capital O) then cell == alive
// If row[xPos] is a '.' (period) then cell == dead
if (row[xPos] == 'O')
{
universe[xPos, y].isOn = true;
}
else if (row[xPos] == '.')
{
universe[xPos, y].isOn = false;
}
}
y++;
}
}
// Close the file.
reader.Close();
graphicsPanel1.Invalidate();
}
}
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All Files|*.*|Cells|*.cells";
dlg.FilterIndex = 2;
if (DialogResult.OK == dlg.ShowDialog())
{
StreamReader reader = new StreamReader(dlg.FileName);
// Create a couple variables to calculate the width and height
// of the data in the file.
int y = 0;
// Reset the file pointer back to the beginning of the file.
reader.BaseStream.Seek(0, SeekOrigin.Begin);
// Iterate through the file again, this time reading in the cells.
while (y < universe.GetLength(1))
{
// Read one row at a time.
string row = reader.ReadLine();
// If the row begins with '!' then
// it is a comment and should be ignored.
if (row[0] == '!')
{
continue;
}
else
{
// If the row is not a comment then
// it is a row of cells and needs to be iterated through.
for (int xPos = 0; xPos < universe.GetLength(0); xPos++)
{
// If row[xPos] is a 'O' (capital O) then cell == alive
// If row[xPos] is a '.' (period) then cell == dead
if (row[xPos] == 'O')
{
universe[xPos, y].isOn = true;
}
else if (row[xPos] == '.')
{
universe[xPos, y].isOn = false;
}
}
y++;
}
}
// Close the file.
reader.Close();
graphicsPanel1.Invalidate();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "All Files|*.*|Cells|*.cells";
dlg.FilterIndex = 2; dlg.DefaultExt = "cells";
if (DialogResult.OK == dlg.ShowDialog())
{
StreamWriter writer = new StreamWriter(dlg.FileName);
// Write any comments you want to include first.
// Prefix all comment strings with an exclamation point.
// Use WriteLine to write the strings to the file.
writer.WriteLine("!This is my comment.");
// Iterate through the universe one row at a time.
for (int y = 0; y < universe.GetLength(1); y++)
{
// Create a string to represent the current row.
String currentRow = string.Empty;
// Iterate through the current row one cell at a time.
for (int x = 0; x < universe.GetLength(0); x++)
{
// If the universe[x,y] is alive then append 'O' (capital O)
// Else if the universe[x,y] is dead then append '.' (period)
if (universe[x, y].isOn == true)
{
currentRow += 'O';
}
else if (universe[x, y].isOn == false)
{
currentRow += '.';
}
}
// Once the current row has been read through and the
// string constructed then write it to the file using WriteLine.
writer.WriteLine(currentRow);
}
// After all rows and columns have been written then close the file.
writer.Close();
}
graphicsPanel1.Invalidate();
}
//Closing function, updates all settings
private void GOLForm_FormClosed(object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.timerInterval = timeInt;
Properties.Settings.Default.seed = seed;
Properties.Settings.Default.gridColor = gridColor;
Properties.Settings.Default.tenGridColor = tenGridColor;
Properties.Settings.Default.cellColor = cellColor;
Properties.Settings.Default.backgroundColor = backgroundColor;
Properties.Settings.Default.universeX = univX;
Properties.Settings.Default.universeY = univY;
Properties.Settings.Default.Save();
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseQueryOverTest.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Queries;
using FluentAssertions;
using NUnit.Framework;
namespace CGI.Reflex.Core.Tests.Queries
{
public class BaseQueryOverTest : BaseDbTest
{
[Test]
[TestCase(250, 10)]
[TestCase(51, 25)]
public void It_should_paginate(int numberOfElements, int pageSize)
{
for (var i = 0; i < numberOfElements; i++)
Factories.DomainValue.Save();
var expectedNumberofPages = (numberOfElements / pageSize) + (numberOfElements % pageSize == 0 ? 0 : 1);
for (var i = 1; i <= expectedNumberofPages; i++)
{
var paginationResult = new DomainValueQuery().Paginate(i, pageSize);
paginationResult.CurrentPage.Should().Be(i);
paginationResult.HasNextPage.Should().Be(i != expectedNumberofPages);
paginationResult.HasPreviousPage.Should().Be(i != 1);
paginationResult.IsFirstPage.Should().Be(i == 1);
paginationResult.IsLastPage.Should().Be(i == expectedNumberofPages);
paginationResult.Items.Count().Should().Be(i == expectedNumberofPages ? numberOfElements - (pageSize * (i - 1)) : pageSize);
paginationResult.PageSize.Should().Be(pageSize);
paginationResult.PageCount.Should().Be(expectedNumberofPages);
paginationResult.TotalItems.Should().Be(numberOfElements);
}
}
[Test]
public void It_should_List()
{
for (var i = 0; i < 50; i++)
Factories.DomainValue.Save();
new DomainValueQuery().List().Count().Should().Be(50);
}
[Test]
public void It_should_Count()
{
for (var i = 0; i < 50; i++)
Factories.DomainValue.Save();
new DomainValueQuery().Count().Should().Be(50);
}
[Test]
public void It_should_SingleOrDefault()
{
var dv = Factories.DomainValue.Save();
new DomainValueQuery().SingleOrDefault().Should().Be(dv);
}
}
}
|
using System;
using CRUDelicious.Models;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace CRUDelicious.Controllers
{
public class CRUDController : Controller
{
private CRUDContext db;
// here we can "inject" our context service into the constructor
public CRUDController(CRUDContext context)
{
db = context;
}
[HttpGet("")]
public IActionResult Welcome()
{
List<Dish> allDishes = db.Dishes.ToList();
return View("Welcome",allDishes);
}
[HttpGet("/new")]
public IActionResult New()
{
return View();
}
[HttpPost("/create")]
public IActionResult Create(Dish newDish)
{
Console.WriteLine("\n" + newDish.Tastiness +"\n");
// string to int ""
if(ModelState.IsValid == false)
{
return View("New");
}
db.Dishes.Add(newDish);
db.SaveChanges();
return RedirectToAction("Details",new {id = newDish.DishId});
}
[HttpGet("/{id}")]
public IActionResult Details(int id)
{
Dish selectedDish = db.Dishes.FirstOrDefault(dish => dish.DishId == id);
if (selectedDish == null)
{
return RedirectToAction("Welcome");
}
return View("Details", selectedDish);
}
[HttpGet("/edit/{id}")]
public IActionResult Edit(int id)
{
Dish selectedDish = db.Dishes.FirstOrDefault(dish => dish.DishId == id);
if (selectedDish == null)
{
return RedirectToAction("Details",selectedDish.DishId);
}
return View("Edit",selectedDish);
}
[HttpPost("/edit/{id}/update")]
public IActionResult Update(Dish editedDish, int id)
{
if(ModelState.IsValid == false)
{
editedDish.DishId = id;
return View("Edit",editedDish);
}
Dish selectedDish = db.Dishes.FirstOrDefault(dish => dish.DishId == id);
if (selectedDish == null)
{
return RedirectToAction("Welcome");
}
selectedDish.Name = editedDish.Name;
selectedDish.Chef = editedDish.Chef;
selectedDish.Calories = editedDish.Calories;
selectedDish.Tastiness = editedDish.Tastiness;
selectedDish.Description = editedDish.Description;
selectedDish.UpdatedAt = DateTime.Now;
db.Dishes.Update(selectedDish);
db.SaveChanges();
return RedirectToAction("Details",new {id = selectedDish.DishId});
}
[HttpGet("/{id}/delete")]
public IActionResult Delete(int id)
{
Dish selectedDish = db.Dishes.FirstOrDefault(dish => dish.DishId == id);
if (selectedDish != null)
{
db.Dishes.Remove(selectedDish);
db.SaveChanges();
}
return RedirectToAction("Welcome");
}
}
} |
using System;
using System.Threading.Tasks;
using akka_microservices_proj.Commands;
using akka_microservices_proj.Domain;
using akka_microservices_proj.Messages;
using akka_microservices_proj.Requests;
using Microsoft.AspNetCore.Mvc;
namespace akka_microservices_proj.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class BasketController : Controller
{
private readonly Lazy<IGetBasketFromCustomerCommand> _getBasketFromCustomerCommand;
private readonly Lazy<IAddProductToBasketCommand> _addProductToBasketCommand;
private readonly Lazy<IRemoveProductFromBasketCommand> _removeProductFromBasketCommand;
public BasketController(Lazy<IGetBasketFromCustomerCommand> getBasketFromCustomerCommand,
Lazy<IAddProductToBasketCommand> addProductToBasketCommand,
Lazy<IRemoveProductFromBasketCommand> removeProductFromBasketCommand)
{
_getBasketFromCustomerCommand = getBasketFromCustomerCommand;
_addProductToBasketCommand = addProductToBasketCommand;
_removeProductFromBasketCommand = removeProductFromBasketCommand;
}
/// <summary>
/// Get the basket from customer
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
[HttpGet("{customerId}")]
public async Task<IActionResult> Get(long customerId) => await _getBasketFromCustomerCommand.Value.ExecuteAsync(new GetBasketMessage(customerId));
/// <summary>
/// Place product in the basket.
/// </summary>
/// <param name="customerId"></param>
/// <param name="product"></param>
/// <returns></returns>
[HttpPut("addproduct")]
public async Task<IActionResult> Put([FromBody] AddProductToBasketRequest request) =>
await _addProductToBasketCommand.Value.ExecuteAsync(new AddProductToBasketMessage(request.CustomerId) { Product = request.Product });
/// <summary>
/// Remove product from the basket.
/// </summary>
/// <param name="customerId"></param>
/// <param name="product"></param>
/// <returns></returns>
[HttpDelete("removeproduct")]
public async Task<IActionResult> Delete([FromBody] RemoveProductFromBasketRequest request) =>
await _removeProductFromBasketCommand.Value.ExecuteAsync(new RemoveProductFromBasketMessage(request.CustomerId) { Product = request.Product });
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Whale.Shared.Models.Contact;
using Whale.Shared.Services;
namespace Whale.API.Controllers
{
[Route("[controller]")]
[ApiController]
[Authorize]
public class ContactsController : ControllerBase
{
private readonly ContactsService _contactsService;
public ContactsController(ContactsService contactsService)
{
_contactsService = contactsService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<ContactDTO>>> GetAll()
{
var email = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var contacts = await _contactsService.GetAllContactsAsync(email);
if (contacts == null) return NotFound();
return Ok(contacts);
}
[HttpGet("accepted")]
public async Task<ActionResult<IEnumerable<ContactDTO>>> GetAccepted()
{
var email = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
Console.WriteLine("email");
Console.WriteLine(email);
var contacts = await _contactsService.GetAcceptedContactsAsync(email);
if (contacts == null)
return NotFound();
return Ok(contacts);
}
[HttpGet("id/{contactId}")]
public async Task<ActionResult<ContactDTO>> Get(Guid contactId)
{
var email = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var contact = await _contactsService.GetContactAsync(contactId, email);
if (contact == null) return NotFound();
return Ok(contact);
}
[HttpPost("create")]
public async Task<ActionResult<ContactDTO>> CreateFromEmail([FromQuery(Name = "email")] string contactnerEmail)
{
var ownerEmail = HttpContext?.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var createdContact = await _contactsService.CreateContactFromEmailAsync(ownerEmail, contactnerEmail);
return Created($"id/{createdContact.Id}", createdContact);
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(Guid id)
{
var email = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var deleted = await _contactsService.DeleteContactAsync(id, email);
if (deleted) return NoContent();
return NotFound();
}
[HttpDelete("email/{contactEmail}")]
public async Task<IActionResult> DeletePendingContactByEmail(string contactEmail)
{
var userEmail = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var deleted = await _contactsService.DeletePendingContactByEmailAsync(contactEmail, userEmail);
if (deleted) return NoContent();
return NotFound();
}
[HttpPut]
public async Task<ActionResult<ContactDTO>> Update([FromBody] ContactEditDTO contactDTO)
{
var email = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
return Ok (await _contactsService.UpdateContactAsync(contactDTO, email));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DragonBones;
public class MecaAnimLoader : MonoBehaviour {
[HideInInspector]
public UnityArmatureComponent armatureComponent;
public float size = 6;
// Use this for initialization
void Start () {
// Load data.
UnityFactory.factory.LoadDragonBonesData("PirateShip/ggj_robot"); // DragonBones file path (without suffix)
UnityFactory.factory.LoadTextureAtlasData("PirateShip/texture"); //Texture atlas file path (without suffix)
// Create armature.
armatureComponent = UnityFactory.factory.BuildArmatureComponent("Armature"); // Input armature name
// Play animation.
// armatureComponent.animation.Play("walk");
// Change armatureposition.
armatureComponent.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
armatureComponent.transform.parent = transform;
//armatureComponent.slo
armatureComponent.transform.localScale = new Vector3(armatureComponent.transform.localScale.x * size,
armatureComponent.transform.localScale.y * size,
armatureComponent.transform.localScale.z * size);
}
// Update is called once per frame
void Update () {
}
}
|
namespace MKService.Updates
{
/// <summary>
/// Represents a type that is updatable via a model updater. Simply a marker interface at this point.
/// </summary>
public interface IUpdatable
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogicHandler
{
class ReportHandler
{
}
}
|
using System;
using System.Net.Mime;
using LubyClocker.CrossCuting.Shared.Exceptions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
namespace LubyClocker.Api.Middlewares
{
public static class ExceptionHandlerMiddlewareExtension
{
public static IApplicationBuilder UseExceptionHandlerMiddleware(this IApplicationBuilder app)
{
return app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
context.Response.StatusCode = contextFeature.Error is InvalidRequestException ? StatusCodes.Status400BadRequest : StatusCodes.Status500InternalServerError;
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(
JsonConvert.SerializeObject(new
{
error = contextFeature.Error.Message
})
);
});
});
}
}
}
|
using System;
using JobsityChatroom.WebAPI.Models.Command;
using JobsityChatroom.WebAPI.Services;
using Xunit;
namespace JobsityChatroom.UnitTest
{
public class ChatCommandTest
{
private readonly IChatCommandService commandService;
public ChatCommandTest()
{
commandService = new ChatCommandService();
}
[Fact]
public void ValidCommand()
{
var result = commandService.IsCommand("/stock=aapl.us");
Assert.True(result);
}
[Fact]
public void NotACommand()
{
var result = commandService.IsCommand("stock=aapl.us");
Assert.False(result);
}
[Fact]
public void CommandExecutes_NoExceptions()
{
void call() => commandService.Handle("/stock=aapl.us", _ => { });
var exception = Record.Exception(call);
Assert.Null(exception);
}
[Fact]
public void InvalidSyntax()
{
void call() => commandService.Handle("/stock/stock", _ => { });
var exception = Record.Exception(call);
Assert.NotNull(exception);
Assert.IsType<CommandException>(exception);
Assert.Equal("Invalid command syntax", exception.Message);
}
[Fact]
public void UnknownCommand()
{
void call() => commandService.Handle("/stocc=aapl.us", _ => { });
var exception = Record.Exception(call);
Assert.NotNull(exception);
Assert.IsType<CommandException>(exception);
Assert.Equal("Unknown command", exception.Message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LabsFerreiraCosta.Controllers{
/* File History
* --------------------------------------------------------------------
* Created by : Luciano Filho
* Date : 15/02/2021
* Purpose : Criação da Controller do Usuário
* --------------------------------------------------------------------
*/
public class RelatorioController : Controller
{
// GET: Relatorio
public ActionResult Index()
{
return View("~/Views/Relatorio/Relatorio.cshtml");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace EasyVideoEdition.Model
{
/// <summary>
/// Unique subtitle
/// </summary>
class Subtitle : ObjectBase
{
#region Attributes
private String _startTime;
private String _endTime;
private String _subtitleText;
private static readonly Regex TIME_FORMAT = new Regex(@"^\d{2}:\d{2}:\d{2},\d{3}$"); //Format of a time (hh:mm:ss,msmsms)
#endregion
#region Get/Set
/// <summary>
/// Time when the subtile starts (hh:mm:ss,msmsms)
/// </summary>
public String startTime
{
get
{
return _startTime;
}
set
{
_startTime = value;
RaisePropertyChanged("startTime");
}
}
/// <summary>
/// Time when the subtile ends (hh:mm:ss,msmsms)
/// </summary>
public String endTime
{
get
{
return _endTime;
}
set
{
_endTime = value;
RaisePropertyChanged("endTime");
}
}
/// <summary>
/// Content text of the subtitle
/// </summary>
public String subtitleText
{
get
{
return _subtitleText;
}
set
{
_subtitleText = value;
RaisePropertyChanged("subtitleText");
}
}
#endregion
/// <summary>
/// Creates a subtitle
/// </summary>
public Subtitle() { }
/// <summary>
/// Creates a subtitle with properties
/// </summary>
/// <param name="startTime">Time when the subtitle will start</param>
/// <param name="endTime">Time when the subtitle will end</param>
/// <param name="text">Text that the subtitle will contain</param>
public Subtitle(String startTime, String endTime, String text)
{
this.startTime = startTime;
this.endTime = endTime;
this.subtitleText = text;
}
/// <summary>
/// Edits the subtitle
/// </summary>
/// <param name="startTime">Time when the subtitle will start</param>
/// <param name="endTime">Time when the subtitle will end</param>
/// <param name="text">Text that the subtitle will contain</param>
public void EditSubtile(String startTime, String endTime, String text)
{
/* Check if the format of the strings are good */
if (TIME_FORMAT.IsMatch(startTime))
this.startTime = startTime;
if (TIME_FORMAT.IsMatch(endTime))
this.endTime = endTime;
this.subtitleText = text;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.