text stringlengths 13 6.01M |
|---|
using RabbitMQ.Client;
using System;
using System.Text;
namespace Accenture.DataSaver.Processors
{
public class PublishMessage
{
public PublishMessage()
{
}
public void Publish(string message, ConnectionFactory _factory, string exchange = "configuration", IBasicProperties properties = null)
{
PublishSingleMessage(message, _factory, exchange, properties);
}
private void PublishSingleMessage(string message, ConnectionFactory _factory, string exchange, IBasicProperties properties)
{
using (var connection = _factory.CreateConnection())
using (var channel = connection.CreateModel())
{
var props = properties ?? channel.CreateBasicProperties();
var queueName = channel.QueueDeclare().QueueName;
channel.ConfirmSelect();
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: exchange, routingKey: "configuration.train", basicProperties: props, body: body);
channel.WaitForConfirmsOrDie(new TimeSpan(0, 0, 5));
}
}
}
}
|
using System;
using System.Linq;
using Uintra.Features.CentralFeed.Enums;
using Uintra.Infrastructure.Grid;
using Umbraco.Core.Models.PublishedContent;
namespace Uintra.Core.Feed.Services
{
public abstract class FeedContentServiceBase : IFeedContentService
{
private readonly IFeedTypeProvider _feedTypeProvider;
private readonly IGridHelper _gridHelper;
protected FeedContentServiceBase(IFeedTypeProvider feedTypeProvider, IGridHelper gridHelper)
{
_feedTypeProvider = feedTypeProvider;
_gridHelper = gridHelper;
}
protected abstract string FeedPluginAlias { get; }
protected abstract string ActivityCreatePluginAlias { get; }
public virtual Enum GetFeedTabType(IPublishedContent content) =>
GetCentralFeedTypeFromPlugin(content, FeedPluginAlias);
public virtual Enum GetCreateActivityType(IPublishedContent content) =>
GetCentralFeedTypeFromPlugin(content, ActivityCreatePluginAlias);
protected virtual Enum GetCentralFeedTypeFromPlugin(IPublishedContent content, string gridPluginAlias)
{
var value = _gridHelper
.GetValues(content, gridPluginAlias)
.FirstOrDefault(t => t.value != null)
.value;
if (value == null) return default(CentralFeedTypeEnum);
var tabType = int.TryParse(value.tabType.ToString(), out int result)
? _feedTypeProvider[result]
: default(CentralFeedTypeEnum);
return tabType;
}
}
}
|
using DamianTourBackend.Application.Helpers;
using DamianTourBackend.Core.Entities;
namespace DamianTourBackend.Application.Register
{
public static class RegisterMapper
{
public static User MapToUser(this RegisterDTO model) =>
new User
{
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
PhoneNumber = model.PhoneNumber,
DateOfBirth = DateParser.Parse(model.DateOfBirth)
};
public static AppUser MapToAppUser(this RegisterDTO model) =>
new AppUser()
{
UserName = model.Email,
Email = model.Email
};
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using System.Data;
using System.Configuration;
using System.Data.Common;
using System.IO;
using System.Web;
using System.Drawing;
using System.Security.Cryptography;
namespace generalClassLibrary
{
public class hdbmsClass
{
private DbCommand cmdinsertSubscriber_tbl;
private DbCommand cmdinsertStaff_reg_tbl;
public Decimal GenerateTransID(ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdGenSeq = db.GetStoredProcCommand("GenerateSqlSequenceNo2");
try
{
ds = db.ExecuteDataSet(cmdGenSeq);
msg = "";
UpdateTransID(ref msg);
decimal pos = Convert.ToDecimal(ds.Tables[0].Rows[0]["SEQ_NO"].ToString());
return (pos);
}
catch (Exception ex)
{
msg = ex.Message;
return -1;
}
}
private void UpdateTransID(ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdGenSeq = db.GetStoredProcCommand("GenerateSqlSequenceNo");
try
{
ds = db.ExecuteDataSet(cmdGenSeq);
msg = "";
}
catch (Exception ex)
{
//msg = ex.Message;
//return msg;
}
}
#region HDBMS 09/2018
public void insertSubscriber_tbl(decimal subscriberID, string subscriberName, string description, decimal amount, decimal paid, decimal balance, DateTime subscriptionDate, DateTime expiryDate, string subscriberAddress, string subscriberPhoneNo, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertSubscriber_tbl = db.GetStoredProcCommand("insertSubscriber_tbl");
db.AddInParameter(cmdinsertSubscriber_tbl, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
db.AddInParameter(cmdinsertSubscriber_tbl, "SUBCRIBER_NAME", DbType.String, subscriberName);
db.AddInParameter(cmdinsertSubscriber_tbl, "DESCRIPTION", DbType.String, description);
db.AddInParameter(cmdinsertSubscriber_tbl, "AMOUNT", DbType.Currency, amount);
db.AddInParameter(cmdinsertSubscriber_tbl, "PAID", DbType.Currency, paid);
db.AddInParameter(cmdinsertSubscriber_tbl, "BALANCE", DbType.Currency, balance);
db.AddInParameter(cmdinsertSubscriber_tbl, "SUBCRIPTION_DATE", DbType.Date, subscriptionDate);
db.AddInParameter(cmdinsertSubscriber_tbl, "EXPIRY_DATE", DbType.Date, expiryDate);
db.AddInParameter(cmdinsertSubscriber_tbl, "SUBSCRIBER_ADDRESS", DbType.String, subscriberAddress);
db.AddInParameter(cmdinsertSubscriber_tbl, "SUBSCRIBER_PHONE_NO", DbType.String, subscriberPhoneNo);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertSubscriber_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertStaff_reg_tbl(decimal subscriberID, string subscriberName, string staffID, string staffName, string gender, DateTime dob, string nationality, string state, string lg, string address, string correspondentAddress, string mobileNumber, string emailAddress, string department, string positionLevel, DateTime registrationDate, string nextOfKin, string nokRelationship, string nokAddress, string nokMobileNumber, string highestDegreeObtained, string role, string imageUrl, string userName, string password, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertStaff_reg_tbl = db.GetStoredProcCommand("insertStaff_reg_tbl");
db.AddInParameter(cmdinsertStaff_reg_tbl, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
db.AddInParameter(cmdinsertStaff_reg_tbl, "SUBSCRIBER_NAME", DbType.String, subscriberName);
db.AddInParameter(cmdinsertStaff_reg_tbl, "STAFF_ID", DbType.String, staffID);
db.AddInParameter(cmdinsertStaff_reg_tbl, "STAFF_NAME", DbType.String, staffName);
db.AddInParameter(cmdinsertStaff_reg_tbl, "GENDER", DbType.String, gender);
db.AddInParameter(cmdinsertStaff_reg_tbl, "DOB", DbType.Date, dob);
db.AddInParameter(cmdinsertStaff_reg_tbl, "NATIONALITY", DbType.String, nationality);
db.AddInParameter(cmdinsertStaff_reg_tbl, "STATE", DbType.String, state);
db.AddInParameter(cmdinsertStaff_reg_tbl, "LG", DbType.String, lg);
db.AddInParameter(cmdinsertStaff_reg_tbl, "ADDRESS", DbType.String, address);
db.AddInParameter(cmdinsertStaff_reg_tbl, "CORRESPONDENT_ADDRESS", DbType.String, correspondentAddress);
db.AddInParameter(cmdinsertStaff_reg_tbl, "MOBILE_NUMBER", DbType.String, mobileNumber);
db.AddInParameter(cmdinsertStaff_reg_tbl, "EMAIL_ADDRESS", DbType.String, emailAddress);
db.AddInParameter(cmdinsertStaff_reg_tbl, "DEPARTMENT", DbType.String, department);
db.AddInParameter(cmdinsertStaff_reg_tbl, "POSITION_LEVEL", DbType.String, positionLevel);
db.AddInParameter(cmdinsertStaff_reg_tbl, "REGISTRATION_DATE", DbType.Date, registrationDate);
db.AddInParameter(cmdinsertStaff_reg_tbl, "NEXT_OF_KIN", DbType.String, nextOfKin);
db.AddInParameter(cmdinsertStaff_reg_tbl, "NOK_RELATIONSHIP", DbType.String, nokRelationship);
db.AddInParameter(cmdinsertStaff_reg_tbl, "NOK_ADDRESS", DbType.String, nokAddress);
db.AddInParameter(cmdinsertStaff_reg_tbl, "NOK_MOBILE_NUMBER", DbType.String, nokMobileNumber);
db.AddInParameter(cmdinsertStaff_reg_tbl, "HIGHEST_DEGREE_OBTAINED", DbType.String, highestDegreeObtained);
db.AddInParameter(cmdinsertStaff_reg_tbl, "ROLE", DbType.String, role);
db.AddInParameter(cmdinsertStaff_reg_tbl, "IMAGE_UPLOAD", DbType.String, imageUrl);
db.AddInParameter(cmdinsertStaff_reg_tbl, "USERNAME", DbType.String, userName);
db.AddInParameter(cmdinsertStaff_reg_tbl, "PWD", DbType.String, password);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertStaff_reg_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertMailRegTbl(decimal subscriberID, string subscriberName, string staffID, string staffName, string gender, string nationality, string mobileNumber, string emailAddress, string department, string userName, string password, DateTime regDate, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertMailRegTbl = db.GetStoredProcCommand("insertMailRegTbl");
db.AddInParameter(cmdinsertMailRegTbl, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
db.AddInParameter(cmdinsertMailRegTbl, "SUBSCRIBER_NAME", DbType.String, subscriberName);
db.AddInParameter(cmdinsertMailRegTbl, "STAFF_ID", DbType.String, staffID);
db.AddInParameter(cmdinsertMailRegTbl, "STAFF_NAME", DbType.String, staffName);
db.AddInParameter(cmdinsertMailRegTbl, "GENDER", DbType.String, gender);
db.AddInParameter(cmdinsertMailRegTbl, "NATIONALITY", DbType.String, nationality);
db.AddInParameter(cmdinsertMailRegTbl, "MOBILE_NUMBER", DbType.String, mobileNumber);
db.AddInParameter(cmdinsertMailRegTbl, "EMAIL_ADDRESS", DbType.String, emailAddress);
db.AddInParameter(cmdinsertMailRegTbl, "DEPARTMENT", DbType.String, department);
db.AddInParameter(cmdinsertMailRegTbl, "USERNAME", DbType.String, userName);
db.AddInParameter(cmdinsertMailRegTbl, "PWD", DbType.String, password);
db.AddInParameter(cmdinsertMailRegTbl, "REG_DATE", DbType.DateTime, regDate);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertMailRegTbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
//insertMessaging_Tbl
public void insertMessaging_Tbl(string senderID, string recieverID, string message, DateTime msgDate, string department, decimal subscriberID, string subscriberName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertMessaging_Tbl = db.GetStoredProcCommand("insertMessaging_Tbl");
db.AddInParameter(cmdinsertMessaging_Tbl, "SENDER_ID", DbType.String, senderID);
db.AddInParameter(cmdinsertMessaging_Tbl, "RECIEVER_ID", DbType.String, recieverID);
db.AddInParameter(cmdinsertMessaging_Tbl, "MESSAGE", DbType.String, message);
db.AddInParameter(cmdinsertMessaging_Tbl, "MSG_DATE", DbType.DateTime, msgDate);
db.AddInParameter(cmdinsertMessaging_Tbl, "DEPARTMENT", DbType.String, department);
db.AddInParameter(cmdinsertMessaging_Tbl, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
db.AddInParameter(cmdinsertMessaging_Tbl, "SUBSCRIBER_NAME", DbType.String, subscriberName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertMessaging_Tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertMail_reg_tbl(decimal subscriberID, string subscriberName, string staffID, string staffName, string gender, string nationality, string mobileNumber, string emailAddress, string department, string userName, string password, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertMail_reg_tbl = db.GetStoredProcCommand("insertMail_reg_tbl");
db.AddInParameter(cmdinsertMail_reg_tbl, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
db.AddInParameter(cmdinsertMail_reg_tbl, "SUBSCRIBER_NAME", DbType.String, subscriberName);
db.AddInParameter(cmdinsertMail_reg_tbl, "STAFF_ID", DbType.String, staffID);
db.AddInParameter(cmdinsertMail_reg_tbl, "STAFF_NAME", DbType.String, staffName);
db.AddInParameter(cmdinsertMail_reg_tbl, "GENDER", DbType.String, gender);
db.AddInParameter(cmdinsertMail_reg_tbl, "NATIONALITY", DbType.String, nationality);
db.AddInParameter(cmdinsertMail_reg_tbl, "MOBILE_NUMBER", DbType.String, mobileNumber);
db.AddInParameter(cmdinsertMail_reg_tbl, "EMAIL_ADDRESS", DbType.String, emailAddress);
db.AddInParameter(cmdinsertMail_reg_tbl, "DEPARTMENT", DbType.String, department);
db.AddInParameter(cmdinsertMail_reg_tbl, "USERNAME", DbType.String, userName);
db.AddInParameter(cmdinsertMail_reg_tbl, "PWD", DbType.String, password);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertMail_reg_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertPatient_reg_tbl(decimal subscriberID, string subscriberName, string patientID, string patientName, string gender, DateTime dob, string nationality, string state, string lg, string address, string mobileNumber, string emailAddress, string bloodGroup, string genotype, DateTime registrationDate, string nextOfKin, string nokRelationship, string nokAddress, string nokMobileNumber, string staffIncharge, DateTime dod, string imageUrl, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertPatient_reg_tbl = db.GetStoredProcCommand("insertPatient_reg_tbl");
db.AddInParameter(cmdinsertPatient_reg_tbl, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
db.AddInParameter(cmdinsertPatient_reg_tbl, "SUBSCRIBER_NAME", DbType.String, subscriberName);
db.AddInParameter(cmdinsertPatient_reg_tbl, "PATIENT_ID", DbType.String, patientID);
db.AddInParameter(cmdinsertPatient_reg_tbl, "PATIENT_NAME", DbType.String, patientName);
db.AddInParameter(cmdinsertPatient_reg_tbl, "GENDER", DbType.String, gender);
db.AddInParameter(cmdinsertPatient_reg_tbl, "DOB", DbType.Date, dob);
db.AddInParameter(cmdinsertPatient_reg_tbl, "NATIONALITY", DbType.String, nationality);
db.AddInParameter(cmdinsertPatient_reg_tbl, "STATE", DbType.String, state);
db.AddInParameter(cmdinsertPatient_reg_tbl, "LGA", DbType.String, lg);
db.AddInParameter(cmdinsertPatient_reg_tbl, "ADDRESS", DbType.String, address);
db.AddInParameter(cmdinsertPatient_reg_tbl, "MOBILE_NUMBER", DbType.String, mobileNumber);
db.AddInParameter(cmdinsertPatient_reg_tbl, "EMAIL_ADDRESS", DbType.String, emailAddress);
db.AddInParameter(cmdinsertPatient_reg_tbl, "BLOOD_GROUP", DbType.String, bloodGroup);
db.AddInParameter(cmdinsertPatient_reg_tbl, "GENOTYPE", DbType.String, genotype);
db.AddInParameter(cmdinsertPatient_reg_tbl, "REGISTRATION_DATE", DbType.Date, registrationDate);
db.AddInParameter(cmdinsertPatient_reg_tbl, "NEXT_OF_KIN", DbType.String, nextOfKin);
db.AddInParameter(cmdinsertPatient_reg_tbl, "NOK_RELATIONSHIP", DbType.String, nokRelationship);
db.AddInParameter(cmdinsertPatient_reg_tbl, "NOK_ADDRESS", DbType.String, nokAddress);
db.AddInParameter(cmdinsertPatient_reg_tbl, "NOK_MOBILE_NUMBER", DbType.String, nokMobileNumber);
db.AddInParameter(cmdinsertPatient_reg_tbl, "STAFF_INCHARGE", DbType.String, staffIncharge);
db.AddInParameter(cmdinsertPatient_reg_tbl, "DOD", DbType.Date, dod);
db.AddInParameter(cmdinsertPatient_reg_tbl, "IMAGE_UPLOAD", DbType.String, imageUrl);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertPatient_reg_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertVital_Signs_tbl(string patientID, string patientName, DateTime testDate, string bodyTemperature, string bodyPressure, string pulseRate, string heartRate, string respiration, string oxygenSaturation, string staffID, string hospitalName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertVital_Signs_tbl = db.GetStoredProcCommand("insertPatient_reg_tbl");
db.AddInParameter(cmdinsertVital_Signs_tbl, "PATIENT_ID", DbType.String, patientID);
db.AddInParameter(cmdinsertVital_Signs_tbl, "PATIENT_NAME", DbType.String, patientName);
db.AddInParameter(cmdinsertVital_Signs_tbl, "TEST_DATE", DbType.Date, testDate);
db.AddInParameter(cmdinsertVital_Signs_tbl, "BODY_TEMPERATURE", DbType.String, bodyTemperature);
db.AddInParameter(cmdinsertVital_Signs_tbl, "BLOOD_PRESSURE", DbType.String,bodyPressure);
db.AddInParameter(cmdinsertVital_Signs_tbl, "PULSE_RATE", DbType.String,pulseRate );
db.AddInParameter(cmdinsertVital_Signs_tbl, "HEART_RATE", DbType.String, heartRate);
db.AddInParameter(cmdinsertVital_Signs_tbl, "RESPIRATION", DbType.String, respiration);
db.AddInParameter(cmdinsertVital_Signs_tbl, "OXYGEN_SATURATION", DbType.String, oxygenSaturation);
db.AddInParameter(cmdinsertVital_Signs_tbl, "STAFF_ID", DbType.String, staffID);
db.AddInParameter(cmdinsertVital_Signs_tbl, "HOSPITAL_NAME", DbType.String, hospitalName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertVital_Signs_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertWard_round_tbl(string patientID, string patientName, DateTime testDate, string staffID,string doctorID, string hospitalName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertWard_round_tbl = db.GetStoredProcCommand("insertPatient_reg_tbl");
db.AddInParameter(cmdinsertWard_round_tbl, "PATIENT_ID", DbType.String, patientID);
db.AddInParameter(cmdinsertWard_round_tbl, "PATIENT_NAME", DbType.String, patientName);
db.AddInParameter(cmdinsertWard_round_tbl, "TEST_DATE", DbType.Date, testDate);
db.AddInParameter(cmdinsertWard_round_tbl, "STAFF_ID", DbType.String, staffID);
db.AddInParameter(cmdinsertWard_round_tbl, "DOCTOR_ID", DbType.String, doctorID);
db.AddInParameter(cmdinsertWard_round_tbl, "HOSPITAL_NAME", DbType.String, hospitalName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertWard_round_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertTreatment_Ref_Tbl(string diseases, string causingAgent, string causes, string symptoms, string treatment, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertTreatment_Ref_Tbl = db.GetStoredProcCommand("insertTreatment_Ref_Tbl");
db.AddInParameter(cmdinsertTreatment_Ref_Tbl, "DISEASES", DbType.String, diseases);
db.AddInParameter(cmdinsertTreatment_Ref_Tbl, "CAUSING_AGENT", DbType.String, causingAgent);
db.AddInParameter(cmdinsertTreatment_Ref_Tbl, "CAUSES", DbType.String, causes);
db.AddInParameter(cmdinsertTreatment_Ref_Tbl, "SYMPTOMS", DbType.String, symptoms);
db.AddInParameter(cmdinsertTreatment_Ref_Tbl, "TREATMENT", DbType.String, treatment);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertTreatment_Ref_Tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertBed_ref_tbl(string sections, string ward, string room, string bed, string status, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertBed_ref_tbl = db.GetStoredProcCommand("insertBed_ref_tbl");
db.AddInParameter(cmdinsertBed_ref_tbl, "SECTIONS", DbType.String, sections);
db.AddInParameter(cmdinsertBed_ref_tbl, "WARD", DbType.String, ward);
db.AddInParameter(cmdinsertBed_ref_tbl, "ROOM", DbType.String, room);
db.AddInParameter(cmdinsertBed_ref_tbl, "BED", DbType.String, bed);
db.AddInParameter(cmdinsertBed_ref_tbl, "STATUS", DbType.String, status);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertBed_ref_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertCategory_tbl(string categoryName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertCategory_tbl = db.GetStoredProcCommand("insertCategory_tbl");
db.AddInParameter(cmdinsertCategory_tbl, "CATEGORY_NAME", DbType.String, categoryName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertCategory_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertCategory_sub_tbl(string categoryName, string subCategoryName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertCategory_sub_tbl = db.GetStoredProcCommand("insertCategory_sub_tbl");
db.AddInParameter(cmdinsertCategory_sub_tbl, "CATEGORY_NAME", DbType.String, categoryName);
db.AddInParameter(cmdinsertCategory_sub_tbl, "SUB_CATEGORY_NAME", DbType.String, subCategoryName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertCategory_sub_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertCategory_sub_sub_tbl(string categoryName, string subCategoryName, string subSubCategoryName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertCategory_sub_sub_tbl = db.GetStoredProcCommand("insertCategory_sub_sub_tbl");
db.AddInParameter(cmdinsertCategory_sub_sub_tbl, "CATEGORY_NAME", DbType.String, categoryName);
db.AddInParameter(cmdinsertCategory_sub_sub_tbl, "SUB_CATEGORY_NAME", DbType.String, subCategoryName);
db.AddInParameter(cmdinsertCategory_sub_sub_tbl, "SUB_SUB_CATEGORY_NAME", DbType.String, subSubCategoryName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertCategory_sub_sub_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertDepartment_tbl(string deptID, string deptName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertDepartment_tbl = db.GetStoredProcCommand("insertDepartment_tbl");
db.AddInParameter(cmdinsertDepartment_tbl, "DEPT_ID", DbType.String, deptID);
db.AddInParameter(cmdinsertDepartment_tbl, "DEPT_NAME", DbType.String, deptName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertDepartment_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertPrice_list_tbl(string department, string services, string price, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertPrice_list_tbl = db.GetStoredProcCommand("insertPrice_list_tbl");
db.AddInParameter(cmdinsertPrice_list_tbl, "DEPARTMENT", DbType.String, department);
db.AddInParameter(cmdinsertPrice_list_tbl, "SERVICES", DbType.String, services);
db.AddInParameter(cmdinsertPrice_list_tbl, "PRICE", DbType.String, price);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertPrice_list_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void insertDoctor_report_tbl(string patientID, DateTime consultationDate, string diagnosis, string investigations, string prescriptions, string remark, string advice, string doctorID, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdinsertDoctor_report_tbl = db.GetStoredProcCommand("insertDoctor_report_tbl");
db.AddInParameter(cmdinsertDoctor_report_tbl, "PATIENT_ID", DbType.String, patientID);
db.AddInParameter(cmdinsertDoctor_report_tbl, "CONSULTATION_DATE", DbType.Date, consultationDate);
db.AddInParameter(cmdinsertDoctor_report_tbl, "DIAGNOSIS", DbType.String, diagnosis);
db.AddInParameter(cmdinsertDoctor_report_tbl, "INVESTIGATIONS", DbType.String, investigations);
db.AddInParameter(cmdinsertDoctor_report_tbl, "PRESCRIPTIONS", DbType.String, prescriptions);
db.AddInParameter(cmdinsertDoctor_report_tbl, "REMARK", DbType.String, remark);
db.AddInParameter(cmdinsertDoctor_report_tbl, "ADVICE", DbType.String, advice);
db.AddInParameter(cmdinsertDoctor_report_tbl, "DOCTOR_ID", DbType.String, doctorID);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdinsertDoctor_report_tbl, trans);
trans.Commit(); // commit the transaction
}
catch (Exception ex)
{
trans.Rollback(); // rollback the transaction
conn.Close();
msg = ex.Message;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void UpdateCountry(string countryCode, string countryName, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdUpdateCountry = db.GetStoredProcCommand("spUpdateCountry");
db.AddInParameter(cmdUpdateCountry, "COUNTRY_CODE", DbType.String, countryCode);
db.AddInParameter(cmdUpdateCountry, "COUNTRY_NAME", DbType.String, countryName);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdUpdateCountry, trans);
trans.Commit(); // commit the transaction
}
catch
{
trans.Rollback(); // rollback the transaction
conn.Close();
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public void DeleteCountry(string countryCode, ref string msg)
{
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdDeletecountry = db.GetStoredProcCommand("spDeleteCountry");
db.AddInParameter(cmdDeletecountry, "COUNTRY_CODE", DbType.String, countryCode);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// execute commands, passing in the current transaction to each one
db.ExecuteNonQuery(cmdDeletecountry, trans);
trans.Commit(); // commit the transaction
}
catch
{
trans.Rollback(); // rollback the transaction
conn.Close();
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
}
}
}
public DataSet CheckCountryExit(string countryName, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdcountry = db.GetStoredProcCommand("spCheckCountryExist");
db.AddInParameter(cmdcountry, "COUNTRY_NAME", DbType.String, countryName);
try
{
ds = db.ExecuteDataSet(cmdcountry);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchSubscriberBySN_subID(int sn,decimal subscriberID,ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchSubscriberBySN_subID = db.GetStoredProcCommand("fetchSubscriberBySN_subID");
db.AddInParameter(cmdfetchSubscriberBySN_subID, "SN", DbType.Int32, sn);
db.AddInParameter(cmdfetchSubscriberBySN_subID, "SUBSCRIBER_ID", DbType.Decimal, subscriberID);
try
{
ds = db.ExecuteDataSet(cmdfetchSubscriberBySN_subID);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchMailRegByUserPwd(string username, string pwd, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchMailRegByUserPwd = db.GetStoredProcCommand("fetchMailRegByUserPwd");
db.AddInParameter(cmdfetchMailRegByUserPwd, "USERNAME", DbType.String, username);
db.AddInParameter(cmdfetchMailRegByUserPwd, "PWD", DbType.String, pwd);
try
{
ds = db.ExecuteDataSet(cmdfetchMailRegByUserPwd);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchStaffByUsername_Password(string userName, string Password, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchStaffByUsername_Password = db.GetStoredProcCommand("fetchStaffByUsername_Password");
db.AddInParameter(cmdfetchStaffByUsername_Password, "USERNAME", DbType.String, userName);
db.AddInParameter(cmdfetchStaffByUsername_Password, "PWD", DbType.String, Password);
try
{
ds = db.ExecuteDataSet(cmdfetchStaffByUsername_Password);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchPatientByPatientID(string thepatientID, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchPatientByPatientID = db.GetStoredProcCommand("fetchStaffByUsername_Password");
db.AddInParameter(cmdfetchPatientByPatientID, "PATIENT_ID", DbType.String, thepatientID);
try
{
ds = db.ExecuteDataSet(cmdfetchPatientByPatientID);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchSymptomsByDisease(string diseases, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchSymptomsByDisease = db.GetStoredProcCommand("fetchSymptomsByDisease");
db.AddInParameter(cmdfetchSymptomsByDisease, "DISEASES", DbType.String, diseases);
try
{
ds = db.ExecuteDataSet(cmdfetchSymptomsByDisease);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchCategorySubByCategory(string categoryName, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchCategorySubByCategory = db.GetStoredProcCommand("fetchCategorySubByCategory");
db.AddInParameter(cmdfetchCategorySubByCategory, "CATEGORY_NAME", DbType.String, categoryName);
try
{
ds = db.ExecuteDataSet(cmdfetchCategorySubByCategory);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
public DataSet fetchPatientByID(string patientID, ref string msg)
{
DataSet ds = new DataSet();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
DbCommand cmdfetchPatientByID = db.GetStoredProcCommand("fetchPatientByID");
db.AddInParameter(cmdfetchPatientByID, "PATIENT_ID", DbType.String, patientID);
try
{
ds = db.ExecuteDataSet(cmdfetchPatientByID);
msg = "";
}
catch (Exception ex)
{
msg = ex.Message;
return ds;
}
return (ds);
}
#endregion
public class RandomPassword
{
// Define default min and max password lengths.
private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
// Define supported password characters divided into groups.
// You can add (or remove) characters to (from) these groups.
private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
private static string PASSWORD_CHARS_NUMERIC = "23456789";
private static string PASSWORD_CHARS_SPECIAL = "*$-+?_&=!%{}/";
/// <summary>
/// Generates a random password.
/// </summary>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random. It will be no shorter than the minimum default and
/// no longer than maximum default.
/// </remarks>
public static string Generate()
{
return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
DEFAULT_MAX_PASSWORD_LENGTH);
}
/// <summary>
/// Generates a random password of the exact length.
/// </summary>
/// <param name="length">
/// Exact password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
public static string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password.
/// </summary>
/// <param name="minLength">
/// Minimum password length.
/// </param>
/// <param name="maxLength">
/// Maximum password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random and it will fall with the range determined by the
/// function parameters.
/// </remarks>
public static string Generate(int minLength, int maxLength)
{
// Make sure that input parameters are valid.
if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
return null;
// Create a local array containing supported password characters
// grouped by types. You can remove character groups from this
// array, but doing so will weaken the password strength.
char[][] charGroups = new char[][]
{
PASSWORD_CHARS_LCASE.ToCharArray(),
PASSWORD_CHARS_UCASE.ToCharArray(),
PASSWORD_CHARS_NUMERIC.ToCharArray(),
PASSWORD_CHARS_SPECIAL.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
int[] charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (int i = 0; i < charsLeftInGroup.Length; i++)
charsLeftInGroup[i] = charGroups[i].Length;
// Use this array to track (iterate through) unused character groups.
int[] leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (int i = 0; i < leftGroupsOrder.Length; i++)
leftGroupsOrder[i] = i;
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
byte[] randomBytes = new byte[4];
// Generate 4 random bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = (randomBytes[0] & 0x7f) << 24 |
randomBytes[1] << 16 |
randomBytes[2] << 8 |
randomBytes[3];
// Now, this is real randomization.
Random random = new Random(seed);
// This array will hold password characters.
char[] password = null;
// Allocate appropriate memory for the password.
if (minLength < maxLength)
password = new char[random.Next(minLength, maxLength + 1)];
else
password = new char[minLength];
// Index of the next character to be added to password.
int nextCharIdx;
// Index of the next character group to be processed.
int nextGroupIdx;
// Index which will be used to track not processed character groups.
int nextLeftGroupsOrderIdx;
// Index of the last non-processed character in a group.
int lastCharIdx;
// Index of the last non-processed group.
int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for (int i = 0; i < password.Length; i++)
{
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
if (lastLeftGroupsOrderIdx == 0)
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0,
lastLeftGroupsOrderIdx);
// Get the actual index of the character group, from which we will
// pick the next character.
nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Get the index of the last unprocessed characters in this group.
lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
if (lastCharIdx == 0)
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx + 1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
charsLeftInGroup[nextGroupIdx] =
charGroups[nextGroupIdx].Length;
// There are more unprocessed characters left.
else
{
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
{
char temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] =
charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// There are more unprocessed groups left.
else
{
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] =
leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
}
// 2nd Random DNA Generation Code:
// New Class to Generate Passwords:
public class RandomPassword1
{
// Define default min and max password lengths.
private static int DEFAULT_MIN_PASSWORD_LENGTH = 6;
private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
// Define supported password characters divided into groups.
// You can add (or remove) characters to (from) these groups.
////////////private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
//private static string PASSWORD_CHARS_UCASE = "ACGT";
private static string PASSWORD_CHARS_NUMERIC = "23456789";
////////////private static string PASSWORD_CHARS_SPECIAL = "*$-+?_&=!%{}/";
/// <summary>
/// Generates a random password.
/// </summary>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random. It will be no shorter than the minimum default and
/// no longer than maximum default.
/// </remarks>
public static string Generate()
{
return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
DEFAULT_MAX_PASSWORD_LENGTH);
}
/// <summary>
/// Generates a random password of the exact length.
/// </summary>
/// <param name="length">
/// Exact password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
public static string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password.
/// </summary>
/// <param name="minLength">
/// Minimum password length.
/// </param>
/// <param name="maxLength">
/// Maximum password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random and it will fall with the range determined by the
/// function parameters.
/// </remarks>
public static string Generate(int minLength, int maxLength)
{
// Make sure that input parameters are valid.
if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
return null;
// Create a local array containing supported password characters
// grouped by types. You can remove character groups from this
// array, but doing so will weaken the password strength.
char[][] charGroups = new char[][]
{
//////////////PASSWORD_CHARS_LCASE.ToCharArray(),
//PASSWORD_CHARS_UCASE.ToCharArray(),
PASSWORD_CHARS_NUMERIC.ToCharArray(),
//////////////PASSWORD_CHARS_SPECIAL.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
int[] charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (int i = 0; i < charsLeftInGroup.Length; i++)
charsLeftInGroup[i] = charGroups[i].Length;
// Use this array to track (iterate through) unused character groups.
int[] leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (int i = 0; i < leftGroupsOrder.Length; i++)
leftGroupsOrder[i] = i;
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
byte[] randomBytes = new byte[4];
// Generate 4 random bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = (randomBytes[0] & 0x7f) << 24 |
randomBytes[1] << 16 |
randomBytes[2] << 8 |
randomBytes[3];
// Now, this is real randomization.
Random random = new Random(seed);
// This array will hold password characters.
char[] password = null;
// Allocate appropriate memory for the password.
if (minLength < maxLength)
password = new char[random.Next(minLength, maxLength + 1)];
else
password = new char[minLength];
// Index of the next character to be added to password.
int nextCharIdx;
// Index of the next character group to be processed.
int nextGroupIdx;
// Index which will be used to track not processed character groups.
int nextLeftGroupsOrderIdx;
// Index of the last non-processed character in a group.
int lastCharIdx;
// Index of the last non-processed group.
int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for (int i = 0; i < password.Length; i++)
{
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
if (lastLeftGroupsOrderIdx == 0)
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0,
lastLeftGroupsOrderIdx);
// Get the actual index of the character group, from which we will
// pick the next character.
nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Get the index of the last unprocessed characters in this group.
lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
if (lastCharIdx == 0)
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx + 1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
charsLeftInGroup[nextGroupIdx] =
charGroups[nextGroupIdx].Length;
// There are more unprocessed characters left.
else
{
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
{
char temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] =
charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// There are more unprocessed groups left.
else
{
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] =
leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
}
public DbCommand cmdInsertcountry { get; set; }
public DbCommand cmdinsertVital_Signs_tbl { get; set; }
}
}
|
namespace BettingSystem.Application.Competitions.Leagues.Commands.Create
{
public class CreateLeagueResponseModel
{
internal CreateLeagueResponseModel(int id) => this.Id = id;
public int Id { get; }
}
}
|
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Unit_Test_Demo.Commands;
using Unit_Test_Demo.DAL;
using Unit_Test_Demo.Domain;
namespace Unit_Test_Demo.Controllers
{
[Route("api/[controller]")]
public class ContainersController : Controller
{
private readonly DemoContext _context;
public ContainersController(DemoContext context)
{
_context = context;
}
[HttpGet]
public List<Container> GetAllContainers()
{
return _context.Containers.ToList();
}
[HttpGet("{id}")]
public Container GetContainerById(int id)
{
return _context.Containers.FirstOrDefault(c => c.Id == id);
}
[HttpPost]
public int CreateContainer([FromBody]CreateContainerCommand command)
{
var container = new Container(command.MaxCapacity);
_context.Add(container);
_context.SaveChanges();
return container.Id;
}
[HttpPost("{id}/pack")]
public void PackItemIntoContainer(int id)
{
var container = _context.Containers.FirstOrDefault(c => c.Id == id);
if (container == null)
{
throw new ObjectNotFoundException($"Pack failed: container with ID [{id}] not found!");
}
container.Pack();
_context.SaveChanges();
}
}
}
|
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.Threading;
using System.Windows.Forms;
using System.IO;
using MetroFramework;
using MetroFramework.Forms;
using MetroFramework.Drawing;
using MetroFramework.Controls;
using System.Xml;
namespace TerminalTool
{
public partial class SendToolForm : MetroForm
{
private MetroTextBox textBox = null;
private MainForm mainForm = null;
private bool loopChecked = false;
private Control ParentControl = null;
private string _cmdListDefaultFile;
public MetroColorStyle MetroStyle
{
get { return StyleMng.Style; }
set
{
StyleMng.Style = value;
dividePanel.BackColor = MetroPaint.GetStyleColor(StyleMng.Style);
}
}
public string CmdListDefaultFile
{
get { return _cmdListDefaultFile; }
set
{
_cmdListDefaultFile = value;
reloadToolStripMenuItem.ToolTipText = _cmdListDefaultFile;
}
}
public SendToolForm(MainForm form, MetroTextBox tb)
{
InitializeComponent();
StyleMng.Theme = MetroThemeStyle.Light;
//StyleManager = StyleMng;
MetroStyle = MetroColorStyle.Default;
textBox = tb;
mainForm = form;
CmdListDefaultFile = Application.StartupPath + "\\default.xml";
ReloadFile(false);
}
private void SendMsg(string msg)
{
mainForm.SendMessage(msg, true);
}
public void UpdateLocation()
{
if (null != ParentControl)
{
this.Width = ParentControl.Width - 1;
this.Location = ParentControl.PointToScreen(new Point(ParentControl.Left - 3, ParentControl.Height));
}
}
public void ShowHide(Control control)
{
if (control == null)
throw new ArgumentNullException("control");
ParentControl = control;
UpdateLocation();
if (!this.Visible)
Show(mainForm);
else
Hide();
}
enum ErrorType
{
ERROR,
WARNING,
INFO
}
private void ShowInfo(string error, ErrorType type)
{
switch (type)
{
case ErrorType.ERROR:
labelInfo.Text = "ERROR: ";
labelInfo.BackColor = Color.Crimson;
break;
case ErrorType.WARNING:
labelInfo.Text = "WARNING: ";
labelInfo.BackColor = Color.DarkOrchid;
break;
case ErrorType.INFO:
labelInfo.Text = "INFO: ";
labelInfo.BackColor = Color.DeepSkyBlue;
break;
default:
break;
}
labelInfo.Text += error;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
DataGridViewRow row = gridCmdList.CurrentRow;
if (null != row)
{
Clipboard.SetDataObject((string)row.Cells[1].Value);
}
}
private void copyAllToolStripMenuItem_Click(object sender, EventArgs e)
{
string str = null;
foreach (DataGridViewRow row in gridCmdList.Rows)
{
str = str + row.Cells[1].Value + "\r\n";
}
Clipboard.SetDataObject(str);
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in gridCmdList.SelectedRows)
{
//gridCmdList.Rows.Remove(row);
if (!row.IsNewRow)
gridCmdList.Rows.Remove(row);
else
gridCmdList.ClearSelection();
}
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
gridCmdList.Rows.Clear();
textBox.Clear();
}
public void AddCmdDisc(string cmd, string discription)
{
if (null == cmd || 0 == cmd.Length)
return;
foreach (DataGridViewRow row in gridCmdList.Rows)
{
if (cmd.Equals(row.Cells[1].Value))
{
return;
}
}
int index = gridCmdList.Rows.Add();
gridCmdList.Rows[index].Cells[1].Value = cmd;
gridCmdList.Rows[index].Cells[1].ToolTipText = discription;
}
public void AddCmd(string item)
{
if (null == item || 0 == item.Length)
return;
foreach (DataGridViewRow row in gridCmdList.Rows)
{
if (item.Equals(row.Cells[1].Value))
{
return;
}
}
int index = gridCmdList.Rows.Add();
gridCmdList.Rows[index].Cells[1].Value = item;
gridCmdList.Rows[index].Cells[1].ToolTipText = "no discription";
// string[] array = new string[] { "null", item };
//gridCmdList.Rows.Insert(0, array);
}
private void UploadFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "(*.xml)|*.xml";
ofd.InitialDirectory = Application.StartupPath;
if (ofd.ShowDialog() == DialogResult.OK)
{
XmlDocument xml = new XmlDocument();
xml.Load(@ofd.FileName);
XmlNodeList nodeList = xml.DocumentElement.GetElementsByTagName("CMD");
foreach (XmlNode node in nodeList) //当然也能用nodeList的值
{
if (null != node.Attributes["cmd"])
{
if (null != node.Attributes["discription"])
{
AddCmdDisc(node.Attributes["cmd"].InnerText, node.Attributes["discription"].InnerText);
}
else
{
AddCmd(node.Attributes["cmd"].InnerText);
}
}
}
CmdListDefaultFile = ofd.FileName;
}
}
private void SaveToFile()
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Filter = "(*.xml)|*.xml";
fileDialog.DefaultExt = "xml";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
try
{
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlElement root = doc.CreateElement("cmdlist");
doc.AppendChild(root);
foreach (DataGridViewRow row in gridCmdList.Rows)
{
XmlElement element = doc.CreateElement("CMD");
element.SetAttribute("cmd", (string)row.Cells[1].Value);
element.SetAttribute("discription", row.Cells[1].ToolTipText);
root.AppendChild(element);
}
doc.Save(@fileDialog.FileName);
}
catch (Exception ex)
{
MetroMessageBox.Show(this, ex.Message, "MetroMessagebox");
}
}
}
private void ReloadFile(bool warning)
{
if (!File.Exists(@CmdListDefaultFile))
{
if (warning)
MetroMessageBox.Show(this, CmdListDefaultFile + ":文件不存在");
return;
}
gridCmdList.Rows.Clear();
textBox.Clear();
XmlDocument xml = new XmlDocument();
xml.Load(@CmdListDefaultFile);
XmlNodeList nodeList = xml.DocumentElement.GetElementsByTagName("CMD");
foreach (XmlNode node in nodeList) //当然也能用nodeList的值
{
if (null != node.Attributes["cmd"])
{
if (null != node.Attributes["discription"])
{
AddCmdDisc(node.Attributes["cmd"].InnerText, node.Attributes["discription"].InnerText);
}
else
{
AddCmd(node.Attributes["cmd"].InnerText);
}
}
}
}
private void uploadFileToolStripMenuItem_Click(object sender, EventArgs e)
{
UploadFile();
}
private void saveToFileToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveToFile();
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
ReloadFile(true);
}
private void UpdateOwnerTextBox(string text)
{
this.Invoke((EventHandler)(delegate
{
textBox.Text = text;
}));
}
private void gridCmdList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
/*foreach (DataGridViewRow row in gridCmdList.SelectedRows)
{
UpdateOwnerTextBox((string)row.Cells[1].Value);
return;
}*/
DataGridViewRow row = gridCmdList.CurrentRow;
if (null != row)
{
UpdateOwnerTextBox((string)row.Cells[1].Value);
}
}
private void gridCmdList_SelectionChanged(object sender, EventArgs e)
{
/*foreach (DataGridViewRow row in gridCmdList.SelectedRows)
{
UpdateOwnerTextBox((string)row.Cells[1].Value);
return;
}*/
DataGridViewRow row = gridCmdList.CurrentRow;
if (null != row)
{
UpdateOwnerTextBox((string)row.Cells[1].Value);
}
}
private int AddGridItem()
{
string cmd;
string name;
int index;
NewCmdForm addForm = new NewCmdForm();
//addForm.Owner = this;
//addForm.Parent = mainForm.Parent;
if (addForm.ShowDialog() == DialogResult.OK)
{
cmd = addForm.GetNewCmd();
name = addForm.GetNewCmdName();
if (null == cmd || 0 == cmd.Length)
{
ShowInfo("Null Cmd", ErrorType.ERROR);
return -1;
}
index = gridCmdList.Rows.Add();
gridCmdList.Rows[index].Cells[1].Value = cmd;
if (null == name || 0 == name.Length)
{
ShowInfo("Not Add Cmd Discription", ErrorType.WARNING);
gridCmdList.Rows[index].Cells[1].ToolTipText = "No Discription";
}
else
{
gridCmdList.Rows[index].Cells[1].ToolTipText = name;
ShowInfo("A New Cmd Added", ErrorType.INFO);
}
}
return 0;
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
AddGridItem();
}
private int LoadGridItem()
{
string cmd = null;
string name = null;
//int index;
NewCmdForm addForm = new NewCmdForm();
DataGridViewRow row = gridCmdList.CurrentRow;
if (null == row)
{
return -1;
}
//foreach (DataGridViewRow row in gridCmdList.SelectedRows)
//{
cmd = (string)row.Cells[1].Value;
name = row.Cells[1].ToolTipText;
// break;
//}
addForm.SetNewCmd(cmd);
addForm.SetNewCmdName(name);
if (addForm.ShowDialog() == DialogResult.OK)
{
cmd = addForm.GetNewCmd();
name = addForm.GetNewCmdName();
if (null == cmd || 0 == cmd.Length)
{
ShowInfo("Null Cmd", ErrorType.ERROR);
return -1;
}
//index = gridCmdList.Rows.Add();
row.Cells[1].Value = cmd;
if (null == name || 0 == name.Length)
{
ShowInfo("Not Add Cmd Discription", ErrorType.WARNING);
row.Cells[1].ToolTipText = "No Discription";
}
else
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)row.Cells["ColumnEdit"];
checkCell.Value = false;
row.Cells[1].ToolTipText = name;
ShowInfo("Cmd had modify success", ErrorType.INFO);
}
}
return 0;
}
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
LoadGridItem();
}
private void gridCmdList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = gridCmdList.CurrentRow;
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)row.Cells["ColumnEdit"];
DataGridViewTextBoxCell textCell = (DataGridViewTextBoxCell)row.Cells["ColumnCmd"];
bool flag = Convert.ToBoolean(checkCell.Value);
if (flag)
{
LoadGridItem();
}
else
{
SendMsg((string)row.Cells[1].Value);
}
}
private bool LoopChecked
{
get { return loopChecked; }
set
{
loopChecked = value;
if (loopChecked)
{
loopChecked = true;
loopToolStripMenuItem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
LoopBGWorker.RunWorkerAsync();
}
else
{
loopChecked = false;
loopToolStripMenuItem.DisplayStyle = ToolStripItemDisplayStyle.Text;
LoopBGWorker.CancelAsync();
}
}
}
private void btListSend_Click(object sender, EventArgs e)
{
DataGridViewRow row = gridCmdList.CurrentRow;
if (null != row)
{
SendMsg((string)row.Cells[1].Value);
}
}
private void SendToolForm_Deactivate(object sender, EventArgs e)
{
if (autoHideToggle.Checked)
{
this.TopLevel = false;
Hide();
this.TopLevel = true;
}
}
private void selectedToolStripMenuItem_Click(object sender, EventArgs e)
{
DataGridViewRow row = gridCmdList.CurrentRow;
if (null != row)
{
SendMsg((string)row.Cells[1].Value);
}
}
private void SendChecked()
{
foreach (DataGridViewRow row in gridCmdList.Rows)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)row.Cells[0];
if ((bool)checkCell.EditedFormattedValue)
{
SendMsg((string)row.Cells[1].Value);
Thread.Sleep(1);
}
}
}
private void checkedToolStripMenuItem_Click(object sender, EventArgs e)
{
SendChecked();
}
private void loopToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mainForm.IsPortOpen())
{
LoopChecked = !LoopChecked;
}
else
{
LoopChecked = false;
}
}
private void LoopBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
do
{
foreach (DataGridViewRow row in gridCmdList.Rows)
{
try
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)row.Cells[0];
if ((bool)checkCell.EditedFormattedValue)
{
SendMsg((string)row.Cells[1].Value);
Thread.Sleep(10);
}
}
catch (Exception ex)
{
MetroMessageBox.Show(this, ex.Message, "MetroMessagebox");
}
if (LoopBGWorker.CancellationPending)
{
break;
}
}
} while (LoopChecked && (!LoopBGWorker.CancellationPending));
}
private void LoopBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WritingToTextFile
{
class Program
{
static void Main(string[] args)
{
int count=1;
StreamWriter file = new StreamWriter(@"C:\Users\chery\Desktop\WriteText.txt",true);
//file.WriteLine("Hi Chery Garu1");
//file.WriteLine("Ding dong ding");
file.Close();
StreamReader file1 = new StreamReader(@"C:\Users\chery\Desktop\WriteText.txt");
string line = null;
while ((line = file1.ReadLine()) != null)
{
if (line.Contains("ding") || line.Contains("ding"))
{
count = count +1;
Console.WriteLine(count);
}
}
//Console.WriteLine(file1.ReadToEnd());
Console.ReadLine();
}
}
}
|
using MdServices.Base.Interfaces;
namespace MdServices.Base
{
public static class LocalContext
{
public static ILoggerFactory LoggerFactory { get; }
static LocalContext()
{
LoggerFactory = new LoggerFactory();
LoggerFactory.SetLevel(ILogger.LogLevel.Trace);
}
}
public static class Context<T>
{
public static ILogger Logger { get; set; }
static Context()
{
Logger = LocalContext.LoggerFactory.CreateLogger<T>();
Logger.Info("Logger for type: " + typeof(T).FullName);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MeriMudra.Models;
namespace MeriMudra.Controllers
{
public class BusinessPartnerProgrammesController : Controller
{
private MmDbContext db = new MmDbContext();
// GET: BusinessPartnerProgrammes
public ActionResult Index()
{
return View();
}
// GET: BusinessPartnerProgrammes/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BusinessPartnerProgramme businessPartnerProgramme = db.BusinessPartnerProgrammes.Find(id);
if (businessPartnerProgramme == null)
{
return HttpNotFound();
}
return View(businessPartnerProgramme);
}
// GET: BusinessPartnerProgrammes/Create
public ActionResult Create()
{
return View();
}
// POST: BusinessPartnerProgrammes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,FullName,Mobile,Email,PAN,Aadhar,Company,City")] BusinessPartnerProgramme businessPartnerProgramme)
{
var isDuplicateAdharOrPan = false;
if (db.BusinessPartnerProgrammes.Any(b => b.Aadhar.Equals(businessPartnerProgramme.Aadhar)))
{
ModelState.AddModelError("Aadhar", "Given Aadhar Number is already registered with us. ");
isDuplicateAdharOrPan = true;
}
if (db.BusinessPartnerProgrammes.Any(b => b.PAN.Equals(businessPartnerProgramme.PAN)))
{
isDuplicateAdharOrPan = true;
ModelState.AddModelError("PAN", "Given PAN Number is already registered with us. ");
}
if (ModelState.IsValid && !isDuplicateAdharOrPan)
{
businessPartnerProgramme.CreatedDate = System.DateTime.Now;
db.BusinessPartnerProgrammes.Add(businessPartnerProgramme);
var x = db.SaveChanges();
TempData["BusinessPartnerSaved"] = "We accepted your details for our Business Partner Programm, our representative will contact you soon.";
return RedirectToAction("Index");
}
return View(businessPartnerProgramme);
}
// GET: BusinessPartnerProgrammes/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BusinessPartnerProgramme businessPartnerProgramme = db.BusinessPartnerProgrammes.Find(id);
if (businessPartnerProgramme == null)
{
return HttpNotFound();
}
return View(businessPartnerProgramme);
}
// POST: BusinessPartnerProgrammes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FullName,Mobile,Email,PAN,Aadhar,Company,City")] BusinessPartnerProgramme businessPartnerProgramme)
{
if (ModelState.IsValid)
{
db.Entry(businessPartnerProgramme).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(businessPartnerProgramme);
}
// GET: BusinessPartnerProgrammes/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BusinessPartnerProgramme businessPartnerProgramme = db.BusinessPartnerProgrammes.Find(id);
if (businessPartnerProgramme == null)
{
return HttpNotFound();
}
return View(businessPartnerProgramme);
}
// POST: BusinessPartnerProgrammes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BusinessPartnerProgramme businessPartnerProgramme = db.BusinessPartnerProgrammes.Find(id);
db.BusinessPartnerProgrammes.Remove(businessPartnerProgramme);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
namespace DanialProject.Models.Others
{
public class LoginViewModel
{
[Display(Name="Username")]
[Required]
public string Email
{
get;
set;
}
[DataType(DataType.Password)]
[Display(Name="Password")]
[Required]
public string Password
{
get;
set;
}
[Display(Name="Remember me?")]
public bool RememberMe
{
get;
set;
}
public LoginViewModel()
{
}
}
} |
using System.Collections.Generic;
namespace Quote.Framework
{
public interface ILoanRequestedAmountValidator
{
List<ILoanRequestedAmountValidationRule> Rules { get; set; }
void Validate(int requestedAmount);
}
}
|
namespace Sentry.Internal;
internal abstract class RandomValuesFactory
{
public abstract int NextInt();
public abstract int NextInt(int minValue, int maxValue);
public abstract double NextDouble();
public abstract void NextBytes(byte[] bytes);
public bool NextBool(double rate) => rate switch
{
>= 1 => true,
<= 0 => false,
_ => NextDouble() < rate
};
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using IRAP.Global;
using IRAPShared;
namespace IRAP.Entity.MDM
{
/// <summary>
/// 一点课
/// </summary>
public class OnePointLesson
{
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 问题编号
/// </summary>
public int IssueNo { get; set; }
/// <summary>
/// 工序叶标识
/// </summary>
public int T216LeafID { get; set; }
/// <summary>
/// 工序代码
/// </summary>
public string T216Code { get; set; }
/// <summary>
/// 工序名称
/// </summary>
public string T216Name { get; set; }
/// <summary>
/// 问题类型
/// </summary>
public string IssueType { get; set; }
/// <summary>
/// 缺陷描述
/// </summary>
public string DefectDesc { get; set; }
/// <summary>
/// 缺陷根源叶标识
/// </summary>
public int T144LeafID { get; set; }
/// <summary>
/// 缺陷根源代码
/// </summary>
public string T144Code { get; set; }
/// <summary>
/// 缺陷根源
/// </summary>
public string T144Name { get; set; }
/// <summary>
/// 操作要求
/// </summary>
public string OperationReq { get; set; }
/// <summary>
/// 不正确的图片Base64编码
/// </summary>
public string IncorrectPic { get; set; }
/// <summary>
/// 正确的图片Base64编码
/// </summary>
public string CorrectPic { get; set; }
/// <summary>
/// 培训日期
/// </summary>
public string TrainingDate { get; set; }
/// <summary>
/// 培训者工号
/// </summary>
public string TrainerCode { get; set; }
/// <summary>
/// 培训者姓名
/// </summary>
public string TrainerName { get; set; }
/// <summary>
/// 不正确的图片
/// </summary>
[IRAPORMMap(ORMMap = false)]
public Image IncorrectPicture
{
get { return Base64ToImage(IncorrectPic); }
}
/// <summary>
/// 正确的图片
/// </summary>
[IRAPORMMap(ORMMap = false)]
public Image CorrectPicture
{
get { return Base64ToImage(CorrectPic); }
}
private Image Base64ToImage(string stringBase64)
{
byte[] imageBytes;
try
{
imageBytes = Convert.FromBase64String(stringBase64);
return Tools.BytesToImage(imageBytes);
}
catch
{
return null;
}
}
public OnePointLesson Clone()
{
return MemberwiseClone() as OnePointLesson;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartObjects
{
public class AxlAccount:SimpleDbEntity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Счет AXL"; }
}
/// <summary>
/// Начальный остаток
/// </summary>
public decimal BeginRest
{
get;
set;
}
/// <summary>
/// Текущий остаток
/// </summary>
public decimal CurrRest
{
get;
set;
}
/// <summary>
/// Значение внутреннего кредита
/// </summary>
public decimal CreditAmount
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace SportHub.Models
{
public class Sport
{
public int Id { get; set; }
public ApplicationUser SportMan { get; set; }
[Required]
public string SportManId { get; set; }
public DateTime DateTime { get; set; }
[Required]
[StringLength(255)]
public string Venue { get; set; }
public SportKind SportKind { get; set; }
[Required]
public int SportKindId { get; set; }
}
} |
using System;
using System.Reflection;
using Sitecore.Includes.AssemblyBinding.Configuration;
namespace Sitecore.Includes.AssemblyBinding.App_Start
{
/// <summary>
/// Initialize assembly bindings
/// </summary>
public class InitializeAssemblyBindings
{
/// <summary>
/// Processes the specified arguments.
/// </summary>
public static void Start()
{
if (BindingPolicyConfiguration.BindingPolicyManager == null)
{
return;
}
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += ResolveFromIncludesAssemblyBinding;
}
/// <summary>
/// Resolves from includes assembly binding.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="ResolveEventArgs"/> instance containing the event data.</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private static Assembly ResolveFromIncludesAssemblyBinding(object sender, ResolveEventArgs args)
{
if (args.RequestingAssembly != null)
{
return null;
}
var assemblyName = new AssemblyName(args.Name);
var redirectAssemblyName = BindingPolicyConfiguration.BindingPolicyManager.Redirect(assemblyName);
if (redirectAssemblyName != null)
{
BindingPolicyConfiguration.BindingPolicyManager.IgnoreRedirectsForAssembly(assemblyName);
return Assembly.Load(redirectAssemblyName);
}
return null;
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class InfoPanel : MonoBehaviour
{
[SerializeField] private CardData CardDate = null;
[SerializeField] private Text[] Texts = new Text[(int)EnumNumbers.Cards];
[SerializeField] private Image[] Images = new Image[(int)EnumNumbers.Cards];
[SerializeField] private Sprite[] FullCardSprites = new Sprite[(int)EnumNumbers.FullCards];
public void Init(int[] cardIDs)
{
var loadtext = (Resources.Load("CardEffect", typeof(TextAsset)) as TextAsset).text;
string[] spliteText = loadtext.Split('\n');
var num = 0;
foreach(var val in cardIDs)
{
Texts[num].text=
CardDate.KeyValuesName[val] + ":HP" + CardDate.KeyValuesHP[val].ToString() + "/AD" + CardDate.KeyValuesAD[val].ToString() + "\n" +
spliteText[val].Replace("ad", (CardDate.KeyValuesAD[val] * CardDate.KeyValuesRatio[val]).ToString())
.Replace("hp", CardDate.KeyValuesHP[val].ToString());
Images[num].sprite = FullCardSprites[val];
num++;
}
}
[SerializeField] private GameObject Canvas = null;
public void PanelChange()
{
if (Canvas.activeSelf)
{
Canvas.SetActive(false);
}
else if (!Canvas.activeSelf)
{
Canvas.SetActive(true);
}
}
} |
using UnityEngine;
using System.Collections;
namespace Mio.TileMaster {
public class RewardDetailView : MonoBehaviour {
[SerializeField]
private UISprite rewardIcon;
[SerializeField]
private UILabel lbRewardValue;
public void SetReward(string iconSpriteName, string rewardValue) {
if(rewardIcon != null) {
rewardIcon.spriteName = iconSpriteName;
}
if(lbRewardValue != null) {
lbRewardValue.text = rewardValue;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace DucksV2
{
class Program
{
static void Main(string[] args)
{
var donald = new Duck("Sir Donald", "Mallard", 100, 17);
var daffy = new Duck("Sir Daffy", "Mallard", 99, 14);
var daisy = new Duck("Miss Daisy", "Marbled Duck", 38, 11);
var anotherDaisy = new Duck("Sir Daisy", "Mallard", 99, 14);
Console.WriteLine($"{donald.Name} has the hash code of {donald.GetHashCode()}");
Console.WriteLine($"{daffy.Name} has the hash code of {daffy.GetHashCode()}");
Console.WriteLine($"{daisy.Name} has the hash code of {daisy.GetHashCode()}");
Console.ReadLine();
Dictionary<Duck, int> ducks = new Dictionary<Duck, int>
{
{ donald, donald.GetHashCode() },
{ daffy, daffy.GetHashCode() },
{ daisy, daisy.GetHashCode() }
};
List<Duck> duckies = new List<Duck>
{
donald,
daffy,
daisy
};
Console.WriteLine("The ducks have now been added to a list and sorted in name");
foreach (var duck in duckies)
{
Console.WriteLine(duck.Name);
}
duckies.Sort(new SortDuckHelper());
ToString(duckies);
Console.ReadLine();
}
static void ToString(List<Duck> list)
{
StringBuilder result = new StringBuilder("Your ducks in order are: ");
for (int i = 0; i < list.Count; i++)
{
if (i == list.Count - 1)
{
result.AppendFormat(" {0}", list[i].Name);
}
else
{
result.AppendFormat(" {0},", list[i].Name);
}
}
Console.WriteLine(result);
}
}
} |
namespace _01.ReverseNumbersWithAStack
{
using System;
using System.Collections.Generic;
using System.Linq;
public class ReverseNumbersWithAStack
{
public static void Main()
{
string input = Console.ReadLine();
if (input != null)
{
int[] numInts =
input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
Stack<int> stackInt = new Stack<int>();
foreach (int i in numInts)
{
stackInt.Push(i);
}
Console.WriteLine(String.Join(" ", stackInt));
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace learn_180330_Graphics_1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string[] colstr = new string[] { "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "天秤座", "处女座",
"天蝎座","射手座", "摩羯座", "水瓶座", "双鱼座" };
ArrayList labelArray;
private void Form2_Load(object sender, EventArgs e)
{
Graphics gra = this.CreateGraphics();
try
{
labelArray = new ArrayList() { label1, label2, label3, label4, label5, label6, label7, label8, label9, label10, label11, label12 };
Font font=new Font("宋体",16,FontStyle.Bold);
for (int i = 0; i < labelArray.Count; i++)
{
//Label temLabel = labelArray[i] as Label;
//temLabel.Location = new Point(33, (30 * (i + 2) + 3));
//temLabel.Text = colstr[i];
gra.DrawString(colstr[i], font, new SolidBrush(Color.Black), new PointF(33, (30 * (i + 2) + 3)));
}
int sum = Method.ConnectSql("SELECT COUNT(1) FROM dbo.T_Constellation");
DataSet ds = Method.GetData("select * from T_Constellation");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = ds.Tables[0].Rows[i];
string colstr1 = dr["Constellation"].ToString();
int count = int.Parse(dr["Count"].ToString());
for (int j = 0; j < colstr.Length; j++)
{
if (colstr1 == colstr[j])
{
Rectangle re = new Rectangle(110, (30 * (j + 2) + 3), (count * 1000 / sum), 12);
SolidBrush sBrush = new SolidBrush(Color.Blue);
Pen pen = new Pen(sBrush, 2);
gra.DrawRectangle(pen, re);
gra.FillRectangle(sBrush, re);
//return;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
}
}
|
namespace SimplySqlSchema
{
public class KeySchema
{
public int KeyIndex { get; set; }
public bool AutoIncrement { get; set; }
}
}
|
namespace BDTest.Settings.Skip;
public class SkipStepRule<T>
{
public Func<T, bool> Condition { get; }
public Type AssociatedSkipAttributeType { get; }
public SkipStepRule(Type associatedSkipAttributeType, Func<T, bool> condition)
{
AssociatedSkipAttributeType = associatedSkipAttributeType;
Condition = condition;
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Glass
{
public class Type
{
private readonly System.Type type;
public Type(System.Type type)
{
this.type = type;
}
public IEnumerable<Member> Members
{
get
{
return type.GetMembers().Select(info => new Member(info));
}
}
public string Name
{
get
{
return type.Name;
}
}
public bool IsStatic
{
get
{
return type.IsAbstract && type.IsSealed;
}
}
public override string ToString()
{
return type.FullName;
}
protected bool Equals(Type other)
{
return type == other.type;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != GetType())
return false;
return Equals((Type) obj);
}
public override int GetHashCode()
{
return (type != null ? type.GetHashCode() : 0);
}
public static bool operator ==(Type left, Type right)
{
return Equals(left, right);
}
public static bool operator !=(Type left, Type right)
{
return !Equals(left, right);
}
}
public enum Kind
{
Class,
Interface,
Struct,
Enum
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SuperMassive : MonoBehaviour
{
public void InitSuperMassive(float posX, float posY, int size, int grav) {
PointEffector2D gravityEffector = GetComponent<PointEffector2D>();
gravityEffector.forceMagnitude = grav;
this.transform.position = new Vector3(posX, posY, 0);
this.transform.localScale = new Vector3(size*10, size*10, 0);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Collections.Generic;
namespace Apv.AV.Services.DTO.FC
{
public class CarModelClassDto
{
public string id { get; set; }
public string countryCode { get; set; }
public string companyId { get; set; }
public string modelClassId { get; set; }
public string modelClassCode { get; set; }
public string modelClassBrand {get;set;}
public string modelClassLabel { get; set; }
public string modelClassLabelLoc { get; set; }
public string modelClassTypeLabel { get; set; }
public string modelClassTypeLabelLoc { get; set; }
public List<CarModelClassImageDto> carModelClassImages {get;set;}
public decimal order { get; set; }
public bool published { get; set; }
}
} |
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
public class AiPathGroupCtrl : MonoBehaviour {
public static List<Transform> PathArray = null;
// Use this for initialization
void Awake()
{
SetPathArray();
this.enabled = false;
}
void OnDrawGizmosSelected()
{
if (!enabled) {
return;
}
SetAiPathIndexInfo();
}
void SetAiPathIndexInfo()
{
List<AiPathCtrl> PathArrayScript = new List<AiPathCtrl>(transform.GetComponentsInChildren<AiPathCtrl>()){};
for (int i = 0; i < PathArrayScript.Count; i++) {
PathArrayScript[i].SetPathIndexInfo(i);
}
}
void SetPathArray()
{
List<AiPathCtrl> PathArrayScript = new List<AiPathCtrl>(transform.GetComponentsInChildren<AiPathCtrl>()){};
PathArray = new List<Transform>(){};
for (int i = 0; i < PathArrayScript.Count; i++) {
PathArray.Add(PathArrayScript[i].transform);
}
}
public static Transform FindAiPathTran(int index)
{
if (index < 0 || index >= PathArray.Count) {
return null;
}
return PathArray[index];
}
}
|
using System;
using System.Collections.Generic;
using SpeedSlidingTrainer.Core.Model;
using SpeedSlidingTrainer.Core.Model.State;
namespace ConsoleApplication1.BoardSolverV4
{
internal class NodeV4 : IEquatable<NodeV4>
{
private readonly int distanceFromInitialNode;
private NodeV4(BoardStateV4 state, int estimatedDistanceToGoal)
{
this.State = state;
this.Cost = estimatedDistanceToGoal;
}
private NodeV4(NodeV4 parentNode, Step previousStep, BoardStateV4 state, int distanceFromInitialNode, int estimatedDistanceToGoal)
{
this.ParentNode = parentNode;
this.PreviousStep = previousStep;
this.State = state;
this.distanceFromInitialNode = distanceFromInitialNode;
this.Cost = distanceFromInitialNode + estimatedDistanceToGoal;
}
public NodeV4 ParentNode { get; }
public Step? PreviousStep { get; }
public BoardStateV4 State { get; }
public int Cost { get; }
public static NodeV4 CreateInitialNode(BoardState state, BoardGoal goal)
{
int[] values = new int[state.TileCount];
int eye = 0;
for (int i = 0; i < state.TileCount; i++)
{
if (state[i] == 0)
{
eye = i;
values[i] = -1;
continue;
}
for (int j = 0; j < goal.TileCount; j++)
{
if (state[i] == goal[j])
{
values[i] = state[i];
break;
}
}
}
BoardStateV4 myState = new BoardStateV4(state.Width, state.Height, values, eye);
return new NodeV4(myState, GetManhattanDistance(myState, goal));
}
public IEnumerable<NodeV4> GetNeighbors(BoardGoal goal)
{
if (this.State.CanSlideLeft && this.PreviousStep != Step.Right)
{
yield return this.CreateNeighbor(Step.Left, this.State.SlideLeft(), goal);
}
if (this.State.CanSlideUp && this.PreviousStep != Step.Down)
{
yield return this.CreateNeighbor(Step.Up, this.State.SlideUp(), goal);
}
if (this.State.CanSlideRight && this.PreviousStep != Step.Left)
{
yield return this.CreateNeighbor(Step.Right, this.State.SlideRight(), goal);
}
if (this.State.CanSlideDown && this.PreviousStep != Step.Up)
{
yield return this.CreateNeighbor(Step.Down, this.State.SlideDown(), goal);
}
}
public bool Equals(NodeV4 other)
{
if (ReferenceEquals(other, null))
{
return false;
}
for (int i = 0; i < this.State.Values.Length; i++)
{
if (this.State.Values[i] != other.State.Values[i])
{
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
return this.Equals(obj as NodeV4);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = 0;
for (int i = 0; i < this.State.Values.Length; i++)
{
hashCode = (hashCode * 397) ^ this.State.Values[i];
}
return hashCode;
}
}
private static int GetManhattanDistance(BoardStateV4 state, BoardGoal goal)
{
int width = state.Width;
int height = state.Height;
int sum = 0;
for (int i = 0; i < goal.TileCount; i++)
{
if (goal[i] == 0)
{
continue;
}
for (int j = 0; j < goal.TileCount; j++)
{
if (state.Values[j] == goal[i])
{
int x1 = i % width;
int y1 = i / height;
int x2 = j % width;
int y2 = j / height;
sum += Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
break;
}
}
}
return sum;
}
private NodeV4 CreateNeighbor(Step previousStep, BoardStateV4 newState, BoardGoal goal)
{
return new NodeV4(this, previousStep, newState, this.distanceFromInitialNode + 1, GetManhattanDistance(newState, goal));
}
}
}
|
namespace WebApplication1.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Book",
c => new
{
Book_Id = c.Int(nullable: false),
Book_Name = c.String(nullable: false),
Book_Author = c.String(),
Book_BoughtDate = c.DateTime(nullable: false),
Book_Publisher = c.String(),
Book_Note = c.String(),
Book_Status = c.String(),
Book_Keeper = c.String(),
Create_Date = c.DateTime(nullable: false),
Create_User = c.String(),
Modify_Date = c.DateTime(nullable: false),
Modify_User = c.String(),
})
.PrimaryKey(t => t.Book_Id);
CreateTable(
"dbo.Borrow",
c => new
{
User_Id = c.String(nullable: false, maxLength: 128),
Book_Id = c.Int(nullable: false),
Code_Id = c.String(nullable: false, maxLength: 128),
Status = c.String(),
})
.PrimaryKey(t => new { t.User_Id, t.Book_Id, t.Code_Id })
.ForeignKey("dbo.Book", t => t.Book_Id, cascadeDelete: true)
.ForeignKey("dbo.Member", t => t.User_Id, cascadeDelete: true)
.Index(t => t.User_Id)
.Index(t => t.Book_Id);
CreateTable(
"dbo.Member",
c => new
{
User_Id = c.String(nullable: false, maxLength: 128),
User_CName = c.String(nullable: false),
User_EName = c.String(),
Create_Date = c.DateTime(),
Create_User = c.String(),
Modify_Date = c.DateTime(),
Modify_User = c.String(),
})
.PrimaryKey(t => t.User_Id);
CreateTable(
"dbo.Book_Data",
c => new
{
Book_Id = c.Int(nullable: false),
User_Id = c.String(nullable: false, maxLength: 128),
Code_Id = c.String(nullable: false, maxLength: 128),
Book_Class_Id = c.String(nullable: false, maxLength: 128),
Book_Name = c.String(),
Book_Author = c.String(),
Book_Bought_Date = c.DateTime(),
Book_Publisher = c.String(),
Book_Note = c.String(),
Book_Status = c.String(),
Book_Keeper = c.String(),
Create_Date = c.DateTime(),
Create_User = c.String(),
Modify_Date = c.DateTime(),
Modify_User = c.String(),
})
.PrimaryKey(t => new { t.Book_Id, t.User_Id, t.Code_Id, t.Book_Class_Id })
.ForeignKey("dbo.Book_Class", t => t.Book_Class_Id, cascadeDelete: true)
.ForeignKey("dbo.Book_Code", t => t.Code_Id, cascadeDelete: true)
.ForeignKey("dbo.Member", t => t.User_Id, cascadeDelete: true)
.Index(t => t.User_Id)
.Index(t => t.Code_Id)
.Index(t => t.Book_Class_Id);
CreateTable(
"dbo.Book_Class",
c => new
{
Book_Class_Id = c.String(nullable: false, maxLength: 128),
Book_Class_Name = c.String(),
Create_Date = c.DateTime(),
Create_User = c.String(),
Modify_Date = c.DateTime(),
Modify_user = c.String(),
})
.PrimaryKey(t => t.Book_Class_Id);
CreateTable(
"dbo.Book_Code",
c => new
{
Code_Id = c.String(nullable: false, maxLength: 128),
Code_Type = c.String(),
Code_Type_Desc = c.String(),
Code_Name = c.String(),
Create_Date = c.DateTime(),
Create_User = c.String(),
Modify_Date = c.DateTime(),
Modify_User = c.String(),
})
.PrimaryKey(t => t.Code_Id);
CreateTable(
"dbo.Code",
c => new
{
Code_Id = c.String(nullable: false, maxLength: 128),
Code_Type = c.String(nullable: false),
Code_Name = c.String(),
Code_TypeDesc = c.String(),
Create_Date = c.DateTime(nullable: false),
Create_User = c.String(),
Modify_Date = c.DateTime(nullable: false),
Modify_User = c.String(),
Borrows_User_Id = c.String(maxLength: 128),
Borrows_Book_Id = c.Int(),
Borrows_Code_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Code_Id)
.ForeignKey("dbo.Borrow", t => new { t.Borrows_User_Id, t.Borrows_Book_Id, t.Borrows_Code_Id })
.Index(t => new { t.Borrows_User_Id, t.Borrows_Book_Id, t.Borrows_Code_Id });
}
public override void Down()
{
DropForeignKey("dbo.Code", new[] { "Borrows_User_Id", "Borrows_Book_Id", "Borrows_Code_Id" }, "dbo.Borrow");
DropForeignKey("dbo.Borrow", "User_Id", "dbo.Member");
DropForeignKey("dbo.Book_Data", "User_Id", "dbo.Member");
DropForeignKey("dbo.Book_Data", "Code_Id", "dbo.Book_Code");
DropForeignKey("dbo.Book_Data", "Book_Class_Id", "dbo.Book_Class");
DropForeignKey("dbo.Borrow", "Book_Id", "dbo.Book");
DropIndex("dbo.Code", new[] { "Borrows_User_Id", "Borrows_Book_Id", "Borrows_Code_Id" });
DropIndex("dbo.Book_Data", new[] { "Book_Class_Id" });
DropIndex("dbo.Book_Data", new[] { "Code_Id" });
DropIndex("dbo.Book_Data", new[] { "User_Id" });
DropIndex("dbo.Borrow", new[] { "Book_Id" });
DropIndex("dbo.Borrow", new[] { "User_Id" });
DropTable("dbo.Code");
DropTable("dbo.Book_Code");
DropTable("dbo.Book_Class");
DropTable("dbo.Book_Data");
DropTable("dbo.Member");
DropTable("dbo.Borrow");
DropTable("dbo.Book");
}
}
}
|
using UnityEngine;
using Grpc.Core;
using static NetworkService.NetworkService;
using NetworkService;
public class ComParent {
protected Channel Channel { get; set; }
protected NetworkServiceClient Client { get; set; }
protected string IPaddr { get; set; }
protected string Port { get; set; }
protected string UserName { get; set; }
public ComParent(string ipaddr=null, string port=null, string userName=null) {
this.IPaddr = ipaddr;
this.Port = port;
this.UserName = userName;
}
~ComParent() {
// Not sure if this is actually necessary
Channel.ShutdownAsync().Wait();
}
protected void SetNetData(string ipaddr, string port, string userName) {
this.IPaddr = ipaddr;
this.Port = port;
this.UserName = userName;
}
protected Channel GetChannel() {
if (Channel == null) {
Channel = new Channel(IPaddr + ":" + Port, ChannelCredentials.Insecure);
}
return Channel;
}
protected NetworkServiceClient GetClient() {
GetChannel();
if (Client == null) {
Client = new NetworkServiceClient(Channel);
}
return Client;
}
public bool PingService() {
GetClient();
var reply = Client.PingService(new PingRequest { Name = UserName });
Debug.Log("PingService REPLY: " + reply.ResCode);
if (reply.ResCode == PingReplyStatus.Success)
return true;
return false;
}
}
|
using Discord;
using NUnit.Framework;
using OrbCore.ContentTools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestCommons.DiscordImpls;
namespace OrbCoreTests.ContentToolsTest {
[TestFixture]
class GuildTextMessageToolsTests {
[Test]
public void TestValidatingDMContent() {
var msg = CreateMockMsg();
var result = GuildTextMessageTools.IsSocketMessageGuildTextMessage(msg);
Assert.True(result);
}
[Test]
public void TestCreatingDMContent() {
var msg = CreateMockMsg();
var result = GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg);
Assert.AreEqual(msg, result.MessageInfo);
Assert.AreEqual(msg.Author, result.User);
Assert.AreEqual((msg.Author as IGuildUser).Guild, result.Guild);
Assert.AreEqual(msg.Content, result.MessageText);
Assert.AreEqual(msg.Channel, result.Channel);
}
[Test]
public void TestMessageNotGuildChannelMsg() {
var msg = new MockUserMessage();
msg.Channel = new MockDMChannel();
msg.Author = new MockUser();
msg.Content = "";
Assert.Throws<InvalidCastException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
[Test]
public void TestMessageNotUserMessage() {
var msg = new MockSystemMessage();
msg.Channel = new MockTextChannel();
msg.Author = new MockUser();
msg.Content = "";
Assert.Throws<InvalidCastException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
[Test]
public void TestUserNotGuildUser() {
var msg = new MockUserMessage();
msg.Channel = new MockTextChannel();
msg.Author = new MockUser();
msg.Content = "";
Assert.Throws<InvalidCastException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
[Test]
public void TestNullMessage() {
Assert.Throws<ArgumentNullException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(null));
}
[Test]
public void TestNullMessageContent() {
var msg = new MockUserMessage();
msg.Channel = new MockTextChannel();
msg.Author = new MockGuildUser() { Guild = new MockGuild() };
msg.Content = null;
Assert.Throws<ArgumentNullException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
[Test]
public void TestNullChannel() {
var msg = new MockUserMessage();
msg.Channel = null;
msg.Author = new MockGuildUser() { Guild = new MockGuild() };
msg.Content = "";
Assert.Throws<ArgumentNullException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
[Test]
public void TestNullUser() {
var msg = new MockUserMessage();
msg.Channel = new MockTextChannel();
msg.Author = null;
msg.Content = "";
Assert.Throws<ArgumentNullException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
[Test]
public void TestNullGuild() {
var msg = new MockUserMessage();
msg.Channel = new MockTextChannel();
msg.Author = new MockGuildUser();
msg.Content = "";
Assert.Throws<ArgumentNullException>(() => GuildTextMessageTools.CreateGuildTextMessageContentFromSocketMessage(msg));
}
private IMessage CreateMockMsg() {
var dm = new MockUserMessage();
var channel = new MockTextChannel();
var author = new MockGuildUser();
var guild = new MockGuild();
dm.Content = "Hello";
dm.Channel = channel;
dm.Author = author;
author.Guild = guild;
return dm;
}
}
}
|
public struct Point
{
public double x, y, z;
public Point(double p1, double p2, double p3)
{
x = p1;
y = p2;
z = p3;
}
public double DistSq()
{
return x * x + y * y + z * z;
}
//public override string ToString()
//{
// return "[x=" + x + ", y=" + y + ", z=" + z +"]";
//}
}
public class StructTest
{
public static double PointDistSq(Point p)
{
return p.x * p.x + p.y * p.y + p.z * p.z;
}
public static void BadSwapPoint(Point p)
{
var tmp = p.x;
p.x = p.y;
p.y = tmp;
}
public static void GoodSwapPoint(ref Point p)
{
var tmp = p.x;
p.x = p.y;
p.y = tmp;
}
/*static void Main(string[] args)
{
}*/
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace KemengSoft.UTILS.RemoteDebug
{
public class RemoteDebugRequestCookieCollection: IRequestCookieCollection
{
public struct Enumerator : IEnumerator<KeyValuePair<string, string>>, IEnumerator, IDisposable
{
private Dictionary<string, string>.Enumerator _dictionaryEnumerator;
private bool _notEmpty;
public KeyValuePair<string, string> Current
{
get
{
if (_notEmpty)
{
KeyValuePair<string, string> current = _dictionaryEnumerator.Current;
return new KeyValuePair<string, string>(current.Key, current.Value);
}
return default(KeyValuePair<string, string>);
}
}
object IEnumerator.Current => Current;
internal Enumerator(Dictionary<string, string>.Enumerator dictionaryEnumerator)
{
_dictionaryEnumerator = dictionaryEnumerator;
_notEmpty = true;
}
public bool MoveNext()
{
if (_notEmpty)
{
return _dictionaryEnumerator.MoveNext();
}
return false;
}
public void Dispose()
{
}
public void Reset()
{
if (_notEmpty)
{
((IEnumerator)_dictionaryEnumerator).Reset();
}
}
}
public static readonly RemoteDebugRequestCookieCollection Empty = new RemoteDebugRequestCookieCollection();
private static readonly string[] EmptyKeys = Array.Empty<string>();
private static readonly Enumerator EmptyEnumerator = default(Enumerator);
private static readonly IEnumerator<KeyValuePair<string, string>> EmptyIEnumeratorType = EmptyEnumerator;
private static readonly IEnumerator EmptyIEnumerator = EmptyEnumerator;
private Dictionary<string, string> Store
{
get;
set;
}
public string this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (Store == null)
{
return null;
}
if (TryGetValue(key, out string value))
{
return value;
}
return null;
}
}
public int Count
{
get
{
if (Store == null)
{
return 0;
}
return Store.Count;
}
}
public ICollection<string> Keys
{
get
{
if (Store == null)
{
return EmptyKeys;
}
return Store.Keys;
}
}
public RemoteDebugRequestCookieCollection()
{
}
public RemoteDebugRequestCookieCollection(Dictionary<string, string> store)
{
Store = store;
}
public RemoteDebugRequestCookieCollection(int capacity)
{
Store = new Dictionary<string, string>(capacity, StringComparer.OrdinalIgnoreCase);
}
public static RemoteDebugRequestCookieCollection Parse(IList<string> values)
{
if (values.Count == 0)
{
return Empty;
}
if (CookieHeaderValue.TryParseList(values, out IList<CookieHeaderValue> parsedValues))
{
if (parsedValues.Count == 0)
{
return Empty;
}
RemoteDebugRequestCookieCollection requestCookieCollection = new RemoteDebugRequestCookieCollection(parsedValues.Count);
Dictionary<string, string> store = requestCookieCollection.Store;
for (int i = 0; i < parsedValues.Count; i++)
{
CookieHeaderValue cookieHeaderValue = parsedValues[i];
string key = Uri.UnescapeDataString(cookieHeaderValue.Name.Value);
string text2 = store[key] = Uri.UnescapeDataString(cookieHeaderValue.Value.Value);
}
return requestCookieCollection;
}
return Empty;
}
public bool ContainsKey(string key)
{
if (Store == null)
{
return false;
}
return Store.ContainsKey(key);
}
public bool TryGetValue(string key, out string value)
{
if (Store == null)
{
value = null;
return false;
}
return Store.TryGetValue(key, out value);
}
public Enumerator GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
return EmptyEnumerator;
}
return new Enumerator(Store.GetEnumerator());
}
IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
return EmptyIEnumeratorType;
}
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
return EmptyIEnumerator;
}
return GetEnumerator();
}
}
}
|
using System;
using System.Linq;
using Fingo.Auth.DbAccess.Models.Statuses;
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.Infrastructure.ExtensionMethods;
using Fingo.Auth.Domain.Models.ProjectModels;
using Fingo.Auth.Domain.Projects.Interfaces;
namespace Fingo.Auth.Domain.Projects.Implementation
{
public class GetProjectWithAll : IGetProjectWithAll
{
private readonly IProjectRepository _projectRepository;
public GetProjectWithAll(IProjectRepository projectRepository)
{
_projectRepository = projectRepository;
}
public ProjectDetailWithAll Invoke(int projectId)
{
var project = _projectRepository.GetById(projectId).WithoutStatuses(ProjectStatus.Deleted);
if (project == null)
throw new ArgumentNullException($"Cannot find project with id={projectId}.");
var users = _projectRepository.GetAllUsersFromProject(projectId)
.WithStatuses(UserStatus.Active , UserStatus.Registered);
var customData = _projectRepository.GetByIdWithCustomDatas(projectId).ProjectCustomData;
var policies = project.ProjectPolicies.Select(pp => pp.Policy).Distinct();
return new ProjectDetailWithAll(project , users , customData , policies);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Models
{
/// <summary>
/// 招聘类
/// </summary>
public class Recruitment1
{
public int PostId { get; set; }
public string PostName { get; set; }
public string PostType { get; set; }
public string PostPlace { get; set; }
public string PostDesc { get; set; }
public string PostRequire { get; set; }
public string Experience { get; set; }//工作经验
public string EduBackground { get; set; }//学历
public int RequireCount { get; set; }//招聘人数
public DateTime PublishTime { get; set; }//发布时间
public string Manager { get; set; }//联系人
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string ltaPostName { get; set; }
}
}
|
using System;
namespace CamelCase
{
public class ConvertToCamelCase
{
public static string toCamelCase(string inputString)
{
string camelCaseString = "";
inputString = inputString.ToLower();
for (int i = 0; i < inputString.Length; i++)
{
char nextChar = inputString[i];
if (nextChar == ' ')
{
nextChar = char.ToUpper(inputString[++i]);
}
camelCaseString += nextChar;
}
return camelCaseString;
}
static void Main(string[] args)
{
Console.WriteLine("CamelCase.ConvertToCamelCase.Main()");
string str = "When in the course of human events.";
Console.WriteLine($"{str} --> {toCamelCase(str)}");
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace sbwilger.DAL.Models
{
public enum Vitals
{
Health,
Mana
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using VEE.Models;
using VEE.Models.BasedeDatos;
using VEE.Util;
namespace VEE.Controllers
{
public class PlanillasController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Planillas
public async Task<ActionResult> Index()
{
return View(await db.Planillas.ToListAsync());
}
// GET: Planillas/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Planilla planilla = await db.Planillas.FindAsync(id);
if (planilla == null)
{
return HttpNotFound();
}
return View(planilla);
}
// GET: Planillas/Create
public ActionResult Create()
{
return View();
}
// POST: Planillas/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(
[Bind(Include = "Id,Nombre,Fecha")] Planilla planilla
, HttpPostedFileBase Foto)
{
if (ModelState.IsValid)
{
var model = new Planilla()
{
Id=planilla.Id,
Fecha = planilla.Fecha,
Nombre = planilla.Nombre,
Foto = Foto.ToByteArray()
};
db.Planillas.Add(model);
var m = new Resultado
{
Id = model.Id,
Fecha = DateTime.Now,
Planilla=model,
Votos = 0
};
db.Resultadoes.Add(m);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(planilla);
}
// GET: Planillas/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Planilla planilla = await db.Planillas.FindAsync(id);
if (planilla == null)
{
return HttpNotFound();
}
return View(planilla);
}
// POST: Planillas/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,Nombre,Fecha,Foto")] Planilla planilla)
{
if (ModelState.IsValid)
{
db.Entry(planilla).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(planilla);
}
// GET: Planillas/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Planilla planilla = await db.Planillas.FindAsync(id);
if (planilla == null)
{
return HttpNotFound();
}
return View(planilla);
}
// POST: Planillas/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Planilla planilla = await db.Planillas.FindAsync(id);
db.Planillas.Remove(planilla);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ingresso.TestePauloRocha.Model
{
[Table("CISA_CINEMA_SALAS")]
public class Cinema_Salas
{
[Key]
public int Cin_Id { get; set; }
public int Sal_Id { get; set; }
public virtual Cinema cinema { get; set; }
public virtual Salas salas { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Leaderboard : MonoBehaviour
{
private int id;
private string playerName;
private int score;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
public string PlayerName
{
get
{
return playerName;
}
set
{
playerName = value;
}
}
public int Score
{
get
{
return score;
}
set
{
score = value;
}
}
public Leaderboard(int id, string playerName, int score)
{
this.Id = id;
this.PlayerName = playerName;
this.Score = score;
}
public Leaderboard()
{
}
public override string ToString()
{
string row = string.Format("Player: {0} Score: {1}", PlayerName, Score);
return row;
}
}
|
using Alabo.Web.Mvc.Attributes;
namespace Alabo.App.Kpis.GradeKpis.Domain.Enum
{
[ClassProperty(Name = "升降类型")]
public enum GradeKpiType
{
/// <summary>
/// 晋升
/// </summary>
PromotedKpi = 1,
/// <summary>
/// 降职
/// </summary>
DemotionKpi = 2
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace RunNerdApp.Models
{
public class TrainingCycleModel
{
[Key]
public string Name { get; set; }
public string GoalDistance { get; set; }
public string GoalTime { get; set; }
public List<TrainingWeekModel> TrainingWeeks { get; set; }
// public string StartDate
// public string EndDate
}
} |
using RestDDD.Application.DTOS;
using RestDDD.Application.Interfaces;
using RestDDD.Application.Interfaces.Mappers;
using RestDDD.Domain.Core.Interfaces.Services;
using System.Collections.Generic;
namespace RestDDD.Application
{
public class ApplicationServiceContato : IApplicationServiceContato
{
private readonly IServiceContato _serviceContato;
private readonly IMappersContato _mapperContato;
public ApplicationServiceContato(IServiceContato serviceContato, IMappersContato mapperContato)
{
_serviceContato = serviceContato;
_mapperContato = mapperContato;
}
public void Add(ContatoDTO contatoDTO)
{
var contato = _mapperContato.MapperDTOtoEntity(contatoDTO);
_serviceContato.Add(contato);
}
public IEnumerable<ContatoDTO> GetAll()
{
var contatos = _serviceContato.GetAll();
return _mapperContato.MapperListContatosDTO(contatos);
}
public ContatoDTO GetById(int id)
{
var contato = _serviceContato.GetById(id);
return _mapperContato.MapperEntityToDTO(contato);
}
/*public void Remove(ContatoDTO clienteDTO)
{
var contato = _mapperContato.MapperDTOtoEntity(clienteDTO);
_serviceContato.Remove(contato);
}*/
public void Remove(int id)
{
//var contato = _mapperContato.MapperDTOtoEntity(clienteDTO);
_serviceContato.Remove(id);
}
public void Update(ContatoDTO contatoDTO)
{
var contato = _mapperContato.MapperDTOtoEntity(contatoDTO);
_serviceContato.Upadate(contato);
}
}
}
|
using UnityEngine;
using System.Collections;
public class EnemyManager : MonoBehaviour {
public GameObject enemyPrefab;
public GameObject explosivePrefab;
private GameObject[] enenmies = new GameObject[3];
private Vector3 originalEnemyPosition = new Vector3(0, -50, 0);
// Use this for initialization
void Start () {
for(int i = 0; i< enenmies.Length; i++)
{
GameObject enemy = (GameObject)Instantiate(enemyPrefab, originalEnemyPosition, Quaternion.identity);
EnemyScript enemyScript = (EnemyScript)enemy.GetComponent("EnemyScript");
ResetEnemy(enemy, enemyScript, true);
enenmies[i] = enemy;
}
}
void startCache () {
}
void ResetEnemy (GameObject enemy, EnemyScript enemyScript, bool isFirstTime){
if(!isFirstTime){
Instantiate(explosivePrefab, enemy.transform.position, Quaternion.identity);
}
enemy.SetActive(false);
enemy.transform.position = originalEnemyPosition;
}
void ActiveEnemy (GameObject enemy, EnemyScript enemyScript){
enemy.SetActive(true);
enemyScript.health = 10;
Vector3 enemyPositon = new Vector3(Random.Range(-30, 30), 0, Random.Range(20, 80));
enemy.transform.position = enemyPositon;
}
// Update is called once per frame
void Update () {
for(int i = 0; i< enenmies.Length; i++)
{
GameObject enemy = enenmies[i];
EnemyScript enemyScript = (EnemyScript)enemy.GetComponent("EnemyScript");
if(enemyScript.health <= 0)
ResetEnemy(enemy, enemyScript, false);
if(!enemy.activeSelf)
ActiveEnemy(enemy, enemyScript);
}
}
}
|
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace Xabe.FFMpeg
{
// ReSharper disable once InconsistentNaming
/// <summary>
/// Base FFMpeg class
/// </summary>
public abstract class FFBase: IDisposable
{
/// <summary>
/// Directory contains FFMpeg and FFProbe
/// </summary>
// ReSharper disable once InconsistentNaming
public static string FFMpegDir;
// ReSharper disable once InconsistentNaming
/// <summary>
/// Path to FFMpeg
/// </summary>
protected string FFMpegPath;
// ReSharper disable once InconsistentNaming
/// <summary>
/// Path to FFProbe
/// </summary>
protected string FFProbePath;
/// <summary>
/// FFMpeg process
/// </summary>
protected Process Process;
/// <summary>
/// Initalize new FFMpeg. Search ffmpeg and ffprobe in PATH
/// </summary>
protected FFBase()
{
if(!string.IsNullOrWhiteSpace(FFMpegDir))
{
FFProbePath = new DirectoryInfo(FFMpegDir).GetFiles()
.First(x => x.Name.Contains("ffprobe"))
.FullName;
FFMpegPath = new DirectoryInfo(FFMpegDir).GetFiles()
.First(x => x.Name.Contains("ffmpeg"))
.FullName;
return;
}
var splitChar = ';';
bool isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
if(isLinux)
splitChar = ':';
string[] paths = Environment.GetEnvironmentVariable("PATH")
.Split(splitChar);
foreach(string path in paths)
{
FindProgramsFromPath(path);
if(FFMpegPath != null &&
FFProbePath != null)
break;
}
if(FFMpegPath == null ||
FFMpegPath == null)
throw new ArgumentException("Cannot find FFMpeg.");
}
/// <summary>
/// Returns true if the associated process is still alive/running.
/// </summary>
public bool IsRunning { get; private set; }
/// <summary>
/// Dispose process
/// </summary>
public void Dispose()
{
Process?.Dispose();
}
private void FindProgramsFromPath(string path)
{
try
{
FFProbePath = new DirectoryInfo(path).GetFiles()
.FirstOrDefault(x => x.Name.StartsWith("ffprobe", true, CultureInfo.InvariantCulture))
?.FullName;
FFMpegPath = new DirectoryInfo(path).GetFiles()
.FirstOrDefault(x => x.Name.StartsWith("ffmpeg", true, CultureInfo.InvariantCulture))
?.FullName;
}
catch(Exception)
{
}
}
/// <summary>
/// Run conversion
/// </summary>
/// <param name="args">Arguments</param>
/// <param name="processPath">Path to executable (ffmpeg, ffprobe)</param>
/// <param name="rStandardInput">Should redirect standard input</param>
/// <param name="rStandardOutput">Should redirect standard output</param>
/// <param name="rStandardError">Should redirect standard error</param>
protected void RunProcess(string args, string processPath, bool rStandardInput = false,
bool rStandardOutput = false, bool rStandardError = false)
{
if(IsRunning)
throw new InvalidOperationException(
"The current FFMpeg process is busy with another operation. Create a new object for parallel executions.");
Process = new Process
{
StartInfo =
{
FileName = processPath,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = rStandardInput,
RedirectStandardOutput = rStandardOutput,
RedirectStandardError = rStandardError
},
EnableRaisingEvents = true
};
Process.Exited += OnProcessExit;
Process.Start();
IsRunning = true;
}
private void OnProcessExit(object sender, EventArgs e)
{
IsRunning = false;
}
/// <summary>
/// Kill ffmpeg process.
/// </summary>
public void Kill()
{
if(IsRunning)
Process.Kill();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class PlayerPosition : MonoBehaviour
{
private PlayerMovement player1;
private CameraMovement camera1;
public Vector2 playerDirection;
public string loadName;
// Start is called before the first frame update
/*
NAME: Start
SYNOPSIS:
Finds the player and tracks the position of the player
DESCRIPTION:
Gets the players position and the camerma position, tracks that position and makes
sure that the camera is in the correct position.
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
void Start()
{
// get current location of player
player1 = FindObjectOfType<PlayerMovement>();
if (player1.startZone == loadName) {
player1.transform.position = transform.position;
player1.lastMove = playerDirection;
// get current location of camera
camera1 = FindObjectOfType<CameraMovement>();
camera1.transform.position = new Vector3(transform.position.x, transform.position.y, camera1.transform.position.z);
}
}
//
/*
NAME: Update
SYNOPSIS:
Update is called once per frame
DESCRIPTION:
Update is called once per frame
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
void Update()
{
}
}
|
using Question.DAL;
using Question.DAL.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuestionForm
{
public partial class LoginForm : Form
{
private readonly MyContext context;
public User UserInstance { get; set; }
public static string log { get; set; }
public LoginForm()
{
context = new MyContext();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string login = tblogin.Text;
string pass = tbpassword.Text;
log = login;
var user = context.Users.FirstOrDefault(x => x.Login == login);
if (user != null)
{
var passwordHash = user.Password;
if (PassHash.Verify(pass, passwordHash))
{
UserInstance = user;
DialogResult = DialogResult.OK;
MessageBox.Show($"Вітаю,{user.Name}");
}
}
else
{
MessageBox.Show("Try again");
}
}
private void buttonRegistration_Click(object sender, EventArgs e)
{
new RegistrationForm().ShowDialog();
}
}
}
|
namespace MvvmLight22
{
using System.Globalization;
using System.Windows.Controls;
using ViewModel;
public class EmailRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var email = ViewModelLocator.Instance.Main.Email;
var repeatEmail = ViewModelLocator.Instance.Main.RepeatEmail;
if (email != repeatEmail)
{
return new ValidationResult(false, "Emails are not identical.");
}
else
{
return ValidationResult.ValidResult;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MergeSort
{
interface IBaseService
{
void ConsoleRun();
}
}
|
using PatientService.CustomException;
using PatientService.Model;
using PatientService.Model.Memento;
using System.Collections.Generic;
using Xunit;
namespace PatientServiceTests.UnitTests
{
public class TherapyDailyDoseTests
{
[Theory]
[MemberData(nameof(Data))]
public void Validation(string doctorJmbg, string doctorName, string doctorSurname, string drugName, int dailyDose, bool valid)
{
if (valid)
new Therapy(new TherapyMemento()
{
DoctorJmbg = doctorJmbg,
DoctorName = doctorName,
DoctorSurname = doctorSurname,
DrugName = drugName,
DailyDose = dailyDose,
});
else
Assert.Throws<ValidationException>(() =>
new Therapy(new TherapyMemento()
{
DoctorJmbg = doctorJmbg,
DoctorName = doctorName,
DoctorSurname = doctorSurname,
DrugName = drugName,
DailyDose = dailyDose,
}));
}
public static IEnumerable<object[]> Data =>
new List<object[]>
{
new object[] { "2711998188734", "Mirko", "Miric", "brufen", -2, false },
new object[] { "2711998188734", "Mirko", "Miric", "brufen", 0, false },
new object[] { "2711998188734", "Mirko", "Miric", "brufen", 1, true },
new object[] { "2711998188734", "Mirko", "Miric", "aspirin", 3, true }
};
}
}
|
using UnityEngine;
using System.Collections;
/*
The ButtonScript script holds a collection of functions which load scenes.
The functions are called when the buttons which call them through their
OnClick function are pressed.
*/
public class ButtonScript : MonoBehaviour {
/*
The MainMenu function opens the MainMenu scene when the button which calls
it through the OnClick function is pressed.
*/
public void MainMenu()
{
Application.LoadLevel ("MainMenu");
}
/*
The Play function opens the First level scene when the button which calls
it through the OnClick function is pressed.
*/
public void Play()
{
Application.LoadLevel ("Level1");
}
/*
The Options function opens the Options scene when the button which calls
it through the OnClick function is pressed.
*/
public void Options()
{
Application.LoadLevel ("Options");
}
/*
The Instructions function opens the Instructions scene when the button which calls
it through the OnClick function is pressed.
*/
public void Instructions()
{
Application.LoadLevel ("Instructions");
}
/*
The Viruses function opens the first Viruses scene when the button which calls
it through the OnClick function is pressed.
*/
public void Viruses()
{
Application.LoadLevel ("Viruses");
}
/*
The Viruses2 function opens the second Viruses scene when the button which calls
it through the OnClick function is pressed.
*/
public void Viruses2()
{
Application.LoadLevel ("Viruses2");
}
/*
The Viruses3 function opens the third Viruses scene when the button which calls
it through the OnClick function is pressed.
*/
public void Viruses3()
{
Application.LoadLevel ("Viruses3");
}
/*
The About function opens the About scene when the button which calls
it through the OnClick function is pressed.
*/
public void About()
{
Application.LoadLevel ("About");
}
/*
The Exit function exits the application when the button which calls
it through the OnClick function is pressed.
*/
public void Exit()
{
Application.Quit();
}
/*
The Restart function reloads the current scene when the button which calls
it through the OnClick function is pressed.
*/
public void Restart()
{
Application.LoadLevel (Application.loadedLevel);
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using OpenCVForUnityExample;
using RSG;
using System.Linq;
using System;
using OpenCVForUnity;
using System.Threading;
/// MobileNet SSD WebCamTexture Example
/// This example uses Single-Shot Detector (https://arxiv.org/abs/1512.02325) to detect objects in a WebCamTexture image.
/// Referring to https://github.com/opencv/opencv/blob/master/samples/dnn/mobilenet_ssd_python.py.
[RequireComponent(typeof(WebCamTextureToMatHelper))]
[RequireComponent(typeof(ObjectDetector))]
public class VCameraDetector : MonoBehaviour {
public int DetectionFrameRate = 100;
private float DetectionPeriod;
private WebCamTextureToMatHelper VCameraHelper;
private bool Initialized = false;
// RGB camera matrix
private Mat CameraMat;
private Mat CroppedCameraMat;
private Mat InputMat;
private OpenCVForUnity.Rect CropRegionRect;
private CroppedScaledRegion CropRegion;
private int XStart;
private int YStart;
private int CropSize;
public int Width { get; private set; }
public int Height { get; private set; }
public SizedRegion SizedRegion {
get {
return new SizedRegion(Width, Height);
}
}
#if UNITY_ANDROID && !UNITY_EDITOR
float rearCameraRequestedFPS;
#endif
private ObjectDetector Detector;
private bool DetectorReady = true;
private float TimeSinceLastDetect = float.PositiveInfinity;
public Dictionary<COCOCategories, List<DetectResult<COCOCategories>>> LastResults = new Dictionary<COCOCategories, List<DetectResult<COCOCategories>>>();
public void Awake() {
Detector = GetComponent<ObjectDetector>();
VCameraHelper = GetComponent<WebCamTextureToMatHelper>();
}
public void Start() {
VCameraHelper.onInitialized.AddListener(OnVCameraHelperInitialized);
VCameraHelper.onDisposed.AddListener(OnVCameraHelperDisposed);
//VCameraHelper.onErrorOccurred.AddListener(OnVCameraHelperErrorOccurred);
DetectionPeriod = 1.0f / DetectionFrameRate;
InputMat = new Mat(Detector.Size, Detector.Size, CvType.CV_8UC3);
VCameraHelper.Initialize();
}
/// Raises the webcam texture to mat helper initialized event.
public void OnVCameraHelperInitialized() {
Width = VCameraHelper.GetWidth();
Height = VCameraHelper.GetHeight();
CameraMat = new Mat(Height, Width, CvType.CV_8UC3);
int centerX = Width / 2;
int centerY = Height / 2;
//Debug.Log("ROWS: " + Height + ", COLS: " + Width);
CropSize = Mathf.Min(Height, Width);
//Debug.Log("Crop size: " + CropSize);
XStart = Mathf.Max(0, centerX - CropSize / 2);
YStart = Mathf.Max(0, centerY - CropSize / 2);
//Debug.Log("XStart: " + XStart + ", YStart: " + YStart);
CropRegionRect = new OpenCVForUnity.Rect(XStart, YStart, CropSize, CropSize);
CroppedCameraMat = new Mat(CropSize, CropSize, CvType.CV_8UC3);
CropRegion =
new CroppedScaledRegion(
Width, Height,
new Box(XStart, YStart, XStart + CropSize, YStart + CropSize),
Detector.Size, Detector.Size
);
Initialized = true;
}
/// Raises the webcam texture to mat helper disposed event.
public void OnVCameraHelperDisposed() {
if (CameraMat != null) {
CameraMat.Dispose();
}
}
/// Raises the webcam texture to mat helper error occurred event.
public void OnVCameraHelperErrorOccurred(WebCamTextureToMatHelper.ErrorCode errorCode) {
Debug.Log("OnWebCamTextureToMatHelperErrorOccurred " + errorCode);
}
private void DoDetection() {
if (Initialized) {
//Debug.Log("Doing detection");
DetectorReady = false;
TimeSinceLastDetect = 0.0f;
Mat rgbaMat = VCameraHelper.GetMat();
// Remove the alpha channel
Imgproc.cvtColor(rgbaMat, CameraMat, Imgproc.COLOR_RGBA2RGB);
//Debug.Log("Cropping image");
// Crop the image to obtain a square shaped region
Mat croppedRef = new Mat(CameraMat, CropRegionRect);
croppedRef.copyTo(CroppedCameraMat);
croppedRef.Dispose();
//Debug.Log("Resizing image");
// Resize the image to fit the detector
Imgproc.resize(CroppedCameraMat, InputMat, new Size(Detector.Size, Detector.Size));
int frameId = Time.frameCount;
//Debug.Log("Sending detection request");
// Start the detection
Detector.Detect(InputMat).Done((categorizedBoxes) => {
var newDict = new Dictionary<COCOCategories, List<DetectResult<COCOCategories>>>();
foreach (KeyValuePair<COCOCategories, List<DetectResult<COCOCategories>>> categoryInfo in categorizedBoxes) {
var detections = new List<DetectResult<COCOCategories>>();
foreach (DetectResult<COCOCategories> detectResult in categoryInfo.Value) {
Box b = CropRegion.InverseTransform(detectResult.Box).Clamp(Width - 1, Height - 1);
var remappedDetectResult = new DetectResult<COCOCategories>(detectResult.Category, detectResult.Score, b, SizedRegion, frameId);
detections.Add(remappedDetectResult);
}
if (detections.Count > 0) {
newDict[categoryInfo.Key] = detections;
}
}
LastResults = newDict;
DetectorReady = true;
});
}
}
public void Update() {
TimeSinceLastDetect += Time.time;
if (DetectorReady && TimeSinceLastDetect > DetectionPeriod) {
DoDetection();
}
}
public void OnDestroy() {
VCameraHelper.Dispose();
Utils.setDebugMode(false);
VCameraHelper.onInitialized.RemoveListener(OnVCameraHelperInitialized);
VCameraHelper.onDisposed.RemoveListener(OnVCameraHelperDisposed);
//VCameraHelper.onErrorOccurred.RemoveListener(OnVCameraHelperErrorOccurred);
}
/// Raises the change camera button click event.
public void OnChangeCameraButtonClick() {
#if UNITY_ANDROID && !UNITY_EDITOR
if (!VCameraHelper.IsFrontFacing ()) {
rearCameraRequestedFPS = VCameraHelper.requestedFPS;
VCameraHelper.Initialize (!VCameraHelper.IsFrontFacing (), 15, VCameraHelper.rotate90Degree);
} else {
VCameraHelper.Initialize (!VCameraHelper.IsFrontFacing (), rearCameraRequestedFPS, VCameraHelper.rotate90Degree);
}
#else
VCameraHelper.requestedIsFrontFacing = !VCameraHelper.IsFrontFacing();
#endif
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorWPF
{
public class CalculatorModel
{
public string firstValue;
public string secondValue;
public string chosenOperator;
public double firstValueParsed;
public double secondValueParsed;
public double? result;
Operator op;
public CalculatorModel(string firstValue, string secondValue, string chosenOperator)
{
this.firstValue = firstValue;
this.secondValue = secondValue;
this.chosenOperator = chosenOperator;
}
public double calculateValue()
{
op = Factory.getOperator(chosenOperator);
this.firstValueParsed = parseInput(firstValue);
this.secondValueParsed = parseInput(secondValue);
double result = op.result(firstValueParsed, secondValueParsed);
return result;
}
public double parseInput(string inputValue)
{
return Double.Parse(inputValue);
}
public bool isValidOperand(string operand)
{
bool isParsable = false;
double value;
isParsable = Double.TryParse(operand, out value);
return isParsable;
}
public bool isValidOperator(string chosenOperator)
{
if (chosenOperator.Equals("+") || chosenOperator.Equals("-") || chosenOperator.Equals("*") || chosenOperator.Equals("/") || chosenOperator.Equals("^"))
{
return true;
}
return false;
}
}
}
|
// Copyright (c) Christopher Clayton. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace praxicloud.core.metrics.simpleprovider
{
#region Using Clauses
using System.Threading;
using System.Threading.Tasks;
#endregion
/// <summary>
/// A metric that can be notified to invoke a callback
/// </summary>
public interface ISimpleMetricWriter
{
#region Methods
/// <summary>
/// A writer that is called each time the metric is to be written
/// </summary>
/// <param name="name">The name of the metric</param>
/// <param name="userState">A user state object that was provided to the provider</param>
/// <param name="labels">The labels associated with the metric</param>
/// <param name="value">The value that the metric is currently at</param>
/// <param name="cancellationToken">A token to monitor for abort requests</param>
public abstract Task MetricWriterSingleValueAsync(object userState, string name, string[] labels, double? value, CancellationToken cancellationToken);
/// <summary>
/// A writer that is called each time the metric is to be written
/// </summary>
/// <param name="name">The name of the metric</param>
/// <param name="userState">A user state object that was provided to the provider</param>
/// <param name="labels">The labels associated with the metric</param>
/// <param name="count">The number of values</param>
/// <param name="maximum">The maximum value</param>
/// <param name="mean">The average value using a mean aggregation</param>
/// <param name="minimum">The minimum value</param>
/// <param name="p50">The 50th percentile</param>
/// <param name="p90">The 90th percentile</param>
/// <param name="p95">The 95th percentile</param>
/// <param name="p98">The 98th percentile</param>
/// <param name="p99">The 99th percentile</param>
/// <param name="standardDeviation">The standard deviation</param>
/// <param name="cancellationToken">A token to monitor for abort requests</param>
public abstract Task MetricWriterSummaryAsync(object userState, string name, string[] labels, int? count, double? minimum, double? maximum, double? mean, double? standardDeviation, double? p50, double? p90, double? p95, double? p98, double? p99, CancellationToken cancellationToken);
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Journey.WebApp.Data;
using Journey.WebApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Journey.WebApp.Controllers
{
public class AlbumController : Controller
{
private readonly JourneyDBContext _context;
private HttpClient _httpClient;
private Options _options;
public AlbumController(JourneyDBContext context, HttpClient httpClient, Options options)
{
_context = context;
_httpClient = httpClient;
_options = options;
}
public async Task<IActionResult> Index()
{
var travelerId = (int)TempData.Peek("TravelerID");
var albumList = await _context.TravelerAlbum.Where(ta => ta.TravelerId == travelerId).ToListAsync();
return View(albumList);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(TravelerAlbum travelerAlbum)
{
if (ModelState.IsValid)
{
travelerAlbum.TravelerId = (int)TempData.Peek("TravelerID");
travelerAlbum.DateCreated = DateTime.Now;
_context.Add(travelerAlbum);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return PartialView(travelerAlbum);
}
public async Task<IActionResult> Photos(long? id)
{
var photosList = await _context.AlbumPhoto.Include(ap => ap.Photo)
.Where(ta => ta.AlbumId == id).ToListAsync();
ViewBag.albumId = id;
return View(photosList);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Photos(long? id, PhotoViewModel photo)
{
if (ModelState.IsValid)
{
var p = await MyUtility.UploadPhoto(_context, _httpClient, _options, photo.Upload, (long)id);
var album = await _context.TravelerAlbum.FindAsync(id);
p.PhotoName = photo.AlbumPhoto.Photo.PhotoName;
p.Loc = photo.AlbumPhoto.Photo.Loc;
album.Thumbnail = p.Thumbnail;
_context.Update(album);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Photos));
}
return PartialView(photo);
}
}
} |
using UnityEngine;
public interface IBlockView
{
void BindViewModel(IBlockViewModel viewModel);
void AddProduct(Transform transform);
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace NewsProject.Shared.Models
{
public class Image
{
public int Id { get; set; }
public string Name { get; set; }
public string Picture { get; set; }
[Required]
public DateTime? DateOfUpload { get; set; }
public List<DatabaseImages> DatabaseImages { get; set; } = new List<DatabaseImages>();
[NotMapped]
public string ImagesCharacter { get; set; }
public override bool Equals(object obj)
{
if (obj is Image p2)
{
return Id == p2.Id;
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using IRAP.Global;
namespace IRAP.Interface
{
public class TSoftlandRowSet
{
public virtual XmlNode GenerateXMLNode(XmlNode node)
{
return IRAPXMLUtils.GenerateXMLAttribute(node, this);
}
}
} |
using Assets.Scripts;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
/// <summary>
/// Manager for game lever, sets and create every level attributes
/// </summary>
public class LevelManager : SingletonInstance<LevelManager>
{
[SerializeField]
private CameraMovement _cameraMovement;
[SerializeField]
private List<GameObject> _levelCollection;
[SerializeField]
private Transform _map;
private string[] _currentLvl;
private Point _simplePortPosition;
private List<Vector3> _pathPoints = new List<Vector3>();
[SerializeField]
private GameObject _simplePortalPrefab;
/// <summary>
/// Gets created a path for monster
/// </summary>
public List<Vector3> Path { get; private set; }
/// <summary>
/// Gets a map tiles to create a map
/// </summary>
public Dictionary<Point, TileScript> Tiles { get; set; }
/// <summary>
/// Gets a spawn portal
/// </summary>
public PortalSpawn RatPortal { get; set; }
public float TileSizeX =>
_levelCollection[0].GetComponent<SpriteRenderer>().bounds.size.x;
// Start is called before the first frame update
void Start()
{
CreateLevel();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("escape"))
{
Application.Quit();
}
}
private void CreateLevel()
{
Tiles = new Dictionary<Point, TileScript>();
_currentLvl = ReadLevelData();
var maxTile = Vector3.zero;
var wrt = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height));
for (int y = 0; y < _currentLvl.Length; y++)
{
for (int x = 0; x < _currentLvl[y].Length; x++)
{
PlaceTitle(_currentLvl[y][x], x, y, wrt);
}
}
maxTile = Tiles.Last().Value.transform.position;
_cameraMovement.SetLimits(new Vector3(maxTile.x + TileSizeX, maxTile.y - TileSizeX));
GenerateMonsterPath();
PortalSpawn();
}
private void PlaceTitle(char levelInfo, int x, int y, Vector3 wrt)
{
var parsedTitle = int.Parse(levelInfo.ToString());
TileScript nTile = Instantiate(_levelCollection[parsedTitle]).GetComponent<TileScript>();
var p = new Point(x, y);
var v = new Vector3(wrt.x + (TileSizeX * x), wrt.y - (TileSizeX * y), 0);
nTile.Setup(_map, p, v);
if (parsedTitle != 0)
{
if (_pathPoints.Count == 0)
_simplePortPosition = p;
_pathPoints.Add(v);
}
}
private string[] ReadLevelData()
{
var levelData = Resources.Load("level") as TextAsset;
return levelData.text.Replace(Environment.NewLine, string.Empty).Split('-');
}
private void PortalSpawn()
{
var fp = _pathPoints.FirstOrDefault();
GameObject portal = Instantiate(_simplePortalPrefab, Tiles[_simplePortPosition]
.GetComponent<TileScript>().WorldPos, Quaternion.identity);
RatPortal = portal.GetComponent<PortalSpawn>();
RatPortal.name = "RatPortal";
}
public void GenerateMonsterPath()
{
var tempPath = _pathPoints.ToList();
var fixedPath = new List<Vector3>() { tempPath[0] };
tempPath.RemoveAt(0);
var directions = new List<Vector3>();
do
{
float prevLen = float.MaxValue;
int loopIdx = 0;
for (int i = 0; i < tempPath.Count; i++)
{
var lastP = fixedPath.Last();
var curP = tempPath[i];
var len = GetLenght(lastP, curP);
if (prevLen > len)
{
prevLen = len;
loopIdx = i;
}
}
fixedPath.Add(tempPath[loopIdx]);
tempPath.Remove(tempPath[loopIdx]);
} while (tempPath.Count != 0);
for (int i = 1; i < fixedPath.Count; i++)
{
var v = fixedPath[i] - fixedPath[i - 1];
v = new Vector3(v.x, v.y, v.z);
directions.Add(v);
}
Path = directions;
}
private float GetLenght(Vector3 a, Vector3 b)
{
var xSub = (a.x - b.x);
var ySub = (a.y - b.y);
return (float)Math.Sqrt((xSub * xSub) + (ySub * ySub));
}
}
|
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.AccountEntity;
using Anywhere2Go.DataAccess.Object;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.Business.Accounting
{
public class ServiceTypeLogic
{
private static readonly ILog logger =
LogManager.GetLogger(typeof(ServiceTypeLogic));
private MyContext _context = null;
public ServiceTypeLogic()
{
_context = new MyContext(Configurator.CrmAccountingConnection);
}
public ServiceTypeLogic(MyContext context)
{
_context = context;
}
public List<ServiceType> GetServiceTypes()
{
var repository = new Repository<ServiceType>(_context);
var query = repository.GetQuery().Where(t => t.IsActive).OrderBy(o => o.Sort).ThenBy(o => o.ServiceTypeName);
return query.ToList();
}
public double GetDefaultPercentByServiceType(SyncServiceType serviceType)
{
int serviceTypeCar = 2;
int serviceTypeCarUnitPrice = 4;
int serviceTypeCopy = 7;
int serviceTypeCopyUnitPrice = 25;
if (serviceType.IsCalPercent)
{
return 5;
}
else if(serviceType.ServiceTypeId == serviceTypeCar)
{
return serviceTypeCarUnitPrice;
}
else if (serviceType.ServiceTypeId == serviceTypeCopy)
{
return serviceTypeCopyUnitPrice;
}
return 0;
}
public List<SyncServiceType> GetAPIServiceTypes(DateTime? lastSyncedDateTime)
{
var repository = new Repository<ServiceType>(_context);
if (lastSyncedDateTime == null)
{
var data = repository.GetQuery().Where(t => t.IsActive == true)
.Select(t => new SyncServiceType
{
DefaultPercent = 0,
IsActive = t.IsActive,
IsCalPercent = t.IsCalPercent,
ServiceTypeId = t.ServiceTypeId,
ServiceTypeName = t.ServiceTypeName,
Sort = t.Sort
})
.ToList();
return data.Select(t => new SyncServiceType
{
DefaultPercent = GetDefaultPercentByServiceType(t),
IsActive = t.IsActive,
IsCalPercent = t.IsCalPercent,
ServiceTypeId = t.ServiceTypeId,
ServiceTypeName = t.ServiceTypeName,
Sort = t.Sort
}).ToList();
}
else
{
var data = repository.GetQuery()
.Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value)
.OrderBy(x => (x.UpdateDate ?? x.CreateDate))
.Select(t => new SyncServiceType
{
DefaultPercent = 0,
IsActive = t.IsActive,
IsCalPercent = t.IsCalPercent,
ServiceTypeId = t.ServiceTypeId,
ServiceTypeName = t.ServiceTypeName,
Sort = t.Sort
})
.ToList();
return data.Select(t => new SyncServiceType
{
DefaultPercent = GetDefaultPercentByServiceType(t),
IsActive = t.IsActive,
IsCalPercent = t.IsCalPercent,
ServiceTypeId = t.ServiceTypeId,
ServiceTypeName = t.ServiceTypeName,
Sort = t.Sort
}).ToList();
}
}
public BaseResult<int> GetServiceTypePercentById(int serviceTypeId)
{
BaseResult<int> res = new BaseResult<int>();
var repository = new Repository<ServiceType>(_context);
var query = repository.GetQuery().Where(t => t.IsActive && t.ServiceTypeId== serviceTypeId);
res.Result = query.FirstOrDefault().Sort;
return res;
}
}
} |
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace TalebiAPI.Domain
{
internal class SingleResponse<T>
{
internal SingleResponse()
{
}
public SingleResponse(T data, HttpStatusCode httpStatusCode)
{
Data = data;
StatusCode = httpStatusCode;
}
public SingleResponse(string errorMessage, HttpStatusCode httpStatusCode)
{
HasError = true;
ErrorMessage = errorMessage;
StatusCode = httpStatusCode;
}
public bool HasError { get; set; }
public string ErrorMessage { get; set; }
public string Message { get; set; }
public T Data { get; set; }
public HttpStatusCode StatusCode { get; set; }
}
//public static class ApiExtensionMethods
//{
// public static ActionResult ToHttpResponse<TModel>(this SingleResponse<TModel> response)
// {
// var objectResult = new ObjectResult(response)
// {
// StatusCode = ((int)response.StatusCode > 0) ? (int)response.StatusCode : StatusCodes.Status200OK
// };
// return objectResult;
// }
//}
} |
using Tweetinvi;
namespace TwitCreds
{
public class TwitHelper
{
static bool twitCredsAreSet = false;
public static void SetCreds()
{
if (twitCredsAreSet) return;
twitCredsAreSet = true;
Auth.SetUserCredentials(TwitCreds.Settings.CONSUMER_KEY, TwitCreds.Settings.CONSUMER_SECRET,
TwitCreds.Settings.ACCESS_TOKEN, TwitCreds.Settings.ACCESS_TOKEN_SECRET);
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
}
}
}
|
using Xunit;
namespace Problem1.Test
{
[CollectionDefinition(COLLECTION_NAME)]
public class TripCardTestCollection : ICollectionFixture<TripCardFixture>
{
internal const string COLLECTION_NAME = "Тесты упорядочения карточек путешествий";
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
// See https://xunit.github.io/docs/shared-context.html for details.
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Decorator
{
class MemStream : IStream
{
public String GetBuffer(String aBuffer)
{
return aBuffer;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using static InputManager;
public class InputSender : MonoBehaviour {
public GameObject[] targets = new GameObject[1];
public InputType[] inputTypes = new InputType[1];
public DebugAndTest debug;
void Start () {
}
void OnValidate () {
if (debug.send) {
debug.send = false;
SendInput (targets, new InputType[] { debug.inputType }, ref debug.log, true);
}
}
void Update () {
if (debug.enableLog) {
SendInput (targets, inputTypes, ref debug.log);
} else {
SendInput (targets, inputTypes);
debug.log = "";
}
}
public static void SendInput (GameObject[] targets, InputType[] inputTypes, ref string log, bool forceSend = false) {
if (targets.Length > 0) {
string logTemp = "";
int count = 0;
bool isInput = forceSend?true : false;
foreach (InputType ty in inputTypes) {
bool keydown = Input.GetKeyDown (keyMap[ty]);
bool keyup = Input.GetKeyUp (keyMap[ty]);
if (Input.GetKeyDown (keyMap[ty])) {
isInput = true;
break;
}
if (Input.GetKeyUp (keyMap[ty])) {
isInput = true;
break;
}
}
if (isInput) {
GameObject[] activeObjs = FilterActives (targets);
logTemp += "active objects:" + activeObjs.Count () + "\n";
List<InputReceiver> enableComs = getAllEnableReceivers (activeObjs);
logTemp += "enable components:" + enableComs.Count () + "\n";
foreach (InputType ty in inputTypes) {
int num = 0;
enableComs.ForEach (com => {
Array.ForEach (com.eventSetup, e => {
if (e.inputType == ty) {
if (!forceSend) {
bool keydown = Input.GetKeyDown (keyMap[ty]);
if (keydown) {
e.keyDown.Invoke ();
num += 1;
count += 1;
}
bool keyup = Input.GetKeyUp (keyMap[ty]);
if (keyup) e.keyUp.Invoke ();
} else {
e.keyDown.Invoke ();
num += 1;
count += 1;
e.keyUp.Invoke ();
}
}
});
});
if (num > 0) {
logTemp += ty + " success send:" + num + "\n";
}
}
log = count > 0 ? logTemp : log;
}
}
}
public static void SendInput (GameObject[] targets, InputType[] inputTypes) {
string s = "";
SendInput (targets, inputTypes, ref s);
}
public static GameObject[] FilterActives (GameObject[] objectArray) {
return Array.FindAll (objectArray, ob => {
if (ob != null) {
if (ob.activeSelf) {
return true;
} else return false;
} else return false;
});
}
public static List<InputReceiver> getAllEnableReceivers (GameObject[] enableObjs) {
List<InputReceiver> enableComs = new List<InputReceiver> ();
Array.ForEach (enableObjs, ob => {
List<InputReceiver> results = ob.GetComponents<InputReceiver> ().ToList ().FindAll (x => x.enabled);
enableComs.AddRange (results);
});
return enableComs;
}
[Serializable]
public class DebugAndTest {
public bool send;
public bool enableLog;
public InputType inputType;
[Multiline (5)]
public string log;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
namespace SingletonDemo
{
//Singleton Pattern:
//Only one intsance will be used throught application lifecycle in 1 session
//sealed will stop any other extension sub classes.No one can inherit Cart.
public sealed class Cart
{
//properties
public List<Item> Items { get; set; }
public decimal AmountToPay { get; set; }
public decimal Total { get; set; }
/*Way2: private decimal _total;
public decimal Total{
get{return _total;}
private set{_total=getTotal();}
}
*/
//Implement Singleton
static Cart cart;
//stop from creating instance of class
private Cart()
{
Items = new List<Item>();
}
//give only one instance when getCart called
public static Cart getCart()
{
if (cart == null)//it will be null only if object is not created yet i.e. at the start of app
{
cart = new Cart();
}
Console.WriteLine($"from getCart:Count of Items{cart.Items.Count}");
return cart;
}
/*Way2:public static decimal getTotal()
{ Cart Tcart=Cart.getCart();
decimal sumtotal=0.00M;
foreach(Item item in Tcart.Items)
{
sumtotal+=item.Price;
}
Console.WriteLine($"from getTotal:Count of Items{Tcart.Items.Count}");
return sumtotal;
}*/
}
} |
using System.Windows.Forms;
using System.Drawing;
public class Player
{
//当前角色
public static int current_player = 0;
//行走
public int x = 0;
public int y = 0;
public int face = 1;
public int anm_frame = 1;
public long last_walk_time = 0;
public long walk_interval = 100;
public int speed = 20;
public Bitmap bitmap;
public int x_offset = -48; //位置调整
public int y_offset = -90;
//是否激活
public int is_active = 0;
//碰撞射线长度
public int collision_ray = 50;
//主角状态
public enum Status
{
WALK = 1,
PANEL = 2,
TASK = 3,
FIGHT = 4,
}
public static Status status = Status.WALK;
//鼠标操作
public static int target_x = -1;
public static int target_y = -1;
//鼠标单击位置
public static Bitmap move_flag; //标记图片
public static long FLAG_SHOW_TIME = 3000; //标记时间
public static long flag_start_time = 0; //开始显示时间
//物品,技能,状态栏
public int max_hp = 100;
public int hp = 100;
public int max_mp = 100;
public int mp = 100;
public int attack = 10;
public int defense = 10;
public int fspeed = 10;
public int fortune = 10;
public int equip_att = -1; //武器id
public int equip_def = -1; //防具id
public static int select_player = 0;
public Bitmap status_bitmap; //状态面板图像
public int[] skill = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //技能数组
public static int money = 200;
//战斗
public Bitmap fbitmap; //战斗图
public int fx_offset = -120; //用于确定fbitmap的位置
public int fy_offset = -120;
public Bitmap fface; //角色面部图
public Animation anm_att; //攻击动画
public Animation anm_item; //物品动画
public Animation anm_skill; //技能动画
public string name = "";
public Player()
{
bitmap = new Bitmap(@"role/r1.png");
bitmap.SetResolution(96,96);
move_flag = new Bitmap(@"ui/move_flag.png");
bitmap.SetResolution(96,96);
}
//简化操控key_ctrl, 整理为walk, 减少重复代码
public static void walk(Player[] player, Map[] map, Comm.Direction direction)
{
Player p = player[current_player];
//转向
p.face = (int)direction;
//间隔判定
if (Comm.Time() - p.last_walk_time <= p.walk_interval)
return;
//移动处理
if (direction == Comm.Direction.UP && Map.can_through(map, p.x, p.y - p.speed)) //up //加上判断目标位置是否可以通行
p.y = p.y - p.speed;
else if (direction == Comm.Direction.DOWN && Map.can_through(map, p.x, p.y + p.speed)) //down //行走速度由speed控制
p.y = p.y + p.speed;
else if (direction == Comm.Direction.LEFT && Map.can_through(map, p.x - p.speed, p.y)) //left
p.x = p.x - p.speed;
else if (direction == Comm.Direction.RIGHT && Map.can_through(map, p.x + p.speed, p.y)) //right
p.x = p.x + p.speed;
else return;
//动画帧
p.anm_frame = p.anm_frame + 1;
if (p.anm_frame >= int.MaxValue) p.anm_frame = 0; //超出上限的处理
//时间
p.last_walk_time = Comm.Time();
}
//-----------------------------------------------------------------
// 操控
//-----------------------------------------------------------------
public static void key_ctrl(Player[] player,Map[] map,Npc[] npc,KeyEventArgs e)
{
Player p=player[current_player];
if (Player.status != Status.WALK)
return;
//切换角色
if (e.KeyCode == Keys.Tab) { key_change_player(player); }
/* //是否转向 //先处理转向在处理行走
if (e.KeyCode == Keys.Up && p.face != 4)
p.face = 4;
else if (e.KeyCode == Keys.Down && p.face != 1)
p.face = 1;
else if (e.KeyCode == Keys.Left && p.face != 2)
p.face = 2;
else if (e.KeyCode == Keys.Right && p.face != 3)
p.face = 3;
//间隔判定
if (Comm.Time() - p.last_walk_time <= p.walk_interval)
return;
//移动处理
if (e.KeyCode == Keys.Up&&Map.can_through(map,p.x,p.y-p.speed)) //加上判断目标位置是否可以通行
p.y = p.y - p.speed;
else if (e.KeyCode == Keys.Down && Map.can_through(map, p.x, p.y + p.speed)) //行走速度由speed控制
p.y = p.y + p.speed;
else if (e.KeyCode == Keys.Left && Map.can_through(map, p.x - p.speed, p.y))
p.x = p.x - p.speed;
else if (e.KeyCode == Keys.Right && Map.can_through(map, p.x + p.speed, p.y))
p.x = p.x + p.speed;
else return;
//动画帧
p.anm_frame = p.anm_frame + 1;
if (p.anm_frame >= int.MaxValue) p.anm_frame = 0; //超出上限的处理
//时间
p.last_walk_time = Comm.Time();
*/
//行走
if (e.KeyCode == Keys.Up)
{
walk(player,map,Comm.Direction.UP);
}
else if (e.KeyCode == Keys.Down)
{
walk(player,map,Comm.Direction.DOWN);
}
else if (e.KeyCode == Keys.Left)
{
walk(player, map, Comm.Direction.LEFT);
}
else if (e.KeyCode == Keys.Right)
{
walk(player, map, Comm.Direction.RIGHT);
}
else if (e.KeyCode == Keys.Escape)
{
StatusMenu.show();
Task.block();
}
//npc碰撞
npc_collision(player,map,npc,e);
}
public static void key_ctrl_up(Player[] player, KeyEventArgs e)
{
/* Player p=player[current_player];
//动画帧
p.anm_frame = 0;
p.last_walk_time = 0;
*/
stop_walk(player);
}
public static void draw(Player[] player,Graphics g,int map_sx,int map_sy)
{
Player p=player[current_player];
Rectangle crazycoderRgl = new Rectangle(p.bitmap.Width / 4 * (p.anm_frame% 4), p.bitmap.Height / 4 * (p.face - 1), p.bitmap.Width / 4, p.bitmap.Height / 4);//定义区域
Bitmap bitmap0 = p.bitmap.Clone(crazycoderRgl, p.bitmap.PixelFormat);//复制小图
g.DrawImage(bitmap0, p.x+map_sx+p.x_offset, p.y+map_sy+p.y_offset);
}
//-------------------------------------------------------------------
// 切换角色
//-------------------------------------------------------------------
public static void key_change_player(Player[] player)
{
for(int i=current_player+1;i<player.Length;i++)
if (player[i].is_active == 1)
{
set_player(player,current_player,i);
return;
}
for(int i=0;i<current_player;i++)
if (player[i].is_active == 1)
{
set_player(player,current_player,i);
return;
}
}
public static void set_player(Player[] player, int oldindex, int newindex)//3个参数分别表示玩家数组player,旧的可控角色索引oldindex,新的可控角色索引newindex
{
current_player = newindex;
player[newindex].x = player[oldindex].x;
player[newindex].y= player[oldindex].y;
player[newindex].face = player[oldindex].face;
}
//位置设置
public static void set_pos(Player[] player, int x, int y, int face)
{
player[current_player].x = x;
player[current_player].y = y;
player[current_player].face = face;
}
public static int get_pos_x(Player[] player)//横坐标
{
return player[current_player].x;
}
public static int get_pos_y(Player[] player)//纵坐标
{
return player[current_player].y;
}
public static int get_pos_f(Player[] player)//面向
{
return player[current_player].face;
}
//根据角色方向计算碰撞射线终点
public static Point get_collision_point(Player[] player)
{
Player p=player[current_player];
int collision_x = 0;
int collision_y = 0;
if (p.face == (int)Comm.Direction.UP) //上
{
collision_x = p.x;
collision_y = p.y - p.collision_ray;
}
if (p.face == (int)Comm.Direction.DOWN) //下
{
collision_x = p.x;
collision_y = p.y + p.collision_ray;
}
if (p.face == (int)Comm.Direction.LEFT) //左
{
collision_x = p.x-p.collision_ray;
collision_y = p.y;
}
if (p.face == (int)Comm.Direction.RIGHT) //右
{
collision_x = p.x + p.collision_ray;
collision_y = p.y;
}
return new Point(collision_x,collision_y);
}
//处理角色与npc碰撞
public static void npc_collision(Player[] player, Map[] map, Npc[] npc, KeyEventArgs e)
{
Player p=player[current_player]; //碰撞射线的端点
Point p1 = new Point(p.x,p.y);
Point p2 = get_collision_point(player);
for (int i = 0; i < npc.Length; i++) //遍历NPC
{
if (npc[i] == null)
continue;
if (npc[i].map != Map.current_map)
continue;
if (npc[i].is_line_collision(p1, p2)) //发生碰撞
{
if (npc[i].collision_type == Npc.Collosion_type.ENTER) //碰撞触发
{
Task.story(i);
break;
}
else if (npc[i].collision_type == Npc.Collosion_type.KEY) //按键触发
{
if (e.KeyCode == Keys.Space || e.KeyCode == Keys.Enter)
{
Task.story(i);
break;
}
}
}
}
}
public static int is_reach_x(Player[] player, int target_x) //横坐标
{
Player p=player[current_player];
if (p.x - target_x > p.speed / 2) return 1;
if (p.x - target_x < -p.speed / 2) return -1;
return 0;
}
public static int is_reach_y(Player[] player, int target_y)
{
Player p=player[current_player];
if (p.y - target_y > p.speed / 2) return 1;
if (p.y - target_y < -p.speed / 2) return -1;
return 0;
}
//角色处于行走状态且玩家按下鼠标左键,设置目标坐标
public static void mouse_click(Map[] map, Player[] player, Rectangle stage, MouseEventArgs e)
{
if (Player.status != Status.WALK)
return;
if (e.Button == MouseButtons.Left)
{
target_x = e.X - Map.get_map_sx(map,player,stage);
target_y = e.Y - Map.get_map_sy(map, player, stage);
flag_start_time = Comm.Time();
}
else if (e.Button == MouseButtons.Right) //鼠标右键弹出面板
{
StatusMenu.show();
Task.block();
}
}
//处理角色的定时逻辑
public static void timer_logic(Player[] player, Map[] map)
{
move_logic(player,map);
}
//处理角色行走的方法
public static void move_logic(Player[] player, Map[] map)
{
if (target_x < 0 || target_y < 0)
return;
step_to(player,map,target_x,target_y);
}
public static void stop_walk(Player[] player)
{
Player p=player[current_player];
//动画帧
p.anm_frame = 0;
p.last_walk_time = 0;
//目标位置
target_x = -1;
target_y = -1;
}
//行走算法
public static void step_to(Player[] player, Map[] map, int target_x, int target_y)
{
if (is_reach_x(player, target_x) == 0 && is_reach_y(player, target_y) == 0) //判断是否到达目的地
{
stop_walk(player);
return;
}
Player p=player[current_player];
if (is_reach_x(player, target_x) > 0 && Map.can_through(map, p.x - p.speed, p.y)) //能否往x方向行走(左)
{ //行走
walk(player,map,Comm.Direction.LEFT);
return;
}
else if (is_reach_x(player, target_x) < 0 && Map.can_through(map, p.x + p.speed, p.y)) //能否往x反方向行走(右)
{
walk(player,map,Comm.Direction.RIGHT);
return;
}
else if (is_reach_y(player, target_y) > 0 && Map.can_through(map, p.x, p.y - p.speed)) //能否往y正方向行走(上)
{
walk(player, map, Comm.Direction.UP);
return;
}
else if (is_reach_y(player, target_y) < 0 && Map.can_through(map, p.x, p.y + p.speed)) //能否往y反方向行走(下)
{
walk(player, map, Comm.Direction.DOWN);
return;
}
stop_walk(player);
}
//绘制鼠标标记
public static void draw_flag(Graphics g, int map_sx, int map_sy)
{
if (target_x < 0 || target_y < 0)
return;
if (move_flag == null)
return;
if (Comm.Time() - flag_start_time > FLAG_SHOW_TIME)
return;
g.DrawImage(move_flag,map_sx+target_x-16,map_sy+target_y-17); //16,17为偏移参数
}
//设置战斗
public void fset(string name, string fbitmap_path, int fx_offset, int fy_offset, string fface_path, Animation anm_att, Animation anm_item, Animation anm_skill)
{
this.name = name;
if (fbitmap_path != null && fbitmap_path != "")
{
this.fbitmap = new Bitmap(fbitmap_path);
this.fbitmap.SetResolution(96, 96);
}
this.fx_offset = fx_offset;
this.fy_offset = fy_offset;
if (fface_path != null && fface_path != "")
{
this.fface = new Bitmap(fface_path);
this.fface.SetResolution(96, 96);
}
this.anm_att = anm_att;
this.anm_item = anm_item;
this.anm_skill = anm_skill;
anm_att.load();
anm_item.load();
anm_skill.load();
}
} |
public class Solution {
public void SortColors(int[] nums) {
if (nums.Length == 0) return;
int left = 0, right = nums.Length - 1;
int i = 0;
while (i <= right) {
if (nums[i] == 0) {
// if (i == left) {
// i ++;
// } else {
// Swap(nums, left, i);
// }
// left ++;
Swap(nums, left, i);
i++;
left ++;
} else if (nums[i] == 2) {
Swap(nums, i, right);
right --;
} else {
i ++;
}
}
}
private void Swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
} |
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIKit;
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using JoeCalc;
using JoeCalc.iOS;
[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]
namespace JoeCalc.iOS
{
public class MyEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bush : MonoBehaviour {
public bool isPicture; //Jika semak-semak dihancurkan, apakah mendapatkan potongan gambar
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using UnityEngine;
/* Programmer: Max Nastri
* Project: Spooky Knight Adventures
* Script: PlayerMotor.cs
* Purpose: Foundation for player actions including movement, attacking, combat and animations
*/
public class PlayerMotor : RayController
{
// Reference variable for the CollisionInfo struct
[HideInInspector] public CollisionInfo collisions;
// This mask holds what the player will collide with
public LayerMask collision_mask;
// Variables holding the maximum angle the player can climb or descend
private float max_climb_angle = 60.0f;
private float max_descend_angle = 60.0f;
// This struct stores the current state of the collisions associated with the player
public struct CollisionInfo
{
public bool above, below;
public bool left, right;
public bool climbing_slope;
public bool descending_slope;
public float slope_angle, angle_old;
public Vector3 velocity_old;
public void Reset()
{
above = below = false;
left = right = false;
climbing_slope = false;
descending_slope = false;
angle_old = slope_angle;
slope_angle = 0;
}
}
public override void Start()
{
base.Start();
}
// Moves the player according to the velocity parameter
// Optional parameter if the player is on a platform object (default = false)
public void Move(Vector3 velocity, bool on_platform = false)
{
// Reset the collision struct
collisions.Reset();
// Update the raycast origins according to the player's position
UpdateRaycastOrigins();
// Store the velocity
collisions.velocity_old = velocity;
// A negative Y velocity indicates the player is descending a slope
if (velocity.y < 0)
{
// Descend the slope
DescendSlope(ref velocity);
}
// The player is moving horizontally
if (velocity.x != 0)
{
// Enable horizontal collisions
HorizontalCollisions(ref velocity);
}
// The player is jumping
if (velocity.y != 0)
{
// Enable vertical collisions
VerticalCollisions(ref velocity);
}
// Move the player
transform.Translate(velocity);
// Check if the player is on a platform
if (on_platform)
{
// The player is colliding with the platform
collisions.below = true;
}
}
// This method uses raycasts to detect horizontal collisions on player movement
void HorizontalCollisions(ref Vector3 velocity)
{
// Get the player direction
float direction_x = Mathf.Sign(velocity.x);
// Ray length = |x velocity| + ray offset
float ray_length = Mathf.Abs(velocity.x) + raycast_offset;
// Cycle through for each ray to cast
for (int x = 0; x < horizontal_ray_count; x++)
{
// If the x direction is negative, the ray origin is bottom left; otherwise bottom right
Vector2 ray_origin = (direction_x == -1) ? raycast_origins.bottom_left : raycast_origins.bottom_right;
// Add horizontal spacing between each ray
ray_origin += Vector2.up * (horizontal_ray_spacing * x);
// Cast the ray looking for objects with the collision mask
RaycastHit2D hit = Physics2D.Raycast(ray_origin, Vector2.right * direction_x, ray_length, collision_mask);
// Draw the ray in the inspector
Debug.DrawRay(ray_origin, Vector2.right * direction_x * ray_length, Color.red);
// The ray hit something in the designated layer mask
if (hit)
{
// This allows for climbing multi-angle slopes
if (hit.distance == 0)
{
// Move to the next ray cast
continue;
}
// Get the angle of the object hit by the ray
float slope_angle = Vector2.Angle(hit.normal, Vector2.up);
// Conditions: Must be the first ray cast and the slope must be less than the max climb angle
if (x == 0 && slope_angle <= max_climb_angle)
{
// Cannot descend a slope while climbing a slope
if (collisions.descending_slope)
{
// No longer descending
collisions.descending_slope = false;
// Store the new velocity
velocity = collisions.velocity_old;
}
// Store the distance to the slope
float distance_to_slope = 0;
// We are climbing a new slope
if (slope_angle != collisions.angle_old)
{
// Store the distance to the slope
distance_to_slope = hit.distance - raycast_offset;
// Finish closing the distance to the slope
velocity.x -= distance_to_slope * direction_x;
}
// Climb the slope passing velocity and angle of the slope
ClimbSlope(ref velocity, slope_angle);
// Restore the velocity to normal after the gap between the player and slope was covered
velocity.x += distance_to_slope * direction_x;
}
// Detects horizontal collisions while not climbing
// Conditions: Cannot be climbing a slope or the angle is greater than the max climbing angle
if (!collisions.climbing_slope || slope_angle > max_climb_angle)
{
// velocity = (target distance - offset) * direction
velocity.x = (hit.distance - raycast_offset) * direction_x;
// Use distance for the ray length
ray_length = hit.distance;
// Detects horizontal collisions while climbing
// Such as an object sticking out while climbing
if (collisions.climbing_slope)
{
// Y Velocity = tan(slope angle) * |x velocity|
velocity.y = Mathf.Tan(collisions.slope_angle * Mathf.Deg2Rad) * Mathf.Abs(velocity.x);
}
// Check if facing left
collisions.left = direction_x == -1;
// Check if facing right
collisions.right = direction_x == 1;
}
}
}
}
// This method uses raycasts to detect vertical collisions on player movement
void VerticalCollisions(ref Vector3 velocity)
{
// Get the player direction
float direction_y = Mathf.Sign(velocity.y);
// Ray length = |y velocity| + ray offset
float ray_length = Mathf.Abs(velocity.y) + raycast_offset;
// Cycle through for each ray to cast
for (int x = 0; x < vertical_ray_count; x++)
{
// Set the raycast origin
// Conditions: Moving down = bottom left, otherwise top left
Vector2 ray_origin = (direction_y == -1) ? raycast_origins.bottom_left : raycast_origins.top_left;
// Add vertical spacing between each ray
ray_origin += Vector2.right * (vertical_ray_spacing * x + velocity.x);
// Cast the ray looking for objects with the collision mask
RaycastHit2D hit = Physics2D.Raycast(ray_origin, Vector2.up * direction_y, ray_length, collision_mask);
// Draw the ray in the inspector
Debug.DrawRay(ray_origin, Vector2.up * direction_y * ray_length, Color.red);
// The ray hit something in the designated layer mask
if (hit)
{
// velocity = (target distance - offset) * direction
velocity.y = (hit.distance - raycast_offset) * direction_y;
// Use distance for the ray length
ray_length = hit.distance;
// Detects vertical collisions while climbing a slope
// Such as a platform over-head
if (collisions.climbing_slope)
{
// x velocity = y velocity / (tan(slope angle) * x direction
velocity.x = velocity.y / Mathf.Tan(collisions.slope_angle * Mathf.Deg2Rad) * Mathf.Sign(velocity.x);
}
// Check if falling
collisions.below = direction_y == -1;
// Check if jumping
collisions.above = direction_y == 1;
}
}
// Check if the player is climbing a slope
if (collisions.climbing_slope)
{
// Get the direction
float direction_x = Mathf.Sign(velocity.x);
// Ray length = |x velocity| + ray offset
ray_length = Mathf.Abs(velocity.x) + raycast_offset;
// Set the ray origin
// Conditions: negative direction = bottom left, otherwise bottom right
Vector2 ray_origin = ((direction_x == -1 ? raycast_origins.bottom_left : raycast_origins.bottom_right)) + Vector2.up * velocity.y;
// Cast the ray looking for objects with the collision mask
RaycastHit2D hit = Physics2D.Raycast(ray_origin, Vector2.right * direction_x, ray_length, collision_mask);
// The ray hit something in the designated layer mask
if (hit)
{
// Get the angle of the object hit by the ray
float slope_angle = Vector2.Angle(hit.normal, Vector2.up);
// This is a new slope
if (slope_angle != collisions.slope_angle)
{
// velocity = (target distance - offset) * direction
velocity.x = (hit.distance - raycast_offset) * direction_x;
// Assign the new slope angle
collisions.slope_angle = slope_angle;
}
}
}
}
// This method allows for climbing slopes
void ClimbSlope(ref Vector3 velocity, float slope_angle)
{
// Get the desired move distance |x velocity|
float move_distance = Mathf.Abs(velocity.x);
// Get the climbing velocity (sin(slope angle) * move distance
float climbing_velocity = Mathf.Sin(slope_angle * Mathf.Deg2Rad) * move_distance;
// Check if the current y velocity is less than or equal the climbing velocity
if (velocity.y <= climbing_velocity)
{
// Set the new y velocity
velocity.y = climbing_velocity;
// Calculate the x velocity to climb the slope
velocity.x = Mathf.Cos(slope_angle * Mathf.Deg2Rad) * move_distance * Mathf.Sign(velocity.x);
// Grounded
collisions.below = true;
// Climbing a slope
collisions.climbing_slope = true;
// Set new slope angle
collisions.slope_angle = slope_angle;
}
}
// This method allows for descending slopes
void DescendSlope(ref Vector3 velocity)
{
// Get the horizontal direction
float direction_x = Mathf.Sign(velocity.x);
// Set the raycast origin
// Conditions: Moving left = bottom right, otherwise bottom left
Vector2 origin = (direction_x == -1 ? raycast_origins.bottom_right : raycast_origins.bottom_left);
// Cast the ray looking for objects with the collision mask
RaycastHit2D hit = Physics2D.Raycast(origin, -Vector2.up, Mathf.Infinity, collision_mask);
// The ray hit something in the designated layer mask
if (hit)
{
// Get the angle of the object hit by the ray
float slope_angle = Vector2.Angle(hit.normal, Vector2.up);
// Desceneding down a slope that is not 0 and is less than or equal to the max descend angle
if (slope_angle != 0 && slope_angle <= max_descend_angle)
{
// Check if we are moving down a slope
if (Mathf.Sign(hit.normal.x) == direction_x)
{
// Check if the distance is within velocity range
if (hit.distance - raycast_offset <= Mathf.Tan(slope_angle * Mathf.Deg2Rad) * Mathf.Abs(velocity.x))
{
float move_distance = Mathf.Abs(velocity.x);
// Calculate the velocity along the y axis = sin(slope angle) * x distance
float descend_velocity = Mathf.Sin(slope_angle * Mathf.Deg2Rad) * move_distance;
// Calculate the velocity along the x axis = cos(slope angle) * x distance * direction
velocity.x = Mathf.Cos(slope_angle * Mathf.Deg2Rad) * move_distance * Mathf.Sign(velocity.x);
velocity.y -= descend_velocity;
// Assign the new slope angle
collisions.slope_angle = slope_angle;
// In the descending slope state
collisions.descending_slope = true;
// Assign grounded
collisions.below = true;
}
}
}
}
}
// This function detects if an enemy is in the player's attack range
public GameObject EnemyInRange()
{
// Player has a melee range of 1.55 by default
float player_range = 1.6f;
// Draw the ray with a length of 1.55 from the character's origin
Debug.DrawRay(transform.position, new Vector2(player_range, 0), Color.red);
// Detect if an enemy is within the player's attack range
RaycastHit2D enemy_hit = Physics2D.Raycast(transform.position, new Vector2(1, 0), player_range, LayerMask.GetMask("Enemy"));
// Determine if the raycast hit an enemy
if (enemy_hit)
{
// Return the enemy hit by the ray
return enemy_hit.collider.gameObject;
}
else
{
return null;
}
}
}
|
using System.Collections.Generic;
using Umbraco.Core.Models.PublishedContent;
namespace Uintra.Features.CentralFeed.Providers
{
public abstract class FeedContentProviderBase : ContentProviderBase, IFeedContentProvider
{
protected abstract IEnumerable<string> OverviewAliasPath { get; }
protected FeedContentProviderBase() : base()
{ }
public virtual IPublishedContent GetOverviewPage() =>
GetContent(OverviewAliasPath);
public abstract IEnumerable<IPublishedContent> GetRelatedPages();
}
} |
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.Script.Serialization;
using TestWebService.Model;
using TestWebService.Data;
using TestWebService.Tools;
using System;
using System.Web.Services.Protocols;
namespace TestWebService
{
/// <summary>
/// Веб сервис
/// </summary>
[WebService(Namespace = "http://tempuri.org/TestWebService/TestWebService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class TestWebService : System.Web.Services.WebService
{
private IRepository _repo;
private ICryptographer _crypto;
public TestWebService()
{
_repo = new RepositoryLoginet();
// В задании не указано как будет использоваться поле email на клиенте, поэтому просто шифруем в MP5 без возможности дешифровки
_crypto = new CryptographerMP5();
}
public TestWebService(IRepository repo, ICryptographer crypto)
{
_repo = repo;
_crypto = crypto;
}
/// <summary>
/// Шифрование поля email объекта User
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private User EncryptEmail(User user)
{
user.email = _crypto.Encrypt(user.email);
return user;
}
/// <summary>
/// Шифрование поля email массива объектов User
/// </summary>
/// <param name="users"></param>
/// <returns></returns>
private User[] EncryptEmail(User[] users)
{
foreach(var user in users)
{
EncryptEmail(user);
}
return users;
}
/// <summary>
/// Выкидываем наружу ошибку, которая будет обрабатываться на стороне клиента
/// </summary>
/// <param name="ex">Ошибка</param>
private void ThrowSoapException(Exception ex)
{
throw new SoapException(ex.Message, SoapException.ServerFaultCode);
}
#region Xml
[WebMethod]
public User[] GetUsersXml()
{
try
{
var users = _repo.GetUsers();
return EncryptEmail(users);
}
catch(Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
public User GetUserByIdXml(int id)
{
try
{
var user = _repo.GetUserById(id);
return EncryptEmail(user);
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
public Album[] GetAlbumsXml()
{
try
{
return _repo.GetAlbums();
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
public Album GetAlbumByIdXml(int id)
{
try
{
return _repo.GetAlbumById(id);
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
public Album[] GetAlbumsByUserIdXml(int userId)
{
try
{
return _repo.GetAlbumsByUserId(userId);
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
#endregion
#region JSON
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUsersJson()
{
try
{
return new JavaScriptSerializer().Serialize(_repo.GetUsers());
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUserByIdJson(int id)
{
try
{
return new JavaScriptSerializer().Serialize(_repo.GetUserById(id));
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAlbumsJson()
{
try
{
return new JavaScriptSerializer().Serialize(_repo.GetAlbums());
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAlbumByIdJson(int id)
{
try
{
return new JavaScriptSerializer().Serialize(_repo.GetAlbumById(id));
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAlbumsByUserIdJson(int userId)
{
try
{
return new JavaScriptSerializer().Serialize(_repo.GetAlbumsByUserId(userId));
}
catch (Exception ex)
{
ThrowSoapException(ex);
}
return null;
}
#endregion
}
}
|
using System.Threading.Tasks;
using BookLibrary.Models;
namespace BookLibrary.Dal
{
public class BookLibraryRepository : IBookLibraryRepository
{
public Task<Book> AddAsync(string name, string content)
{
return Task.FromResult(new Book
{
Id = 42,
Name = name,
Content = content
});
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GamePlayMenuManager : MonoBehaviour
{
int sceneindex;
private void Start()
{
sceneindex= SceneManager.GetActiveScene().buildIndex;
}
public void BackStartMenu()
{
SceneManager.LoadScene("StartMenu");
}
public void StartGameLevel()
{
SceneManager.LoadScene("GamePlay");
}
public void StartFruitLevel()
{
SceneManager.LoadScene("FruitVegetable");
}
public void StartAnimalLevel()
{
SceneManager.LoadScene("Animals");
}
public void StartGeometryLevel()
{
SceneManager.LoadScene("Geometry");
}
public void StartColorsLevel()
{
SceneManager.LoadScene("Colors");
}
public void StartOrgansLevel()
{
SceneManager.LoadScene("Organs");
}
public void BackToCategories()
{
SceneManager.LoadScene("Categories");
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
SceneManager.LoadScene("Categories");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace E_ShopDomainModel.Interfaces
{
public interface INamedServices<TEntity> : IServices<TEntity>
where TEntity : class, IEntity
{
IEnumerable<TEntity> GetByName(string name);
}
}
|
using System.Windows.Controls;
namespace CODE.Framework.Wpf.Theme.Newsroom.StandardViews
{
/// <summary>
/// Interaction logic for TileNarrow.xaml
/// </summary>
public partial class TileNarrow : Grid
{
/// <summary>
/// Initializes a new instance of the <see cref="TileNarrow"/> class.
/// </summary>
public TileNarrow()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gurux.Device;
using System.Runtime.Serialization;
using System.ComponentModel;
using Gurux.Device.Editor;
namespace Gurux.DLMS.AddIn
{
[DataContract()]
public class GXDLMSData : GXDLMSProperty
{
/// <summary>
/// Default constructor.
/// </summary>
public GXDLMSData()
{
this.AttributeOrdinal = 2;
}
[ValueAccess(ValueAccessType.Show, ValueAccessType.None)]
[GXUserLevelAttribute(UserLevelType.Experienced)]
public override Gurux.DLMS.ObjectType ObjectType
{
get
{
return Gurux.DLMS.ObjectType.Data;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Windows.Forms;
using UseFul.ClientApi;
using UseFul.ClientApi.Dtos;
using UseFul.Forms.Welic;
using UseFul.Uteis;
using UseFul.Uteis.UI;
namespace Welic.WinForm.Cadastros.Estacionamento
{
public partial class FrmCadastroEstacionamentos : FormCadastro
{
public FrmCadastroEstacionamentos()
{
InitializeComponent();
//Inicialização dos Eventos.
this.Load += new EventHandler(LoadFormulario);
this.toolStripBtnNovo.Visible = true;
this.toolStripBtnNovo.Click += new EventHandler(ClickNovo);
this.toolStripBtnEditar.Visible = true;
this.toolStripBtnEditar.Click += new EventHandler(ClickEditar);
this.toolStripBtnExcluir.Visible = true;
this.toolStripBtnExcluir.Click += new EventHandler(ClickExcluir);
this.toolStripBtnGravar.Visible = true;
this.toolStripBtnGravar.Click += new EventHandler(ClickGravar);
this.toolStripBtnVoltar.Visible = true;
this.toolStripBtnVoltar.Click += new EventHandler(ClickVoltar);
this.toolStripBtnLocalizar.Visible = false;
this.toolStripBtnImprimir.Visible = false;
this.toolStripBtnAuditoria.Visible = false;
this.toolStripBtnAjuda.Visible = false;
this.toolStripSeparatorAcoes.Visible = true;
this.toolStripSeparatorOutros.Visible = false;
}
private void PreencherVagas()
{
if (!string.IsNullOrEmpty(txtEstacionamento.Text))
{
HttpResponseMessage response =
ClienteApi.Instance.RequisicaoGet($"estacionamento/GetVagasByEstacionamento/{txtEstacionamento.Text}");
var retorno =
ClienteApi.Instance.ObterResposta<List<EstacionamentoVagaDto>>(response);
BindingVagas.DataSource = retorno;
}
else if (BindingVagas.DataSource != null)
((DataTable)BindingVagas.DataSource).Clear();
}
private void PreencherFormulario()
{
try
{
if (string.IsNullOrEmpty(txtEstacionamento.Text))
{
LimpaCampos(this.Controls);
AcaoFormulario = CAcaoFormulario.Nenhum;
GerenciaCampos();
return;
}
HttpResponseMessage response =
ClienteApi.Instance.RequisicaoGet($"estacionamento/Getbyid/{txtEstacionamento.Text}");
var retorno =
ClienteApi.Instance.ObterResposta<EstacionamentoDto>(response);
if (retorno != null)
{
txtNome.Text = retorno.Descricao;
txtRelacao.Text = retorno.Relacao.ToString();
chkValidaVencimento.Checked = retorno.ValidaVencimento;
PreencherVagas();
AcaoFormulario = CAcaoFormulario.Buscar;
}
else
{
MessageBox.Show("Estacionamento não encontrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
LimpaCampos(this.Controls);
AcaoFormulario = CAcaoFormulario.Nenhum;
}
GerenciaCampos();
}
catch (CustomException ex)
{
ProcessMessage(ex.Message, MessageType.Error);
}
catch (Exception exception)
{
ProcessException(exception);
}
}
private void GerenciaCampos()
{
if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar)
pnBlocoVagaCurso.Enabled = true;
else
pnBlocoVagaCurso.Enabled = false;
}
private void SetaCamposEntidade(EstacionamentoDto estacionamento)
{
estacionamento.Descricao = txtNome.Text;
estacionamento.Relacao = int.Parse(txtRelacao.Text) == 0 ? 1 : int.Parse(txtRelacao.Text);
estacionamento.ValidaVencimento = chkValidaVencimento.Checked;
}
/// <summary>
/// Código Padrão - Load do Formulário - Tela de Cadastro
/// Versão 0.1 - 13/08/2010
/// </summary>
private void LoadFormulario(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtEstacionamento.Text))
{
LiberaChaveBloqueiaCampos(this.Controls);
LimpaCampos(this.Controls);
ModoOpcoes();
AcaoFormulario = CAcaoFormulario.Nenhum;
GerenciaCampos();
}
else if (!string.IsNullOrEmpty(txtEstacionamento.Text))
{
PreencherVagas();
}
}
/// <summary>
/// Código Padrão - Ação Botão Gravar - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickGravar(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
try
{
var estacionamento = new EstacionamentoDto();
SetaCamposEntidade(estacionamento);
if (AcaoFormulario == CAcaoFormulario.Novo)
{
HttpResponseMessage
response = ClienteApi.Instance.RequisicaoPost("estacionamento/save", estacionamento);
estacionamento = ClienteApi.Instance.ObterResposta<EstacionamentoDto>(response);
txtEstacionamento.Text = estacionamento.IdEstacionamento.ToString();
MensagemInsertUpdate("Salvo com sucesso.");
}
else if (AcaoFormulario == CAcaoFormulario.Editar)
{
int chave = int.Parse(txtEstacionamento.Text);
//Valida Atualização da Relação Motos/Carro
int relacao = int.Parse(txtRelacao.Text);
if (relacao <= 1)
estacionamento.Relacao = 1;
else
{
for (int i = 1; i <= 3; i++)
{
HttpResponseMessage response =
ClienteApi.Instance.RequisicaoGet($"estacionamento/GetListVagas/{txtEstacionamento.Text}");
var retorno =
ClienteApi.Instance.ObterResposta<List<EstacionamentoVagaDto>>(response);
List<EstacionamentoVagaDto> lista = retorno;
if (lista.Count > 1)
throw new Exception("Atenção!! \n\nEstacionamentos que possuem vagas para mais de 1 Tipo de Veículo no mesmo Tipo de Vaga não podem possuir Relação Motos/Carro diferente de 1. ");
}
estacionamento.Relacao = int.Parse(txtRelacao.Text);
}
SetaCamposEntidade(estacionamento);
HttpResponseMessage
responseUpdate = ClienteApi.Instance.RequisicaoPost("estacionamento/update", estacionamento);
ClienteApi.Instance.ObterResposta<EstacionamentoDto>(responseUpdate);
MensagemInsertUpdate("Alterado com sucesso.");
}
}
catch (CustomException ex)
{
ProcessMessage(ex.Message, MessageType.Error);
}
catch (Exception exception)
{
ProcessException(exception);
}
}
}
private void MensagemInsertUpdate(string mensagem)
{
MensagemStatusBar(mensagem);
LiberaChaveBloqueiaCampos(this.Controls);
ModoOpcoes();
AcaoFormulario = CAcaoFormulario.Gravar;
GerenciaCampos();
}
/// <summary>
/// Código Padrão - Ação Botão Excluir - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickExcluir(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser excluído.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
if (MessageBox.Show("Confirma a exclusão do registro?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
try
{
HttpResponseMessage
response = ClienteApi.Instance.RequisicaoPost($"estacionamento/delete/{txtEstacionamento.Text}");
ClienteApi.Instance.ObterResposta(response);
MensagemStatusBar("Excluído com sucesso.");
LiberaChaveBloqueiaCampos(this.Controls);
LimpaCampos(this.Controls);
AcaoFormulario = CAcaoFormulario.Excluir;
}
catch (CustomException ex)
{
ProcessMessage(ex.Message, MessageType.Error);
}
catch (Exception exception)
{
ProcessException(exception);
}
GerenciaCampos();
}
}
}
/// <summary>
/// Código Padrão - Ação Botão Novo - Tela de Cadastro
/// Versão 0.1 - 13/08/2010
/// </summary>
private void ClickNovo(object sender, EventArgs e)
{
LimpaCamposBloqueiaAutoIncremento(this.Controls);
ModoGravacao();
AcaoFormulario = CAcaoFormulario.Novo;
GerenciaCampos();
}
/// <summary>
/// Código Padrão - Ação Botão Editar - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickEditar(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser alterado.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
BloqueiaChaveLiberaCampos(this.Controls);
ModoGravacao();
AcaoFormulario = CAcaoFormulario.Editar;
GerenciaCampos();
}
}
/// <summary>
/// Código Padrão - Ação Botão Voltar - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickVoltar(object sender, EventArgs e)
{
LiberaChaveBloqueiaCampos(this.Controls);
LimpaCamposNaoChave(this.Controls);
ModoOpcoes();
AcaoFormulario = CAcaoFormulario.Voltar;
GerenciaCampos();
}
private void txtEstacionamento_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F3)
{
HttpResponseMessage response =
ClienteApi.Instance.RequisicaoGet($"estacionamento/get");
var retorno =
ClienteApi.Instance.ObterResposta<List<EstacionamentoDto>>(response);
if (retorno.Count > 0)
{
var fb = new FormBuscaPaginacao();
fb.SetList(retorno, "IdEstacionamento");
fb.ShowDialog();
if (fb.RetornoList<EstacionamentoDto>() != null)
{
txtEstacionamento.Text = fb.RetornoList<EstacionamentoDto>().IdEstacionamento.ToString();
PreencherFormulario();
}
}
}
}
private void txtEstacionamento_Leave(object sender, EventArgs e)
{
PreencherFormulario();
}
private void txtEstacionamento_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtEstacionamento.Text))
PreencherFormulario();
}
private void btnAddVagas_Click(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
if (string.IsNullOrEmpty(txtEstacionamento.Text))
{
ClickGravar(sender, e);
ClickEditar(sender, e);
}
FrmCadastroEstacionamentoVagas frmCEV = new FrmCadastroEstacionamentoVagas(int.Parse(txtEstacionamento.Text));
frmCEV.ShowDialog();
PreencherVagas();
}
}
private void dgvVagas_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dgvVagas.Columns["colVagaExcluir"].Index)
{
if (MessageBox.Show("Tem certeza que deseja EXCLUIR a Vaga?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
try
{
int chave2 = int.Parse(dgvVagas.SelectedRows[0].Cells["ColTipoVaga"].Value.ToString());
int chave3 = int.Parse(dgvVagas.SelectedRows[0].Cells["ColTipoVeiculo"].Value.ToString());
HttpResponseMessage
response = ClienteApi.Instance.RequisicaoPost($"estacionamento/deleteVagas/{txtEstacionamento.Text}/{chave2}/{chave3}");
ClienteApi.Instance.ObterResposta(response);
PreencherVagas();
}
catch (Exception ex)
{
if (ex.InnerException != null)
MessageBox.Show(this, "Não foi possível excluir o registro." + "\nErro: " + ex.InnerException.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show(this, "Não foi possível excluir o registro." + "\nErro: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
} |
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace CSEBrazil.Library.Utils
{
public static class HTTPExtension
{
static Action Throttled;
private static async Task<TResponse> RunTaskWithAutoRetryOnQuotaLimitExceededError<TResponse>(Func<Task<TResponse>> action, int RetryCount, int RetryDelay)
{
int retriesLeft = RetryCount;
int delay = RetryDelay;
TResponse response = default(TResponse);
while (true)
{
try
{
response = await action();
break;
}
catch (Exception exception) when (retriesLeft > 0)
{
if (retriesLeft == 1 && Throttled != null)
{
Throttled();
}
await Task.Delay(delay);
retriesLeft--;
delay *= 2;
continue;
}
}
return response;
}
public static async Task<T> PostContentAsync<T>(this HttpClient client, string uri, object content, int RetryCount = 3, int DelayCount = 500) where T : class
{
var strContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
var result = await RunTaskWithAutoRetryOnQuotaLimitExceededError<HttpResponseMessage>(() => client.PostAsync(uri, strContent), RetryCount, DelayCount);
result.EnsureSuccessStatusCode();
var strResponse = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(strResponse);
}
public static async Task<T> PutContentAsync<T>(this HttpClient client, string uri, object content, int RetryCount = 3, int DelayCount = 500) where T : class
{
var strContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
var result = await RunTaskWithAutoRetryOnQuotaLimitExceededError<HttpResponseMessage>(() => client.PutAsync(uri, strContent), RetryCount, DelayCount);
result.EnsureSuccessStatusCode();
var strResponse = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(strResponse);
}
public static async Task<T> GetContentAsync<T>(this HttpClient client, string uri, int RetryCount = 3, int DelayCount = 500) where T : class
{
var result = await RunTaskWithAutoRetryOnQuotaLimitExceededError<HttpResponseMessage>(() => client.GetAsync(uri), RetryCount, DelayCount);
result.EnsureSuccessStatusCode();
var strResponse = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(strResponse);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.OracleClient;
using System.Data.SqlClient;
namespace pe
{
public partial class FrmSetup : Form
{
ImportDV importDV;
ArrayList alist;
ArrayList alsql;
DbConn db;
String Strsql = "";
String Strsql1 = "";
int i_flag = -1;
DataSet dataSet = null;
OracleDataReader oracleDataReader = null;
DbConn sqlDbConn = null;
SqlDataAdapter sqlDataAdapter = null;
public FrmSetup()
{
InitializeComponent();
sqlDbConn = new DbConn();
}
private void FrmSetup_Load(object sender, EventArgs e)
{
LoadGv();
comboBox1.Enabled = false;
textBox1.Enabled = false;
textBox2.Enabled = false;
comboBox1.SelectedIndex = 0;
}
private void LoadGv()
{
Strsql = "select type as id,name as 参数类型,bavalue as 病案参数,hisvalue as HIS参数 from T_SET,T_SETdetail where T_SET.type=T_SETdetail.id order by type";
sqlDataAdapter = sqlDbConn.GetDataAdapter(Strsql);
dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet, "table1");
dataGridView1.DataSource = dataSet.Tables["table1"].DefaultView;
dataGridView1.Columns["id"].Visible = false;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
comboBox1.SelectedIndex = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
comboBox1.Enabled = false;
textBox1.Enabled = false;
textBox2.Enabled = false;
button3.Enabled = false;
button1.Enabled = true;
button2.Enabled = true;
}
else
{
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
i_flag = 0;
textBox1.Text = "";
textBox2.Text = "";
comboBox1.Enabled = true;
textBox1.Enabled = true;
textBox2.Enabled = true;
button2.Enabled = false;
button3.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult dir = MessageBox.Show("确定删除该项目?", "警告", MessageBoxButtons.YesNo);
if (dir == DialogResult.Yes)
{
Strsql = "delete from T_SET where bavalue='" + textBox1.Text + "' and hisvalue='" + textBox2.Text + "' and type=" + comboBox1.SelectedIndex.ToString();
if (sqlDbConn.GetSqlCmd(Strsql) != 0)
{
MessageBox.Show("删除成功!");
LoadGv();
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > 0)
{
Strsql = "insert into T_SET values('" + textBox2.Text + "','" + textBox1.Text + "','" + comboBox1.SelectedIndex.ToString() + "')";
if (sqlDbConn.GetSqlCmd(Strsql) != 0)
{
MessageBox.Show("新增成功!");
}
textBox1.Enabled = false;
textBox2.Enabled = false;
button3.Enabled = false;
button1.Enabled = true;
button2.Enabled = true;
LoadGv();
}
else
{
MessageBox.Show("请选择类型!");
}
}
}
}
|
using MakePayroll;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MakePayroll {
public class EmployeesWindowView : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public EmployeeView employee { get; set; }
public List<EmployeeView> employees { get; set; }
public ICollectionView employeesView { get; set; }
public EmployeesWindowView(DateTime date) {
Queries queries = new Queries();
employees = queries.getEmployees(date);
}
}
}
|
namespace ProjetctTiGr13.Domain.FicheComponent
{
public class SaveRollManager
{
public bool ForceSave { get; set; }
public bool DexteriteSave { get; set; }
public bool ConstitutionSave { get; set; }
public bool IntelligenceSave { get; set; }
public bool SagesseSave { get; set; }
public bool CharismeSave { get; set; }
public SaveRollManager()
{
ForceSave = false;
DexteriteSave = false;
ConstitutionSave = false;
IntelligenceSave = false;
SagesseSave = false;
CharismeSave = false;
}
}
} |
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Instancer of type `GameObjectPair`. Inherits from `AtomEventInstancer<GameObjectPair, GameObjectPairEvent>`.
/// </summary>
[EditorIcon("atom-icon-sign-blue")]
[AddComponentMenu("Unity Atoms/Event Instancers/GameObjectPair Event Instancer")]
public class GameObjectPairEventInstancer : AtomEventInstancer<GameObjectPair, GameObjectPairEvent> { }
}
|
using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using DtCms.BLL;
using System.Data;
namespace DtCms.Web.m
{
public partial class news : DtCms.Web.UI.BasePage
{
public int pcount = 0; //总条数
public int page; //当前页
public int pagesize; //设置每页显示的大小
public int classId;
public string property = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!int.TryParse(Request.Params["classId"] as string, out this.classId))
{
this.classId = 0;
}
if (!string.IsNullOrEmpty(Request.Params["property"]))
{
this.property = Request.Params["property"].Trim();
}
if (!Page.IsPostBack)
{
this.pagesize = webset.WebNewsSize;
RptBind("IsLock=0 " + this.CombSqlTxt(this.classId, this.property), "AddTime desc");
}
}
#region 列表绑定
private void RptBind(string _where, string _orderby)
{
if (!int.TryParse(Request.Params["page"] as string, out this.page))
{
this.page = 0;
}
DtCms.BLL.Article bll = new DtCms.BLL.Article();
//获得总条数
this.pcount = bll.GetCount(_where);
//查询分页绑定数据
this.rptList.DataSource = bll.GetPageList(this.pagesize, this.page, _where, _orderby);
this.rptList.DataBind();
}
#endregion
#region 组合URL参数
protected string CombKeywords(int _classId, string _property)
{
StringBuilder strTemp = new StringBuilder();
if (_classId > 0)
{
strTemp.Append("classId=" + _classId + "&");
}
if (!string.IsNullOrEmpty(_property))
{
strTemp.Append("property=" + _property + "&");
}
return strTemp.ToString();
}
#endregion
#region 组合查询语句
protected string CombSqlTxt(int _classId, string _property)
{
StringBuilder strTemp = new StringBuilder();
if (_classId > 0)
{
strTemp.Append(" and ClassId=" + _classId);
}
if (!string.IsNullOrEmpty(_property))
{
switch (_property)
{
case "IsMsg":
strTemp.Append(" and IsMsg=1");
break;
case "IsTop":
strTemp.Append(" and IsTop=1");
break;
case "IsRed":
strTemp.Append(" and IsRed=1");
break;
case "IsHot":
strTemp.Append(" and IsHot=1");
break;
case "IsSlide":
strTemp.Append(" and IsSlide=1");
break;
}
}
return strTemp.ToString();
}
#endregion
}
}
|
using System;
class Factorial
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int i = 1;
int sum = 1;
do
{
sum *= i;
i++;
} while (i <= n);
Console.WriteLine(sum);
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Pause manager.
///
/// Allows lots of custom behaviors on pause by centralising
/// pausing and providing pause events to subscribe to.
/// </summary>
public class PauseManager : MonoBehaviour
{
public delegate void PauseAction();
public static event PauseAction OnPaused;
public static event PauseAction OnResumed;
public static bool Paused { get; private set; }
public static void Pause()
{
Debug.Log ("Pause");
Time.timeScale = 0.0000f;
Paused = true;
if (OnPaused != null)
{
OnPaused();
}
Cheats.instance.cheatMenuOpen = true;
}
public static void Resume()
{
Debug.Log ("Resume");
Time.timeScale = 1.0f;
Paused = false;
if (OnResumed != null)
{
OnResumed();
}
Cheats.instance.cheatMenuOpen = false;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KartLib.Views;
using KartObjects;
using System.Threading;
using System.Linq;
using DevExpress.XtraBars;
using KartLib;
using KartObjects.Entities.Documents;
namespace KartSystem
{
public partial class DemandReportView : KartUserControl, IDemandReportView
{
public DemandReportView()
{
InitializeComponent();
ViewObjectType = ObjectType.DemandReport;
//InitView();
}
void DemandReportView_DocIsFormed(object sender, EventArgs e)
{
//Закрываем форму ожидания
(Preseneter as DemandReportPresenter).WriteLog(frmWait.Text);
frmWait.CloseWaitForm();
}
public IList<DemandDocument> DemandDocs
{
get;
set;
}
void RefreshView()
{
gcDemandReport.DataSource = DemandDocs;
gvDemandReport.RefreshData();
}
public override void InitView()
{
Preseneter = new DemandReportPresenter(this);
(Preseneter as DemandReportPresenter).DocIsFormed += new EventHandler(DemandReportView_DocIsFormed);
DateDemandFrom = DateTime.Now.AddDays(-1);
DateDemandTo = DateTime.Now;
lueWarehouses.Properties.DataSource = KartDataDictionary.sWarehouses;
if (KartDataDictionary.CurrWh != null)
{
lueWarehouses.EditValue = KartDataDictionary.CurrWh;
lueWarehouses.Enabled = false;
}
(Preseneter as DemandReportPresenter).getDocuments();
warehouseBindingSource.DataSource = KartDataDictionary.sWarehouses;
docStatusBindingSource.DataSource = KartDataDictionary.sDocStatuses;
supplierBindingSource.DataSource = KartDataDictionary.sSuppliers;
RefreshView();
LoadSettings();
}
/// <summary>
/// Выбранная дата
/// </summary>
public DateTime DateDemand
{
get
{
return deDemandDate.DateTime;
}
set
{
deDemandDate.DateTime = value;
}
}
/// <summary>
/// Выбраный склад
/// </summary>
public Warehouse Warehouse
{
get
{
return (Warehouse)lueWarehouses.EditValue;
}
set
{
lueWarehouses.EditValue = value;
}
}
/// <summary>
/// Выбранный документ
/// </summary>
public DemandDocument ActiveDocument
{
get { return gvDemandReport.GetFocusedRow() as DemandDocument; }
set
{
for (int i = 0; i < gvDemandReport.RowCount; i++)
{
if ((gvDemandReport.GetRow(i) as Document).Id == value.Id)
{
gvDemandReport.FocusedRowHandle = i;
break;
}
}
}
}
private void lueStatus_EditValueChanged(object sender, EventArgs e)
{
ActiveDocument.Status = Convert.ToInt32((sender as DevExpress.XtraEditors.LookUpEdit).Properties.KeyValue);
(Preseneter as DemandReportPresenter).SaveData();
RefreshView();
}
private void deDemandDate_EditValueChanged(object sender, EventArgs e)
{
if ((Preseneter != null) && (DateDemand != null))
(Preseneter as DemandReportPresenter).getDocuments();
RefreshView();
}
public override bool RecordSelected
{
get
{
return gvDemandReport.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle;
}
}
public override void DeleteItem(object sender, ItemClickEventArgs e)
{
if (!RecordSelected)
{
return;
}
else
{
if (MessageBox.Show(this, "Вы уверены что хотите удалить документ?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{
(Preseneter as DemandReportPresenter).deleteDoc();
RefreshView();
}
}
}
public override void EditorAction(bool addMode)
{
if (addMode)
{
if (CheckWh())
{
DemandDocument d = (Preseneter as DemandReportPresenter).NewEmptyDoc();
(Preseneter as DemandReportPresenter).getDocuments();
RefreshView();
ActiveDocument = d;
}
else return;
}
if (KartDataDictionary.currentReportSession == null)
KartDataDictionary.currentReportSession = new ReportSession();
//XDemandEditor frmDemandEditor = new XDemandEditor(ActiveDocument, KartDataDictionary.currentReportSession.IdSession);
DemandDocsEditor frmDemandEditor = new DemandDocsEditor(ActiveDocument as DemandDocument, KartDataDictionary.currentReportSession.IdSession);
if (frmDemandEditor.ShowDialog() == DialogResult.OK)
{
(Preseneter as DemandReportPresenter).getDocuments();
RefreshView();
}
}
public DateTime DateDemandFrom
{
get
{
return deDemandFrom.DateTime;
}
set
{
deDemandFrom.DateTime = value;
}
}
public DateTime DateDemandTo
{
get
{
return deDemandTo.DateTime;
}
set
{
deDemandTo.DateTime = value;
}
}
/// <summary>
/// Форма ожидания
/// </summary>
private FormWait frmWait;
private void btnMakeDemandDoc_Click(object sender, EventArgs e)
{
if (CheckWh())
{
(Preseneter as DemandReportPresenter).CreateDocs = true;
DoProcess();
}
}
/// <summary>
/// Формирование документов
/// </summary>
void DoProcess()
{
KartDataDictionary.CheckReportSession(Warehouse.Id, DateDemandFrom, DateDemandTo);
try
{
frmWait = new FormWait("Формирование документа заказа ...");
// Процесс формирования запускаем отдельным потоком
Thread thread = new Thread((Preseneter as DemandReportPresenter).makeDoc) { IsBackground = true };
thread.Start();
frmWait.ShowDialog();
frmWait.Dispose();
frmWait = null;
}
catch (Exception exc)
{
ExtMessageBox.ShowError(string.Format("Ошибка при формировании заказа.\r\n{0}", exc.Message));
frmWait.CloseWaitForm();
}
RefreshView();
}
public bool restCondition
{
get
{
return cbRestCond.Checked;
}
set
{
cbRestCond.Checked = value;
}
}
private void gcDemandReport_MouseDoubleClick(object sender, MouseEventArgs e)
{
EditAction(sender, null);
}
private void lueWarehouses_Properties_EditValueChanged(object sender, EventArgs e)
{
(Preseneter as DemandReportPresenter).getDocuments();
RefreshView();
}
/// <summary>
/// Проверка на выбор склада
/// </summary>
/// <returns></returns>
bool CheckWh()
{
bool result = false;
if (lueWarehouses.EditValue != null)
{
result = true;
}
else
{
ExtMessageBox.ShowError("Необходимо выбрать место хранения.");
lueWarehouses.Focus();
result = false;
}
return result;
}
private void simpleButton1_Click(object sender, EventArgs e)
{
if (CheckWh())
{
KartDataDictionary.ClearReportSession();
(Preseneter as DemandReportPresenter).CreateDocs = false;
DoProcess();
}
}
private void deDemandFrom_Validating(object sender, CancelEventArgs e)
{
e.Cancel = DateDemandTo < DateDemandFrom;
}
public override bool IsEditable
{
get
{
return true;
}
}
public override bool IsInsertable
{
get
{
return true;
}
}
public override bool UseSubmenu
{
get
{
return false;
}
}
public override bool IsDeletable
{
get
{
return true;
}
}
public override bool IsPrintable
{
get
{
return false;
}
}
public long IdDocType
{
get
{
DocType dtype =
KartDataDictionary.sDocTypes.FirstOrDefault(dt => { return dt.DocKind == DocKindEnum.WhDemand; });
if (dtype != null) return dtype.Id;
else return 0;
}
}
private void simpleButton2_Click(object sender, EventArgs e)
{
DemandMasterForm frmMasterDemand = new DemandMasterForm();
if (lueWarehouses.EditValue != null)
frmMasterDemand.FixedWarehouse = (lueWarehouses.EditValue as Warehouse);
if (frmMasterDemand.ShowDialog() == DialogResult.OK)
RefreshView();
}
private void lueDocStatus_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
{
if ((ActiveDocument.Status == 1 && IsActionBanned(AxiTradeAction.Retirement))
|| (ActiveDocument.Status == 0 && IsActionBanned(AxiTradeAction.Posting)))
{
ExtMessageBox.ShowError("Не хватает прав");
e.Cancel = true;
}
}
private void simpleButton3_Click(object sender, EventArgs e)
{
(Preseneter as DemandReportPresenter).getDocuments();
RefreshView();
}
}
}
|
using FrameOS.Systems.CommandSystem;
using System;
using System.Collections.Generic;
using System.Text;
using FrameOS.Systems.Networking;
using Cosmos.HAL;
namespace FrameOS.Commands
{
class GetNetworkTimeCommand : ICommand
{
public string description { get => "Get the time from time.windows.com"; }
public string command => "time";
public void Run(CommandArg[] commandArgs)
{
NTPClient client = new NTPClient();
DateTime time = client.GetNetworkTime();
if (time == null)
{
Terminal.WriteLine("Couldn't get the time! Check your internet connection!");
}else
{
Terminal.WriteLine("Time: " + time);
}
}
}
}
|
namespace Alabo.Tool.Payment.MiniProgram.Dtos
{
/// <summary>
/// 小程序登录以后返回的状态
/// </summary>
public class LoginOutput
{
/// <summary>
/// 用户是否注册
/// </summary>
/// <value>
/// <c>true</c> if this instance is reg; otherwise, <c>false</c>.
/// </value>
public bool IsReg { get; set; } = false;
/// <summary>
/// 微信登录后返回的信息
/// </summary>
/// <value>The session.</value>
public SessionOutput Session { get; set; }
/// <summary>
/// 登录用户
/// </summary>
/// <value>The user.</value>
// public UserOutput User { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FrbaOfertas.Model
{
public class Funcionalidad
{
public List<String> atributesModify = new List<string>();
Int32 _fun_codigo;
String _fun_nombre;
public Funcionalidad(string p1, int p2)
{
// TODO: Complete member initialization
this._fun_nombre = p1;
this._fun_codigo = p2;
}
public Funcionalidad()
{
// TODO: Complete member initialization
}
[System.ComponentModel.DisplayName("Codigo")]
public Int32 fun_codigo { get { return this._fun_codigo; } set { this._fun_codigo = value; atributesModify.Add("_fun_codigo"); } }
[System.ComponentModel.DisplayName("Nombre")]
public String fun_nombre { get { return this._fun_nombre; } set { this._fun_nombre = value; atributesModify.Add("_fun_nombre"); } }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DSSCriterias.Logic;
using DSSCriterias.Logic.Criterias;
namespace DSSCriterias.Tests
{
[TestClass]
public class StatGameTest
{
private readonly double[,] MatrixExample =
new double[,]
{
{ 9, 9, 9 },
{ 0, 0, 0 },
{ 0, 0, 0 }
};
//Проверка на обновление результатов критериев и выбранных альтернатив
[TestMethod]
//При изменении значения
public void UpdateValue()
{
//assign
StatGame game = new StatGame("", MtxStat.CreateFromArray(MatrixExample));
ICriteria criteria = game.Report.GetCriteria<CriteriaMaxMax>();
double firstResult = criteria.Result;
var firstRank = game.Report.AlternativeRanks;
//act
for (int i = 0; i < 3; i++)
{
game.Mtx.Set(2, i, 15);
}
//assert
Assert.IsTrue(criteria.Result != firstResult, "Критерий не обновлен после изменения значения матрицы");
Assert.IsTrue(game.Report.AlternativeRanks != firstRank, "Отчет по критериям не обновлен после изменения значения матрицы");
}
[TestMethod]
//При изменении вероятности исхода
public void UpdateChance()
{
//assign
StatGame game = new StatGame("", MtxStat.CreateFromArray(MatrixExample), new Situation() { Chances = StateChances.Riscs() });
ICriteria criteria = game.Report.GetCriteria<CriteriaGerr>();
double firstResult = criteria.Result;
var firstRank = game.Report.AlternativeRanks;
//act
game.SetChance(0, 0.5);
//assert
Assert.IsTrue(criteria.Result != firstResult, "Критерий не обновлен после изменения вероятности исхода");
Assert.IsTrue(game.Report.AlternativeRanks != firstRank, "Отчет по критериям не обновлен после изменения вероятности исхода");
}
[TestMethod]
//При изменении структуры матрицы
public void UpdateStructure()
{
//assign
StatGame game = new StatGame("", MtxStat.CreateFromArray(MatrixExample));
var criteria = game.Report.GetCriteria<CriteriaMaxMax>();
double firstResult = criteria.Result;
var firstRank = game.Report.AlternativeRanks;
//act
game.Mtx.RemoveRow(game.Mtx.Rows.First());
//assert
Assert.IsTrue(firstResult != criteria.Result, "Критерий не обновлен изменения структуры матрицы");
Assert.IsTrue(game.Report.AlternativeRanks != firstRank, "Отчет по критериям не обновлен после изменения структуры матрицы");
}
[TestMethod]
//При обновлении ситуации
public void UpdateSituation()
{
//assign
StatGame game = new StatGame("", MtxStat.CreateFromArray(MatrixExample));
game.Report.IgnoreUsage = true;
game.SetChance(0, 0.5);
game.SetChance(1, 0.4);
game.SetChance(2, 0.1);
var criteria = game.Report.GetCriteria<CriteriaGerr>();
double firstResult = criteria.Result;
var firstRank = game.Report.AlternativeRanks;
//act
game.Situation.Chances = StateChances.Riscs();
//assert
Assert.IsTrue(firstResult != criteria.Result, "Критерий не обновлен после шанса у исхода");
Assert.IsTrue(game.Report.AlternativeRanks != firstRank, "Отчет по критериям не обновлен после изменения ситуации матрицы");
}
}
}
|
namespace Domain.Entities
{
public sealed class StoryGenre : BaseEntity
{
public string Type { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using TrainingRooms.Admin.Dialogs;
using TrainingRooms.Admin.SelectionModels;
using TrainingRooms.Model;
using UpdateControls.XAML;
namespace TrainingRooms.Admin.ViewModels
{
public class EventViewModel
{
private readonly Event _event;
private readonly Venue _venue;
public EventViewModel(Event @event, Venue venue)
{
_event = @event;
_venue = venue;
}
internal Event Event
{
get { return _event; }
}
internal Venue Venue
{
get { return _venue; }
}
public string Time
{
get
{
var start = DateTime.Today.AddMinutes(_event.StartMinutes.Value);
var end = DateTime.Today.AddMinutes(_event.EndMinutes.Value);
return String.Format(@"{0:t} - {1:t}", start, end);
}
}
public string GroupName
{
get
{
return _event.Group.Value.Name.Value;
}
}
public ICommand DeleteEvent
{
get
{
return MakeCommand
.Do(delegate
{
_event.Community.Perform(async delegate
{
await _event.Delete();
});
});
}
}
public void Edit()
{
EventEditorDialog editor = new EventEditorDialog();
EventEditorModel model = EventEditorModel.FromEvent(Event);
editor.DataContext = ForView.Wrap(new EventEditorViewModel(model, Venue));
if (editor.ShowDialog() ?? false)
{
model.ToEvent(Event);
}
}
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Projeto_Carros.Models;
using Projeto_Carros.Services;
using System.Collections.Generic;
using System.Linq;
namespace Projeto_Carros.Controllers
{
[Route("api/[controller]")]
[EnableCors("MyPolicy")]
[ApiController]
public class HomeController : Controller
{
private ICarrosServices _carrosServices;
private IRevisoesServices _revisoesServices;
public HomeController(ICarrosServices carrosServices, IRevisoesServices revisoesServices)
{
_carrosServices = carrosServices;
_revisoesServices = revisoesServices;
}
[HttpGet]
public IActionResult Get()
{
return Ok(_carrosServices.Lista());
}
// GET: api/Home/5
[HttpGet("{Codigo}", Name = "Get")]
public IActionResult Get(int Codigo)
{
var carros = _carrosServices.FindById(Codigo);
if (carros == null)
{
return NotFound();
}
return Ok(carros);
}
// POST: api/Home
[HttpPost]
[Route("PostCarros")]
public IActionResult Post([FromBody] Carros carros)
{
if (carros == null)
{
return NotFound();
}
return Ok(_carrosServices.Create(carros));
}
[HttpPost]
[Route("PostRevisoes")]
public IActionResult Post([FromBody] Revisoes revisoes)
{
if (revisoes == null)
{
return NotFound();
}
return Ok(_revisoesServices.Create(revisoes));
}
// PUT: api/Home/5
[HttpPut("{id}")]
public IActionResult Put([FromBody] Carros carros)
{
if (carros == null)
{
return BadRequest();
}
return Ok(_carrosServices.Update(carros));
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_carrosServices.Delete(id);
return NoContent();
}
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Embraer_Backend.Models;
using Microsoft.Extensions.Configuration;
using System;
using Microsoft.AspNetCore.Cors;
using System.Linq;
namespace Embraer_Backend.Controllers
{
[Route("api/[controller]/[action]")]
[EnableCors("CorsPolicy")]
public class ParticulasController : Controller
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ParticulasController));
private readonly IConfiguration _configuration;
ParticulasModel _prtModel = new ParticulasModel();
LocalMedicaoModel _localMedicaoModel = new LocalMedicaoModel();
ParametrosModel _parModel = new ParametrosModel();
IEnumerable<Particulas> _particulas;
IEnumerable<ParticulasMedicoes> _medicoes;
IEnumerable<Parametros> _par;
IEnumerable<ParticulasTam> _tampart;
IEnumerable<ParticulasReport> _report;
ControleApontamento _ctrl;
ControleApontamentoModel _ctrlModel = new ControleApontamentoModel();
public ParticulasController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index(long IdLocalMedicao)
{
if (IdLocalMedicao>0)
{
log.Debug("Get Do parametro de Particulas!");
_par = _parModel.SelectParametros(_configuration,IdLocalMedicao,"Particulas");
return Ok(_par);
}
else
return StatusCode(505,"Não foi recebido o parametro IdLocalMedicao!");
}
//Get api/GetParticulas
[HttpGet]
public IActionResult GetParticulas(long id, string Ini, string Fim,bool Ocorrencia)
{
if (id!=0 || (Ini!=null && Fim!=null))
{
log.Debug("Get Dos Apontamentos de Particulas!");
_particulas=_prtModel.SelectParticulas(_configuration, id, Ini, Fim,Ocorrencia);
return Ok(_particulas);
}
else
return StatusCode(505,"Não foi recebido o parametro IdIApontParticulas ou os parametros de Data Inicio e Data Fim");
}
//Get api/GetMedicoes
[HttpGet("{IdIApontParticulas}")]
public IActionResult GetMedicoes(long IdIApontParticulas)
{
if (IdIApontParticulas!=0)
{
log.Debug("Get Dos Apontamentos de Particulas!");
_medicoes=_prtModel.SelectMedicaoParticulas(_configuration, IdIApontParticulas);
return Ok(_medicoes);
}
return StatusCode(505,"O IdIApontParticulas não pode ser nulo nem Igual a 0!");
}
//Get api/GetMedicoes
[HttpGet("{IdMedicaoParticulas}")]
public IActionResult GetMedicoesTamParticulas(long IdMedicaoParticulas)
{
if (IdMedicaoParticulas!=0)
{
log.Debug("Get Dos Apontamentos de Tamanhos Particulas!");
_tampart=_prtModel.SelectParticulasTam(_configuration, IdMedicaoParticulas);
return Ok(_tampart);
}
return StatusCode(505,"O IdTamParticulas não pode ser nulo nem Igual a 0!");
}
[HttpGet]
public IActionResult GetParticulasReport(long IdLocalMedicao,string Ini, string Fim)
{
if (Ini!=null && Fim!=null)
{
log.Debug("Get Dos Apontamentos de Iluminancia para Report!");
_report=_prtModel.ParticulasReport(_configuration, IdLocalMedicao,Ini, Fim);
return Ok(_report);
}
else
return StatusCode(505,"Não foi recebido o parametro IdLocalMedicao ou os parametros de Data Inicio e Data Fim");
}
[HttpPost]
public IActionResult PostParticulas([FromBody]Particulas _Particulas)
{
if (ModelState.IsValid)
{
var insert = _prtModel.InsertIParticulas(_configuration,_Particulas);
if(insert==true)
{
log.Debug("Post do Apontamento com sucesso:" + _Particulas);
return Json(_Particulas);
}
return StatusCode(500,"Houve um erro, verifique o Log do sistema!");
}
else
log.Debug("Post não efetuado, Bad Request" + ModelState.ToString());
return BadRequest(ModelState);
}
[HttpPost]
public IActionResult PostMedicoes([FromBody]List <ParticulasMedicoes> _medicoes)
{
if (ModelState.IsValid)
{
foreach(var item in _medicoes)
{
_prtModel.InsertMedicaoParticulas(_configuration,item);
}
_ctrl = _ctrlModel.SelectControleApontamento(_configuration,"Particulas").FirstOrDefault();
_ctrl.ProxApont=_ctrl.ProxApont.Value.AddDays(_ctrl.DiasProximaMed);
_ctrlModel.UpdateControleApontamento(_configuration,_ctrl);
return Json(_medicoes);
}
else
log.Debug("Post não efetuado, Bad Request" + ModelState.ToString());
return BadRequest(ModelState);
}
[HttpPost]
public IActionResult PostMedicoesTamParticulas([FromBody]List <ParticulasTam> _medicoes)
{
if (ModelState.IsValid)
{
foreach(var item in _medicoes)
{
_prtModel.InsertParticulasTam(_configuration,item);
}
return Json(_medicoes);
}
else
log.Debug("Post não efetuado, Bad Request" + ModelState.ToString());
return BadRequest(ModelState);
}
[HttpPut]
public IActionResult PutParticulas([FromBody]Particulas _Particulas)
{
if (ModelState.IsValid)
{
var insert = _prtModel.UpdateParticulas(_configuration,_Particulas);
if(insert==true)
{
log.Debug("Put do Apontamento com sucesso:" + _Particulas);
return Ok();
}
return StatusCode(500,"Houve um erro, verifique o Log do sistema!");
}
else
log.Debug("Put não efetuado, Bad Request" + ModelState.ToString());
return BadRequest(ModelState);
}
}
} |
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using System.Threading;
using Union.Gateway.Abstractions;
namespace Union.Gateway.MsgIdHandler
{
public class UnionMsgIdHandlerHostedService : IHostedService
{
private readonly IUnionMsgConsumer jT808MsgConsumer;
private readonly IUnionMsgIdHandler jT808MsgIdHandler;
public UnionMsgIdHandlerHostedService(
IUnionMsgIdHandler jT808MsgIdHandler,
IUnionMsgConsumer jT808MsgConsumer)
{
this.jT808MsgIdHandler = jT808MsgIdHandler;
this.jT808MsgConsumer = jT808MsgConsumer;
}
public Task StartAsync(CancellationToken cancellationToken)
{
jT808MsgConsumer.Subscribe();
jT808MsgConsumer.OnMessage(jT808MsgIdHandler.Processor);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
jT808MsgConsumer.Unsubscribe();
return Task.CompletedTask;
}
}
}
|
using System;
using Microsoft.Xna.Framework;
namespace VoxelSpace {
// represents a field of voxel orientations
// usually mainly to determine texture directions; should generally coincide with gravity
public interface IVoxelOrientationField {
Orientation GetVoxelOrientation(Coords c);
}
} |
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.IO;
namespace CourseWork
{
public partial class Form1 : Form
{
RedBlackTree<DateKey, ProcessedReq> tree = new RedBlackTree<DateKey, ProcessedReq>();
List<ProcessedReq> list = new List<ProcessedReq>();
List<request> reqlist = new List<request>();
HashTableOA tab = new HashTableOA();
public Form1()
{
InitializeComponent();
Form MainForm = new MainForm();
MainForm.Hide();
tab.Clear();
string path = @"C:\Users\WhiteZetsu\source\repos\CourseWork\Requests.txt";
var flag = true;
try
{
StreamReader input = new StreamReader(path);
try
{
var ch = true;
dataGridView1.Rows.Clear();
while (!input.EndOfStream)
{
if (flag != false)
{
string s = input.ReadLine();
string[] subs = s.Split(' ');
if (!subs[subs.Length - 1].Contains('.'))
{
ch = false;
}
string[] dates = subs[subs.Length - 1].Split('.');
if (subs[0].ToCharArray()[0] != '8' || subs[0].ToCharArray().Length != 11)
{
ch = false;
}
var problem = subs[1].ToCharArray();
if (problem.Length > 30)
{
ch = false;
}
for (var i = 0; i < problem.Length; i++)
{
if ((problem[i] < 'А'))
{
if ((problem[i] != '!') && (problem[i] != ',') && (problem[i] != '.') && (problem[i] == ' ') && (problem[i] != '_'))
{
ch = false;
}
}
}
if (dates.Length != 3)
ch = false;
if (int.Parse(dates[0]) < 1 || int.Parse(dates[0]) > 31 || int.Parse(dates[1]) < 0 || int.Parse(dates[1]) > 12 || int.Parse(dates[2]) < 2007 || int.Parse(dates[2]) > 2030)
{
ch = false;
}
if (ch != false)
{
request r = new request(new Date(int.Parse(dates[0]), int.Parse(dates[1]), int.Parse(dates[2])), subs[0], subs[1].Replace('_', ' '));
tab.Add(r);
reqlist.Add(r);
}
else
{
flag = false;
break;
}
}
}
}
catch (Exception)
{
MessageBox.Show("Ошибка входных данных!");
Application.Exit();
}
finally
{
input.Close();
}
foreach (var it in reqlist)
{
dataGridView1.Rows.Add(tab.Hash(it, 0), tab.Find(it), it.number, it.problem, it.Key.day.ToString() + "." + it.Key.month.ToString() + "." + it.Key.year.ToString());
}
//////////////////////
tree.Clear();
string path1 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\ProcRequests.txt";
StreamReader input1 = new StreamReader(path1);
try
{
var ch1 = true;
dataGridView2.Rows.Clear();
while (!input1.EndOfStream)
{
string s1 = input1.ReadLine();
string[] subs1 = s1.Split(' ');
string[] dates1 = subs1[0].Split('.');
if (!subs1[0].Contains('.'))
{
ch1 = false;
}
if (subs1[subs1.Length - 1].ToCharArray()[0] != '8' || subs1[subs1.Length - 1].ToCharArray().Length != 11)
{
ch1 = false;
}
var problem1 = subs1[1].ToCharArray();
var worker = subs1[3].ToCharArray();
var customer = subs1[2].ToCharArray();
if (problem1.Length > 30)
{
ch1 = false;
}
for (var i = 0; i < problem1.Length; i++)
{
if ((problem1[i] < 'А'))
{
if ((problem1[i] != '!') && (problem1[i] != ',') && (problem1[i] != '.') && (problem1[i] == ' ') && (problem1[i] != '_'))
{
ch1 = false;
}
}
}
if (dates1.Length != 3)
ch1 = false;
if (int.Parse(dates1[0]) < 1 || int.Parse(dates1[0]) > 31 || int.Parse(dates1[1]) < 0 || int.Parse(dates1[1]) > 12 || int.Parse(dates1[2]) < 2007 || int.Parse(dates1[2]) > 2030)
{
ch1 = false;
}
for (var i = 0; i < worker.Length; i++)
{
if ((worker[i] < 'А'))
{
if ((worker[i] != '!') && (worker[i] != ',') && (worker[i] != '.') && (worker[i] == ' ') && (worker[i] != '_'))
{
ch1 = false;
}
}
}
for (var i = 0; i < customer.Length; i++)
{
if ((customer[i] < 'А'))
{
if ((customer[i] != '!') && (customer[i] != ',') && (customer[i] != '.') && (customer[i] == ' ') && (customer[i] != '_'))
{
ch1 = false;
}
}
}
if (ch1 != false)
{
ProcessedReq r = new ProcessedReq(new DateKey(int.Parse(dates1[0]), int.Parse(dates1[1]), int.Parse(dates1[2])), subs1[subs1.Length - 1], subs1[3].Replace('_', ' '), subs1[2].Replace('_', ' '), subs1[1].Replace('_', ' '));
list.Add(r);
tree.Add(r.Key, r);
}
else
{
flag = false;
break;
}
}
if (flag != false)
MessageBox.Show("Файлы успешно считаны!");
else
{
MessageBox.Show("Ошибка входных данных!");
Application.Exit();
}
}
catch (Exception)
{
MessageBox.Show("Ошибка входных данных!");
Application.Exit();
}
finally
{
input1.Close();
}
foreach (var it in list)
{
dataGridView2.Rows.Add(it.Key.dd.ToString() + "." + it.Key.mm.ToString() + "." + it.Key.yy.ToString(), it.problem, it.customer, it.worker, it.num);
}
}
catch (Exception)
{
MessageBox.Show("Ошибка входных данных!");
Application.Exit();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Form2 addForm = new Form2();
DialogResult dialogResult = addForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
request N = addForm.NewRequest();
if (tab.Find(N) == -1)
{
tab.Add(N);
reqlist.Add(N);
RefreshDataGrid();
MessageBox.Show("Заявка успешно добавлена");
}
else MessageBox.Show("Такая заявка уже существует!");
}
}
private void RefreshDataGrid()
{
dataGridView1.Rows.Clear();
foreach (var it in reqlist)
{
dataGridView1.Rows.Add(tab.Hash(it, 0), tab.Find(it), it.number, it.problem, it.Key.day.ToString() + "." + it.Key.month.ToString() + "." + it.Key.year.ToString());
}
}
private void RefreshDataGrid1()
{
dataGridView2.Rows.Clear();
foreach (var it in list)
{
dataGridView2.Rows.Add(it.Key.dd.ToString() + "." + it.Key.mm.ToString() + "." + it.Key.yy.ToString(), it.problem, it.customer, it.worker, it.num);
}
}
private void button4_Click(object sender, EventArgs e)
{
Form3 addForm = new Form3();
DialogResult dialogResult = addForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
int dd = 0;
int mm = 0;
int yy = 0;
string num = "";
string problem = "";
addForm.GetKey(ref dd, ref mm, ref yy, ref num, ref problem);
try
{
request Key = new request(new Date(dd, mm, yy), num, problem);
DateKey KeyTree = new DateKey(dd, mm, yy);
bool found = false;
if (tab.Find(Key) != -1)
{
if (tree.TryFind(KeyTree, out var outp))
{
foreach (var it in outp)
{
if (it.num == Key.number && it.problem == Key.problem)
{
DialogResult result=MessageBox.Show("Обнаружены связанные элементы. Удалить из обоих справочников?","Внимание!", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
tab.Delete(Key);
tree.Remove(KeyTree, it);
list.Remove(it);
reqlist.Remove(Key);
RefreshDataGrid();
RefreshDataGrid1();
MessageBox.Show("Заявка успешно удалена из обоих справочников!");
found = true;
break;
}
else
{
MessageBox.Show("Удаление отменено пользователем!");
found = true;
}
}
}
}
if (found != true)
{
tab.Delete(Key);
reqlist.Remove(Key);
RefreshDataGrid();
MessageBox.Show("Заявка успешно удалена!");
}
}
else MessageBox.Show("Такой заявки не существует!");
}
catch (Exception)
{
MessageBox.Show("Ошибка ввода!");
}
}
}
private void button5_Click_1(object sender, EventArgs e)
{
Form4 addForm = new Form4();
DialogResult dialogResult = addForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
int dd = 0;
int mm = 0;
int yy = 0;
string num = "";
string problem = "";
addForm.GetKey1(ref dd, ref mm, ref yy, ref num, ref problem);
request Key = new request(new Date(dd, mm, yy), num, problem);
try
{
var index = tab.Find(Key);
if (index != -1)
{
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add(tab.Hash(Key, 0), index, tab.data[index].number, tab.data[index].problem, tab.data[index].Key.day.ToString() + "." + tab.data[index].Key.month.ToString() + "." + tab.data[index].Key.year.ToString());
}
else MessageBox.Show("Такой заявки не существует!");
}
catch (Exception)
{
MessageBox.Show("Такой заявки не существует!");
}
}
}
private void button6_Click(object sender, EventArgs e)
{
RefreshDataGrid();
}
private void button8_Click(object sender, EventArgs e)
{
Form6 addForm = new Form6();
DialogResult dialogResult = addForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
ProcessedReq N = addForm.NewProcRequest();
bool foundin = false;
request K = new request(new Date(N.Key.dd, N.Key.mm, N.Key.yy), N.num, N.problem);
if (tab.Find(K)!=-1)
{
if (tree.TryFind(N.Key, out var check))
{
if (check != null)
{
foreach (var iter in check)
{
if (foundin != true)
{
if (iter.num == N.num && iter.problem == N.problem)
{
foundin = true;
break;
}
}
}
}
}
if (foundin != true)
{
tree.Add(N.Key, N);
list.Add(N);
RefreshDataGrid1();
MessageBox.Show("Обработанная заявка успешно добавлена!");
}
else
{
MessageBox.Show("Заявка уже обработана!");
}
}
else MessageBox.Show("Невозможно обработать несуществующую заявку!");
}
}
private void button9_Click(object sender, EventArgs e)
{
Form7 addForm = new Form7(ref tree);
DialogResult dialogResult = addForm.ShowDialog();
ProcessedReq a = addForm.NewProcRequest();
if (dialogResult == DialogResult.OK)
{
if (a != null)
{
tree.Remove(a.Key, a);
list.Remove(a);
RefreshDataGrid1();
MessageBox.Show("Обработанная заявка успешно удалена");
}
else MessageBox.Show("Такой обработанной заявки не существует!");
}
}
private void button10_Click(object sender, EventArgs e)
{
Form8 addForm = new Form8();
DialogResult dialogResult = addForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
var list = tree.GetValuesRange(addForm.Min(), addForm.Max());
try
{
dataGridView2.Rows.Clear();
foreach (var it in list)
{
dataGridView2.Rows.Add(it.Key.dd.ToString() + "." + it.Key.mm.ToString() + "." + it.Key.yy.ToString(), it.problem, it.worker, it.customer, it.num);
}
}
catch (Exception)
{
MessageBox.Show("Не существует обработанных заявок в указанном диапазоне!");
}
}
}
private void button11_Click(object sender, EventArgs e)
{
RefreshDataGrid1();
}
private void button12_Click(object sender, EventArgs e)
{
string path1 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\ProcRequests.txt";
string path2 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\Requests.txt";
foreach (var it in list)
{
it.customer = it.customer.Replace(" ", "_");
it.worker = it.worker.Replace(" ", "_");
it.problem = it.problem.Replace(" ", "_");
}
for (var i = 0; i < tab.data.Length; i++)
{
if (tab.data[i] != null)
{
tab.data[i].problem = tab.data[i].problem.Replace(" ", "_");
}
}
using (StreamWriter sw1 = new StreamWriter(path1))
{
foreach (var it in list)
{
sw1.WriteLine(it);
}
}
using (StreamWriter sw2 = new StreamWriter(path2))
{
for (var i = 0; i < tab.data.Length; i++)
{
if (tab.data[i] != null)
{
sw2.WriteLine(tab.data[i]);
}
}
}
DialogResult = DialogResult.OK;
Hide();
}
private void button13_Click(object sender, EventArgs e)
{
string path1 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\ProcRequests.txt";
string path2 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\Requests.txt";
foreach (var it in list)
{
it.customer= it.customer.Replace(" ", "_");
it.worker = it.worker.Replace(" ", "_");
it.problem = it.problem.Replace(" ", "_");
}
for (var i = 0; i < tab.data.Length; i++)
{
if (tab.data[i] != null)
{
tab.data[i].problem= tab.data[i].problem.Replace(" ", "_");
}
}
using (StreamWriter sw1 = new StreamWriter(path1))
{
foreach (var it in list)
{
sw1.WriteLine(it);
}
}
using (StreamWriter sw2 = new StreamWriter(path2))
{
for (var i = 0; i < tab.data.Length; i++)
{
if (tab.data[i] != null)
{
sw2.WriteLine(tab.data[i]);
}
}
}
Application.Exit();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
string path1 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\ProcRequests.txt";
string path2 = @"C:\Users\WhiteZetsu\source\repos\CourseWork\Requests.txt";
foreach (var it in list)
{
it.customer = it.customer.Replace(" ", "_");
it.worker = it.worker.Replace(" ", "_");
it.problem = it.problem.Replace(" ", "_");
}
for (var i = 0; i < tab.data.Length; i++)
{
if (tab.data[i] != null)
{
tab.data[i].problem = tab.data[i].problem.Replace(" ", "_");
}
}
using (StreamWriter sw1 = new StreamWriter(path1))
{
foreach (var it in list)
{
sw1.WriteLine(it);
}
}
using (StreamWriter sw2 = new StreamWriter(path2))
{
for (var i = 0; i < tab.data.Length; i++)
{
if (tab.data[i] != null)
{
sw2.WriteLine(tab.data[i]);
}
}
}
Application.Exit();
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.