text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ISESecurityLoginRemote
{
public class RemoteLogin
{
string path = PathProvider.RemoteLoginDll();
string extToken = "";
Dictionary<string,string> tokenData=new Dictionary<string,string>();
public RemoteLogin()
{
}
//public RemoteLogin(string link)
//{
// SetToken(link);
//}
public RemoteLogin(string token)
{
extToken = token;
}
public bool IsValidToken()
{
var token = GetToken();
return ReadToken(token);
}
public string GetNationalCode()
{
if (tokenData != null)
return tokenData["nationalCode"];
return string.Empty;
}
public string GetPersonelCode()
{
if (tokenData != null)
return tokenData["personelCode"];
return string.Empty;
}
private bool ReadToken(string token)
{
var assembly = AssemblyLoader.Load(path);
var obj = assembly.CreateInstance("ISESecurityLogin.RemoteTokenValidator");
Object ret = obj.GetType().InvokeMember("GetToken", BindingFlags.InvokeMethod, null, obj, new object[] { token });
tokenData = (Dictionary<string,string>)ret;
return tokenData.Keys.Count>0 ;
}
private string GetToken()
{
string token = "";
if (extToken.Length > 0)
token = extToken;
return token;
}
}
}
|
using LeaveApplication.Dal.Models;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace LeaveApplication.Dal.Configuration
{
public class LeaveConfiguration : BaseEntityConfiguration<Leave>
{
public override void Configure(EntityTypeBuilder<Leave> builder)
{
base.Configure(builder);
builder
.Property(p => p.LeaveType)
.IsRequired();
builder
.Property(p => p.Description)
.IsRequired();
builder
.HasMany(p => p.UserLeaves)
.WithOne(p => p.Leave)
.HasForeignKey(p => p.LeaveId);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Predictr.Data;
using Predictr.Models;
using Predictr.ViewModels;
namespace Predictr.Controllers
{
[RequireHttps]
[Authorize]
public class MyPredictrController : Controller
{
private readonly ApplicationDbContext _context;
public MyPredictrController(ApplicationDbContext context)
{
_context = context;
}
// GET: Fixtures
public IActionResult Index()
{
var user = User.FindFirst(ClaimTypes.NameIdentifier);
VM_MyPredictr vm = new VM_MyPredictr();
vm.Predictions = _context.Predictions.Where(p => p.ApplicationUser.Id == user.Value).ToList();
var allFixtures = _context.Fixtures.ToList();
foreach (Fixture fixture in allFixtures.ToList())
{
int searchingFor = fixture.Id;
foreach (Prediction prediction in vm.Predictions)
{
if (prediction.FixtureId == searchingFor)
{
allFixtures.Remove(fixture);
}
}
}
vm.UnPredictedFixtures = allFixtures.OrderBy(p => p.FixtureDateTime).ToList();
return View("Index", vm);
}
}
}
|
namespace ResolveUR.Library
{
using System.IO;
public class ResolveURFactory
{
const string Proj = "proj";
const string Sln = "sln";
public static IResolve GetResolver(
ResolveUROptions options,
HasBuildErrorsEventHandler hasBuildErrorsEvent,
ProjectResolveCompleteEventHandler projectResolveCompleteEvent)
{
IResolveUR resolveUr = new ProjectReferencesResolveUR
{
ShouldResolvePackage = options.ShouldResolvePackages,
BuilderPath = options.MsBuilderPath,
FilePath = options.FilePath
};
resolveUr.HasBuildErrorsEvent += hasBuildErrorsEvent;
resolveUr.ProjectResolveCompleteEvent += projectResolveCompleteEvent;
if (options.FilePath.EndsWith(Proj))
return resolveUr;
if (options.FilePath.EndsWith(Sln))
return new SolutionReferencesResolveUR(resolveUr);
if (resolveUr == null)
throw new InvalidDataException(
"The file path supplied(arg 0) must either be a solution or project file");
return resolveUr;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Salle.Model.Commun;
namespace Salle.Model.Salle
{
public interface IClient
{
int ClientCommande { get; set; }
string Repas { get; set; }
bool Mange { get; set; }
void prendreRepas();
void choisirRepas(Carte carte);
void mangerPlat();
void commanderVin(Serveur serveur);
void commanderEau(Serveur serveur);
void commanderPain(Serveur serveur);
}
}
|
using System.Collections.Generic;
using Lanches.Web.Models;
namespace Lanches.Web.ViewModels
{
public class HomeViewModel
{
public IEnumerable<Lanche> LanchesPreferidos { get; set; }
}
} |
using System;
using System.IO;
using System.Security.Cryptography;
namespace Ingen.Network
{
public class AesCryptoService : ICryptoService, IDisposable
{
public byte[] IV => CryptoService?.IV;
public byte[] Key => CryptoService?.Key;
private AesManaged CryptoService { get; }
private ICryptoTransform Encryptor { get; }
private ICryptoTransform Decryptor { get; }
public AesCryptoService()
{
CryptoService = new AesManaged
{
BlockSize = 128,
KeySize = 256,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
};
CryptoService.GenerateIV();
CryptoService.GenerateKey();
Encryptor = CryptoService.CreateEncryptor();
Decryptor = CryptoService.CreateDecryptor();
}
public AesCryptoService(byte[] initalVector, byte[] key)
{
CryptoService = new AesManaged
{
BlockSize = 128,
KeySize = 256,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
IV = initalVector,
Key = key
};
Encryptor = CryptoService.CreateEncryptor();
Decryptor = CryptoService.CreateDecryptor();
}
public byte[] Encrypt(byte[] input)
{
using (var outputStream = new MemoryStream())
using (var cStream = new CryptoStream(outputStream, Encryptor, CryptoStreamMode.Write))
{
cStream.Write(input, 0, input.Length);
cStream.FlushFinalBlock();
return outputStream.ToArray();
}
}
public byte[] Decrypt(byte[] input)
{
using (var outputStream = new MemoryStream())
using (var cStream = new CryptoStream(outputStream, Decryptor, CryptoStreamMode.Write))
{
cStream.Write(input, 0, input.Length);
cStream.FlushFinalBlock();
return outputStream.ToArray();
}
}
public void Dispose()
{
Decryptor.Dispose();
Encryptor.Dispose();
CryptoService.Dispose();
}
}
}
|
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CabMedical
{
public partial class OrdonnanceData : System.Web.UI.Page
{
ADO d = new ADO();
public void RemplirGrid()
{
d.connecter();
if (d.dt.Rows != null)
{
d.dt.Clear();
}
d.cmd.CommandText = "select Ordonnances.Num_Ordonnance, Date_Ordonnance , Ville_Ordonnances , Description_Ordonnances ,medecin , Nom_Prénom_Patient ,consultation from Ordonnances join Patients on Patients.Num_Patient = Ordonnances.patient";
d.cmd.Connection = d.con;
d.dr = d.cmd.ExecuteReader();
d.dt.Load(d.dr);
GridView_Ordonnance.DataSource = d.dt;
GridView_Ordonnance.DataBind();
d.dr.Close();
d.Deconnecter();
}
DataSet dsPat = new DataSet();
SqlDataAdapter daPat;
public void RemplirDrop_Patient()
{
string con = "Data Source=DESKTOP-HT16NSJ\\SQLEXPRESS;Initial Catalog=MyCabMedDB2;Integrated Security=True";
string req = "select Nom_Prénom_Patient , Num_Patient from Patients";
daPat = new SqlDataAdapter(req, con);
daPat.Fill(dsPat, "Patients");
DropDownList_Patient.DataTextField = "Nom_Prénom_Patient";
DropDownList_Patient.DataValueField = "Num_Patient";
DropDownList_Patient.DataSource = dsPat.Tables["Patients"];
DropDownList_Patient.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RemplirGrid();
RemplirDrop_Patient();
}
if (Session["User"] == null)
{
Response.Redirect("Login.aspx");
}
TextBox_Date_Ordonnance.Enabled = false;
TextBox_Ville.Enabled = false;
TextBox1_Description.Enabled = false;
TextBox_Medecin.Enabled = false;
DropDownList_Patient.Enabled = false;
TextBox_Consultation.Enabled = false;
}
protected void Btn_Modifier_Click(object sender, EventArgs e)
{
d.connecter();
d.cmd.CommandText = " update Ordonnances set Ville_Ordonnances = '"+TextBox_Ville.Text+"' , Description_Ordonnances = '"+TextBox1_Description.Text+"' where Num_Ordonnance = '"+Textox_Numero_Ordonnance.Text+"' ";
d.cmd.Connection = d.con;
d.cmd.ExecuteNonQuery();
RemplirGrid();
d.Deconnecter();
Response.Write("<script>alert('Update');window.location = 'OrdonnanceData.aspx';</script>");
}
protected void GridView_Ordonnance_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int a = e.RowIndex;
int code = int.Parse(GridView_Ordonnance.Rows[a].Cells[2].Text);
d.connecter();
d.cmd.CommandText = " delete from Ordonnances where Num_Ordonnance = '"+code+"'";
d.cmd.Connection = d.con;
d.cmd.ExecuteNonQuery();
RemplirGrid();
d.Deconnecter();
}
protected void GridView_Ordonnance_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int r = e.NewSelectedIndex;
Textox_Numero_Ordonnance.Text = GridView_Ordonnance.Rows[r].Cells[2].Text;
TextBox_Date_Ordonnance.Text = GridView_Ordonnance.Rows[r].Cells[3].Text;
TextBox_Ville.Text = GridView_Ordonnance.Rows[r].Cells[4].Text;
TextBox1_Description.Text = GridView_Ordonnance.Rows[r].Cells[5].Text;
TextBox_Medecin.Text = GridView_Ordonnance.Rows[r].Cells[6].Text;
//DropDownList_Patient.SelectedValue = GridView_Ordonnance.Rows[r].Cells[7].Text;
TextBox_Consultation.Text = GridView_Ordonnance.Rows[r].Cells[8].Text;
//TextBox_Date_Ordonnance.Enabled = true;
TextBox_Ville.Enabled = true;
TextBox1_Description.Enabled = true;
}
protected void Button_Actualiser_Click(object sender, EventArgs e)
{
RemplirGrid();
}
protected void Button_Imprimer_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-GPDIAMB\\SQLEXPRESS;Initial Catalog=MyCabMedDB2;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Ordonnances where Num_Ordonnance = '" + TextBox_Num_Ordonnance.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
ReportDocument crp = new ReportDocument();
crp.Load(Server.MapPath("CrystalReport_Ordonnance.rpt"));
crp.SetDataSource(ds.Tables["table"]);
CrystalReportViewer1.ReportSource = crp;
crp.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "Ordonnances");
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace _05._Teamwork_Projects
{
class Team
{
public Team(string creator, string name)
{
Creator = creator;
Name = name;
Members = new List<string>();
}
public string Name { get; set; }
public string Creator { get; set; }
public List<string> Members { get; set; }
public int Count()
{
return Members.Count + 1;
}
public void UserJoin(string userName)
{
Members.Add(userName);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SMARTplanner.Entities.Helpers;
namespace SMARTplanner.Entities.Domain
{
public class ProjectUserAccess
{
[Key, Column(Order = 0)]
public long ProjectId { get; set; }
[Key, Column(Order = 1)]
public string UserId { get; set; }
public virtual Project Project { get; set; }
public virtual ApplicationUser User { get; set; }
public ProjectAccess ProjectAccess { get; set; }
public bool CanGrantAccess { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Telerik.OpenAccess;
namespace Sparda.Contracts
{
public interface IService
{
bool IsPublic { get; set; }
string Name { get; set; }
string Owner { get; set; }
int? Version { get; set; }
string DisplayName { get; set; }
bool ShareSettings { get; set; }
[Obsolete]
bool QueryAccessRightInterceptor(string entityName);
[Obsolete]
void ChangeAccessRightInterceptor(string entityName, UpdateOperations operations);
[Obsolete]
Expression<Func<T, bool>> QueryInterceptor<T>(string entityName);
Expression<Func<T, bool>> QueryInterceptor<T>();
[Obsolete]
void ChangeInterceptor(string entityName, OpenAccessContext context, object entity, UpdateOperations operations);
[Obsolete]
void ChangeInterceptor<T>(string entityName, object entity, UpdateOperations operations);
void ChangeInterceptor<T>(object entity, UpdateOperations operations);
//bool HasRight();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CacheSqlXmlService.SqlManager
{
[Flags]
public enum ConnectFlags
{
And =0x1,
Or =0x2,
Group =0x4,
EndGroup = 0x8,
AndGroup = 0x16,
OrGroup = 0x32
}
public static class ConnectFlagsExtend
{
public static string ToSqlString(this ConnectFlags flag)
{
switch (flag)
{
case ConnectFlags.And:
return " AND ";
case ConnectFlags.Or:
return " OR ";
case ConnectFlags.Group:
return " (";
case ConnectFlags.EndGroup:
return ") ";
case ConnectFlags.AndGroup:
return " AND (";
case ConnectFlags.OrGroup:
return " OR (";
default:
return string.Empty;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TravelExperts
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["PackageID"] = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Session["PackageID"] = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[0].Text);
}
}
} |
using ScriptableObjectFramework.Variables;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ScriptableObjectFramework.Conditions.Watchers
{
public class IntComparisonWatcher : BaseConditionWatcher<int, IntVariable, IntComparableConditionCollection>{ }
}
|
using System.Collections.Generic;
using TheMapToScrum.Back.BLL.Interfaces;
using TheMapToScrum.Back.BLL.Mapping;
using TheMapToScrum.Back.DAL.Entities;
using TheMapToScrum.Back.DTO;
using TheMapToScrum.Back.Repositories.Contract;
using TheMapToScrum.Back.Repositories.Repo;
namespace TheMapToScrum.Back.BLL
{
public class ScrumMasterLogic : IScrumMasterLogic
{
private readonly IScrumMasterRepository _repo;
public ScrumMasterLogic(IScrumMasterRepository repo)
{
_repo = repo;
}
public List<ScrumMasterDTO> List()
{
List<ScrumMasterDTO> retour = new List<ScrumMasterDTO>();
List<ScrumMaster> liste = _repo.GetAll();
retour = MapScrumMasterDTO.ToDto(liste);
return retour;
}
public List<ScrumMasterDTO> ListActive()
{
List<ScrumMasterDTO> retour = new List<ScrumMasterDTO>();
List<ScrumMaster> liste = _repo.GetAllActive();
retour = MapScrumMasterDTO.ToDto(liste);
return retour;
}
public ScrumMasterDTO Create(ScrumMasterDTO objet)
{
ScrumMaster entite = MapScrumMaster.ToEntity(objet, true);
ScrumMaster resultat = _repo.Create(entite);
objet = MapScrumMasterDTO.ToDto(resultat);
return objet;
}
public ScrumMasterDTO Update(ScrumMasterDTO objet)
{
ScrumMaster entity = MapScrumMaster.ToEntity(objet, false);
ScrumMaster resultat = _repo.Update(entity);
ScrumMasterDTO retour = MapScrumMasterDTO.ToDto(resultat);
return retour;
}
public ScrumMasterDTO GetById(int Id)
{
ScrumMasterDTO retour = new ScrumMasterDTO();
ScrumMaster objet = _repo.Get(Id);
retour = MapScrumMasterDTO.ToDto(objet);
return retour;
}
public bool Delete(int Id)
{
bool resultat = _repo.Delete(Id);
return resultat;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaskScheduler
{
public class TaskScheduler : ITaskScheduler
{
private List<Task> Tasks;
private List<Task> Results;
private List<Task> TaskPath;
/// <summary>
/// Run tasks in order of dependencies
/// </summary>
/// <param name="inTasks">A list of tasks unordered</param>
/// <returns>Returns results in order of execution</returns>
public List<Task> RunTasks(List<Task> inTasks)
{
Tasks = inTasks;
Results = new List<Task>();
foreach (var task in Tasks)
{
TaskPath = new List<Task>();
if (task.Dependency != null)
{
CheckDependency(task);
}
if (!task.Completed)
{
task.Completed = true;
Results.Add(task);
}
}
return Results;
}
/// <summary>
/// Checks the dependencies of a task, if needed, we run that task first
/// </summary>
/// <param name="inTask">Task to check for dependent tasks</param>
public void CheckDependency(Task inTask)
{
Task task = inTask;
var isReference = TaskPath.FirstOrDefault(t => t.Name == task.Name);
if (isReference != null)
{
throw new Exception("Error - This is a circular dependency");
}
else
{
TaskPath.Add(task);
var dependency = (from t in Tasks
where t.Name == task.Dependency
select t).FirstOrDefault();
if (dependency != null)
{
CheckDependency(dependency);
Tasks.Find(t => t.Name == dependency.Name).Completed = true;
Results.Add(dependency);
}
}
}
}
} |
using System;
using DelftTools.Utils.PropertyBag;
namespace SharpMap.UI.Tools
{
public class QueryResultEventArgs : EventArgs
{
public PropertyTable Result;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Speed
{
Program prog = new Program();
public void IncreaseSpeed()
{
string test = prog.ReturnScore().ToString();
if (5 >= prog.ReturnScore())
{
System.Threading.Thread.Sleep(200);
}
else if (10 >= prog.ReturnScore())
{
System.Threading.Thread.Sleep(150);
}
else if (50 >= prog.ReturnScore())
{
System.Threading.Thread.Sleep(50);
}
else if (999 >= prog.ReturnScore())
{
System.Threading.Thread.Sleep(40);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace LightBoxRectSubForm.windows {
/// <summary>
/// WidFirstId.xaml 的交互逻辑
/// </summary>
public partial class WidFirstId : Window {
public int newId;
private int oldId;
public WidFirstId(int id) {
InitializeComponent();
oldId = id;
txtId.Text = Convert.ToString(oldId);
}
private void btnCancel_Click(object sender, RoutedEventArgs e) {
DialogResult = false;
}
private void btnOk_Click(object sender, RoutedEventArgs e) {
try {
newId = Convert.ToInt32(txtId.Text);
if(newId <= 0) {
return;
}
} catch (Exception) {
return;
}
DialogResult = true;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.MRP.TRANS
{
[Serializable]
public partial class MrpFiShiftPlan : EntityBase
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Display(Name = "MrpFiShiftPlan_ProductLine", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string ProductLine { get; set; }
[Display(Name = "MrpFiShiftPlan_Item", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string Item { get; set; }
//[Display(Name = "MrpFiShiftPlan_Location", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
//public string Location { get; set; }
[Display(Name = "MrpFiShiftPlan_PlanDate", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public DateTime PlanDate { get; set; }
[Display(Name = "MrpFiShiftPlan_Shift", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string Shift { get; set; }
[Display(Name = "MrpFiShiftPlan_Sequence", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public int Sequence { get; set; }
[Display(Name = "MrpFiShiftPlan_PlanVersion", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public DateTime PlanVersion { get; set; }
[Display(Name = "MrpFiShiftPlan_Qty", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public double Qty { get; set; }
[Display(Name = "MrpFiShiftPlan_Machine", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string Machine { get; set; }
[Display(Name = "MrpFiShiftPlan_MachineDescription", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string MachineDescription { get; set; }
[Display(Name = "MrpFiShiftPlan_MachineQty", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public Double MachineQty { get; set; }
[Display(Name = "MrpFiShiftPlan_MachineType", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public com.Sconit.CodeMaster.MachineType MachineType { get; set; }
[Display(Name = "MrpFiShiftPlan_Island", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string Island { get; set; }
[Display(Name = "MrpFiShiftPlan_IslandDescription", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public string IslandDescription { get; set; }
//[Display(Name = "MrpFiShiftPlan_DateIndex", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
//public string DateIndex { get; set; }
[Display(Name = "MrpFiShiftPlan_ShiftQuota", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public Double ShiftQuota { get; set; }
[Display(Name = "MrpFiShiftPlan_ShiftType", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public com.Sconit.CodeMaster.ShiftType ShiftType { get; set; }
[Display(Name = "MrpFiShiftPlan_WorkDayPerWeek", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public Double WorkDayPerWeek { get; set; }
[Display(Name = "MrpFiShiftPlan_ShiftPerDay", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public int ShiftPerDay { get; set; }
[Display(Name = "MrpFiShiftPlan_UnitCount", ResourceType = typeof(Resources.MRP.MrpFiShiftPlan))]
public double UnitCount { get; set; }
public DateTime StartTime { get; set; }
public DateTime WindowTime { get; set; }
public string LocationFrom { get; set; }
public string LocationTo { get; set; }
public string Bom { get; set; }
public int OrderDetailId { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
MrpFiShiftPlan another = obj as MrpFiShiftPlan;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Final_Project
{
class Dogs : Animal
{
//Variables
private string type;
//Get, set and construct
public new string Type { get { return type; } }
public Dogs(int ID, double amtWater, double weight, int age, string colour, double dailyCost, string type)
: base(ID, amtWater, dailyCost, weight, age, colour)
{
this.AmtWater = amtWater;
this.Weight = weight;
this.Age = age;
this.Colour = colour;
this.DailyCost = dailyCost;
this.type = type;
}
public override string DisplayInfo()
{
// String to hold all dog informations
string info = "Amount of Water \tWeight \tAge \tColour \tDaily Cost \r\n" +
Convert.ToString(AmtWater) + "\t\t" +
Convert.ToString(Weight) + "\t" +
Convert.ToString(Age) + "\t" +
Colour + "\t" +
Convert.ToString(DailyCost);
// Return string
return (info);
}
public override string DisplayType()
{
string type_info = type;
return (type_info);
}
public override double GetTax()
{
double totalTax = 0;
return (totalTax);
}
}
}
|
namespace KK.AspNetCore.EasyAuthAuthentication.Samples.Web.Repositories
{
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IRepository
{
Task<IEnumerable<string>> GetRoles(string userIdentifier);
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorSample1.Models;
using RazorSample1.Models.Enums;
using RazorSample1.Services;
namespace RazorSample1.Pages.Catalog
{
public class editModel : PageModel
{
private readonly IItemRepository itemRepository;
public editModel(IItemRepository itemRepository, IWebHostEnvironment webHostEnvironment)
{
this.itemRepository = itemRepository;
this.webHostEnvironment = webHostEnvironment;
}
// Used to get the full path for storing the uploaded photos.
private readonly IWebHostEnvironment webHostEnvironment;
[BindProperty]
public Item Item { get; set; }
[BindProperty]
public List<Topics> Topics { get; set; }
public List<Consumers> Consumers { get; set; }
[BindProperty]
public IFormFile ScreenShotPhoto { get; set; }
public IActionResult OnGet(int? id)
{
if (id.HasValue)
{
Item = itemRepository.GetItem(id.Value);
} else
{
Item = new Item();
}
if (Item == null)
{
return RedirectToPage("/NotFound");
}
return Page();
}
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
Item.Topics = Topics;
Item.Consumers = Consumers;
if (ScreenShotPhoto != null)
{
if (Item.ScreenShotPath != null)
{
string filePath = Path.Combine(webHostEnvironment.WebRootPath, "catalogScreenShots", Item.ScreenShotPath);
System.IO.File.Delete(filePath);
}
Item.ScreenShotPath = ProcessUploadedFile(ScreenShotPhoto);
}
if (Item.Id > 0)
{
Item = itemRepository.Update(Item);
}
else
{
Item = itemRepository.Add(Item);
}
return RedirectToPage("index");
}
// In the event there are validation issues we can re-render the page
// so the user can correct any errors.
return Page();
}
private string ProcessUploadedFile(IFormFile file)
{
string uniqueFileName = null;
if (file != null)
{
string uploadsFolder =
Path.Combine(webHostEnvironment.WebRootPath, "catalogScreenShots");
uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(fileStream);
}
}
return uniqueFileName;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApp.Data.Models
{
public partial class TiresModelsBrands
{
public static TiresModelsBrands CreateAsgt(string brand, string model, string country, string category, double startPrice = 0)
{
return new TiresModelsBrands
{
Id = Guid.NewGuid(),
Brand = brand,
Model = model,
Category = category,
StartPrice = startPrice,
Country = country
};
}
public void UpdateAsgt(string brand, string model, string country, string category, double startPrice)
{
Brand = brand;
Model = model;
Category = category;
StartPrice = startPrice;
Country = country;
}
}
}
|
using Galeri.Entities.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Galeri.Entities.Concrete
{
public class Model:IEntity
{
public Model()
{
Tasitlari = new List<Tasit>();
}
public int Id { get; set; }
public string ModelAdi { get; set; }
public string Vites { get; set; }
public string Yakit { get; set; }
public short Yil { get; set; }
public string KasaTipi { get; set; }
public short MotorGucu { get; set; }
public short MotorHacmi { get; set; }
public string Cekis { get; set; }
public short AzamiSurat { get; set; }
public short BagajKapasitesi { get; set; }
public int MarkaId { get; set; }
public virtual Marka Markasi { get; set; }
public virtual ICollection<Tasit> Tasitlari { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMoveHV : CharacterBehaviour
{
protected override void OnHorizontal()
{
hInput = Input.GetAxis("Horizontal")*moveSpeed.value;
movement.Set(hInput,yVar,vInput);
}
}
|
using AppNotas.Modelo;
using CarritoCompras.Modelo;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CarritoCompras.Service
{
public class ApiServiceAuthentication
{
public static async Task<bool> Login(UserAuthentication oUsuario)
{
try
{
HttpClient client = new HttpClient();
var body = JsonConvert.SerializeObject(oUsuario);
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await client.PostAsync(AppSettings.ApiAuthentication("LOGIN"), content);
if (response.StatusCode.Equals(HttpStatusCode.OK))
{
var jsonResult = await response.Content.ReadAsStringAsync();
ResponseAuthentication oResponse = JsonConvert.DeserializeObject<ResponseAuthentication>(jsonResult);
AppSettings.oAuthentication = oResponse;
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
string t = ex.Message;
return false;
}
}
public static async Task<bool> RegistrarUsuario(Usuario oUsuario)
{
bool respuesta = true;
try
{
UserAuthentication oUser = new UserAuthentication()
{
email = oUsuario.Email,
password = oUsuario.Clave,
returnSecureToken = true
};
HttpClient client = new HttpClient();
var body = JsonConvert.SerializeObject(oUser);
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await client.PostAsync(AppSettings.ApiAuthentication("SIGNIN"), content);
if (response.StatusCode.Equals(HttpStatusCode.OK))
{
var jsonResult = await response.Content.ReadAsStringAsync();
ResponseAuthentication oResponse = JsonConvert.DeserializeObject<ResponseAuthentication>(jsonResult);
if(oResponse != null)
{
respuesta = await ApiServiceFirebase.RegistrarUsuario(oUsuario, oResponse);
}
else
{
respuesta = false;
}
}
else
{
respuesta = false;
}
}
catch (Exception ex)
{
string t = ex.Message;
respuesta = false;
}
return respuesta;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using ExamOnline.BaseClass;
namespace ExamOnline.Admin
{
public partial class ExaminationDetail : System.Web.UI.Page
{
private static int id;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AdminName"] == null)
{
Response.Redirect("../Login.aspx");
}
if (!IsPostBack)
{
id = Convert.ToInt32(Request.QueryString["Eid"]);
DalAdmin dal = new DalAdmin();
SqlDataReader sdr = dal.GetSdrInformation("select * from F_Test where ID=" + id);
sdr.Read();
txtsubject.Text = sdr["TestContent"].ToString();
txtAnsA.Text = sdr["TestAns1"].ToString();
txtAnsB.Text = sdr["TestAns2"].ToString();
txtAnsC.Text = sdr["TestAns3"].ToString();
txtAnsD.Text = sdr["TestAns4"].ToString();
rblRightAns.SelectedValue = sdr["RightAns"].ToString();
string fb = sdr["Pub"].ToString();
if (fb == "1")
cbFB.Checked = true;
else
cbFB.Checked = false;
lblkm.Text = sdr["TestCourse"].ToString();
sdr.Close();
}
}
protected void btnconfirm_Click(object sender, EventArgs e)
{
if (txtsubject.Text == "" || txtAnsA.Text == "" || txtAnsB.Text == "" || txtAnsC.Text == "" || txtAnsD.Text == "")
{
MessageBox.Show("请将信息填写完整");
return;
}
else
{
string isfb = "";
if (cbFB.Checked == true)
isfb = "1";
else
isfb = "0";
string str = "update F_Test set TestContent='" + txtsubject.Text.Trim() + "',TestAns1='" + txtAnsA.Text.Trim() + "',TestAns2='" + txtAnsB.Text.Trim() + "',TestAns3='" + txtAnsC.Text.Trim() + "',TestAns4='" + txtAnsD.Text + "',RightAns='" + rblRightAns.SelectedValue.ToString() + "',Pub='" + isfb + "' where ID=" + id;
BaseClass.BaseClass.OperateData(str);
Response.Redirect("ExaminationInfo.aspx");
}
}
protected void btnconcel_Click(object sender, EventArgs e)
{
Response.Redirect("ExaminationInfo.aspx");
}
}
} |
using System;
using System.Collections.Generic;
namespace Core.Entities
{
public partial class RTeam
{
public int RTeamId { get; set; }
public int RLeagueId { get; set; }
public string TeamName { get; set; }
public bool? FCheck { get; set; }
public RLeague RLeague { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace MessageClicker.Web.Models
{
public class UserView
{
public int Id { get; set; }
[Required(ErrorMessage = "Введите login")]
public string Login { get; set; }
[Required(ErrorMessage = "Введите пароль")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Пароли должны совпадать")]
public string ConfirmPassword { get; set; }
}
} |
using Xamarin.Forms;
namespace RRExpress.Seller.Views {
public partial class AddGoodsView : ContentPage {
public AddGoodsView() {
InitializeComponent();
}
}
}
|
using gView.Framework.Data.Cursors;
namespace gView.Framework.Data
{
public class XmlCursor : IXmlCursor
{
private string _xml;
public XmlCursor(string xml)
{
_xml = xml;
}
#region IXmlCursor Member
public string Xml
{
get { return _xml; }
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Generics
{
internal class ClassExc04<T>
{
T[] arr;
public ClassExc04(T[] arr)
{
this.arr = arr;
}
public T this[int k]
{
get
{
return arr[k];
}
set
{
arr[k] = value;
}
}
public void Show()
{
foreach (T item in arr)
{
Console.Write(" | " + item);
}
Console.WriteLine(" |");
}
}
internal class Exc04
{
public static void MainExc04()
{
int[] array = new int[] { 1, 2, 3, 4, 5 };
ClassExc04<int> ObjA = new ClassExc04<int>(array);
char[] charray = new char[] { 'C', 'D', 'R', 'M' };
ClassExc04<char> ObjB = new ClassExc04<char>(charray);
ObjA[4] = 13;
Console.WriteLine(ObjA[4]);
ObjA.Show();
ObjB[1] = 'T';
Console.WriteLine(ObjB[1]);
ObjB.Show();
}
}
}
|
using Anywhere2Go.DataAccess.Entity;
using System.Collections.Generic;
namespace Claimdi.Account.Models
{
public class ReportViewModel
{
public string RepTaskId { get; set; }
public string RepTaskProcessId { get; set; }
public string RepInsurerId { get; set; }
public string RepTaskTypeId { get; set; }
public string RepDepartmentId { get; set; }
public string RepStartDate { get; set; }
public string RepEndDate { get; set; }
public string RepTaskDisplay { get; set; }
public List<TaskReport> TaskReportData { get; set; }
public List<TaskInspectionReport> TaskInspectionReportData { get; set; }
public List<InsPaymentReport> InsPaymentReportData { get; set; }
public List<InsCountTaskReport> InsCountTaskReportData { get; set; }
public string RepProvinceCode { get; set; }
public string RepAmphurCode { get; set; }
public string RepDistrictCode { get; set; }
public string RepCarRegis { get; set; }
public string RepComId { get; set; }
public string RepAssignAccId { get; set; }
// public List<SurveyorReport> SurveyorReportData { get; set; }
}
public class ReportSearchModel
{
public string RepTaskDisplay { get; set; }
public string RepProcessId { get; set; }
public string RepInsurerId { get; set; }
public string RepTaskTypeId { get; set; }
public string RepDepartmentId { get; set; }
public string RepStartDate { get; set; }
public string RepEndDate { get; set; }
public List<TaskReport> TaskReportData { get; set; }
public string RepProvinceCode { get; set; }
public string RepAmphurCode { get; set; }
public string RepDistrictCode { get; set; }
public string RepCarRegis { get; set; }
public string RepComId { get; set; }
public string RepEmployeeId { get; set; }
}
} |
using System;
namespace PostgresIssue855
{
public class TestClass
{
// Can be ignored in this sample
public int Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public TestSubClass SubClass { get; set; }
}
} |
using System.Drawing;
namespace RectangleGame.Map
{
/// <summary>
/// An empty map without any additional objects.
/// </summary>
class Map
{
/******** Variables ********/
/// <summary>
/// The position of the map. It will not automatically be drawn at this point!
/// </summary>
public Point position;
/// <summary>
/// The size of the map.
/// </summary>
public Size size;
/// <summary>
/// The pen used to draw the outer part of the map.
/// </summary>
public Pen pen;
/// <summary>
/// The brush used to draw the inner of the map.
/// </summary>
public Brush brush;
/******** Functions ********/
/// <summary>
/// Creates a new map with the specified size.
/// </summary>
/// <param name="width">The width of the map.</param>
/// <param name="height">The height of the map.</param>
public Map(int width, int height)
{
size = new Size(width, height);
// Center map, if it's smaller than the screen
position = new Point(0, 0);
if(width < Program.mainForm.ClientSize.Width)
{
position.X = Program.mainForm.ClientSize.Width / 2 - size.Width / 2;
}
if (height < Program.mainForm.ClientSize.Height)
{
position.Y = Program.mainForm.ClientSize.Height / 2 - size.Height / 2;
}
#warning Exception because pen was already being used
pen = new Pen(Brushes.Black, 2);
brush = Brushes.White;
}
/// <summary>
/// Draw the map.
/// </summary>
/// <param name="g">The graphics object that is used for drawing.</param>
public virtual void Draw(Graphics g)
{
Rectangle tempRectangle = new Rectangle(new Point(), size);
g.FillRectangle(brush, tempRectangle);
g.DrawRectangle(pen, tempRectangle);
}
/// <summary>
/// Nothing in here at the moment.
/// </summary>
public virtual void Update() { }
/// <summary>
/// Convert display coordinates to map coordinates.
/// </summary>
/// <param name="displayLocation">Location in display coordinates.</param>
/// <returns>Location in map coordinates.</returns>
public Point ToMapCoordinates(Point displayLocation)
{
Point mapLocation = displayLocation;
mapLocation.Y -= position.Y;
mapLocation.X -= position.X;
return (mapLocation);
}
/// <summary>
/// Convert map coordinates to display coordinates.
/// </summary>
/// <param name="mapLocation">Location in map coordinates.</param>
/// <returns>Location in display coordinates.</returns>
public Point ToDisplayCoordinates(Point mapLocation)
{
Point displayLocation = mapLocation;
displayLocation.X += position.X;
displayLocation.Y += position.Y;
return (displayLocation);
}
}
}
|
using System;
namespace IrsMonkeyApi.Models.Dto
{
public class OrderDto
{
public int OrderStatusId { get; set; }
public DateTime OrderDate { get; set; }
public float Discount { get; set; }
public string DiscountType { get; set; }
public string DiscountCode { get; set; }
public Guid MemberId { get; set; }
public float OrderTotal { get; set; }
public int PaymentTypeID { get; set; }
public string SubscriptionID { get; set; }
public DateTime PaymentStartDate { get; set; }
}
} |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using zm.Questioning;
using zm.Users;
using zm.Util;
namespace zm.Levels
{
public class LevelsModel : GenericSingleton<LevelsModel>
{
#region Constants
/// <summary>
/// Path of directory that holds all serialized levels as individual files
/// </summary>
public static readonly string LevelsPath = Application.streamingAssetsPath + "/levels.txt"; //TODO: private
#endregion Constants
#region Private Methods
/// <summary>
/// Serialize all levels from collection. To ensure that new users will be saved.
/// </summary>
private void SaveLevels()
{
string s = JsonUtility.ToJson(levels, true);
using (StreamWriter writer = new StreamWriter(LevelsPath, false))
{
writer.Write(s);
}
}
#endregion Private Methods
#region Fields and Properties
/// <summary>
/// List of all levels that exist in this game.
/// </summary>
public LevelsCollection levels; //TODO switch this to be private
/// <summary>
/// Returns Collection of all levels that exist.
/// </summary>
public LevelsCollection Levels
{
get { return levels; }
}
/// <summary>
/// Level that is currently selected.
/// </summary>
public Level CurrentLevel;
/// <summary>
/// Flag indicating if this model is initialized.
/// </summary>
private bool initialized;
#endregion Fields and Properties
#region Public Methods
/// <summary>
/// Initialize LevelsModel, populate all levels data.
/// </summary>
public override void Initialize()
{
if (initialized) { return; }
initialized = true;
using (StreamReader reader = new StreamReader(LevelsPath))
{
levels = JsonUtility.FromJson<LevelsCollection>(reader.ReadToEnd());
}
CurrentLevel = Levels.Collection.First();
}
/// <summary>
/// Loads all necessary data for current level.
/// This is done before scene is loaded, so all data will be prepared for populating scene.
/// </summary>
public void LoadCurrentLevel()
{
QuestionsModel.Instance.Initialize();
List<Question> questions = new List<Question>();
foreach (var category in CurrentLevel.Categories)
{
questions.AddRange(QuestionsModel.Instance.GetQuestions(category));
}
CurrentLevel.InitializeQuestions(questions);
}
#endregion Public Methods
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ManageDomain.DAL
{
public class ServerWatchDal
{
public const int ChartMaxItmes = 4000;//10万
public void AddDataCpu(CCF.DB.DbConn dbconn, Models.ServerWatch.DataCpu model)
{
string sql = "INSERT INTO `datacpu`(`serverid`,`timestamp`,`userange`,`createtime`) values(@serverid,@timestamp,@userange,now());";
dbconn.ExecuteSql(sql, new
{
serverid = model.serverid,
timestamp = model.timestamp,
userange = model.userange
});
}
public void AddDataDiskSpace(CCF.DB.DbConn dbconn, Models.ServerWatch.DataDiskSpace model)
{
string sql = "INSERT INTO `datadiskspace`(`serverid`,`timestamp`,`subkey`,`used`,`available`,`createtime`) values(@serverid,@timestamp,@subkey, @used,@available,now());";
dbconn.ExecuteSql(sql, new
{
serverid = model.serverid,
timestamp = model.timestamp,
subkey = model.subkey,
used = model.used,
available = model.available
});
}
public void AddDataDiskIO(CCF.DB.DbConn dbconn, Models.ServerWatch.DataDiskIO model)
{
string sql = "INSERT INTO `datadiskio`(`serverid`,`timestamp`,`subkey`,`iovalue`,`createtime`) values(@serverid,@timestamp,@subkey,@iovalue,now());";
dbconn.ExecuteSql(sql, new
{
serverid = model.serverid,
timestamp = model.timestamp,
subkey = model.subkey,
iovalue = model.iovalue
});
}
public void AddDataHttpRequest(CCF.DB.DbConn dbconn, Models.ServerWatch.DataHttpRequest model)
{
string sql = "INSERT INTO `datahttprequest`(`serverid`,`timestamp`,`requestcount`,`createtime`) values(@serverid,@timestamp,@requestcount,now());";
dbconn.ExecuteSql(sql, new
{
serverid = model.serverid,
timestamp = model.timestamp,
requestcount = model.requestcount
});
}
public void AddDataMemory(CCF.DB.DbConn dbconn, Models.ServerWatch.DataMemory model)
{
string sql = "INSERT INTO `datamemory`(`serverid`,`timestamp`,`used`,`available`,`createtime`) values(@serverid,@timestamp, @used,@available,now());";
dbconn.ExecuteSql(sql, new
{
serverid = model.serverid,
timestamp = model.timestamp,
used = model.used,
available = model.available
});
}
public void AddDataNewWorkIO(CCF.DB.DbConn dbconn, Models.ServerWatch.DataNetWorkIO model)
{
string sql = "INSERT INTO `datanetworkio`(`serverid`,`timestamp`,`subkey`,`sent`,`received`,`createtime`) values(@serverid,@timestamp,@subkey, @sent,@received,now());";
dbconn.ExecuteSql(sql, new
{
serverid = model.serverid,
timestamp = model.timestamp,
subkey = model.subkey,
sent = model.sent,
received = model.received
});
}
public Models.ServerWatch.ServerStateInfo GetServerSummary(CCF.DB.DbConn dbconn, int serverid)
{
string sql1 = "select stateinfo,updatetime from serverstateinfo where serverid=@serverid;";
var objstamp = dbconn.Query<Models.ServerWatch.ServerStateInfo>(sql1, new { serverid = serverid }).FirstOrDefault();
return objstamp;
}
public void AddServerSummary(CCF.DB.DbConn dbconn, int serverid, string p)
{
string sql = "update serverstateinfo set stateinfo=@stateinfo ,updatetime=now() where serverid=@serverid;";
int r = dbconn.ExecuteSql(sql, new
{
stateinfo = p,
serverid = serverid
});
if (r == 0)
{
string sql2 = "insert into serverstateinfo(serverid,stateinfo,updatetime) values(@serverid,@stateinfo ,now() );";
dbconn.ExecuteSql(sql2, new
{
stateinfo = p,
serverid = serverid
});
}
}
public List<Models.ServerWatch.DataCpu> GetChartCpu(CCF.DB.DbConn dbconn, int serverid, DateTime begintime, DateTime endtime)
{
string sql = "select * from datacpu where serverid=@serverid and timestamp>=@begintime and timestamp<=@endtime order by timestamp desc limit " + ChartMaxItmes + ";";
var data = dbconn.Query<Models.ServerWatch.DataCpu>(sql, new
{
serverid = serverid,
begintime = begintime,
endtime = endtime
});
return data;
}
public List<Models.ServerWatch.DataDiskSpace> GetChartDiskSpace(CCF.DB.DbConn dbconn, int serverid, DateTime begintime, DateTime endtime)
{
string sql = "select * from datadiskspace where serverid=@serverid and timestamp>=@begintime and timestamp<=@endtime order by timestamp desc limit " + ChartMaxItmes + ";";
var data = dbconn.Query<Models.ServerWatch.DataDiskSpace>(sql, new
{
serverid = serverid,
begintime = begintime,
endtime = endtime
});
return data;
}
public List<Models.ServerWatch.DataDiskIO> GetChartDiskIO(CCF.DB.DbConn dbconn, int serverid, DateTime begintime, DateTime endtime)
{
string sql = "select * from datadiskio where serverid=@serverid and timestamp>=@begintime and timestamp<=@endtime order by timestamp desc limit " + ChartMaxItmes + ";";
var data = dbconn.Query<Models.ServerWatch.DataDiskIO>(sql, new
{
serverid = serverid,
begintime = begintime,
endtime = endtime
});
return data;
}
public List<Models.ServerWatch.DataMemory> GetChartMemory(CCF.DB.DbConn dbconn, int serverid, DateTime begintime, DateTime endtime)
{
string sql = "select * from datamemory where serverid=@serverid and timestamp>=@begintime and timestamp<=@endtime order by timestamp desc limit " + ChartMaxItmes + ";";
var data = dbconn.Query<Models.ServerWatch.DataMemory>(sql, new
{
serverid = serverid,
begintime = begintime,
endtime = endtime
});
return data;
}
public List<Models.ServerWatch.DataNetWorkIO> GetChartNetworkIO(CCF.DB.DbConn dbconn, int serverid, DateTime begintime, DateTime endtime)
{
string sql = "select * from datanetworkio where serverid=@serverid and timestamp>=@begintime and timestamp<=@endtime order by timestamp desc limit " + ChartMaxItmes + ";";
var data = dbconn.Query<Models.ServerWatch.DataNetWorkIO>(sql, new
{
serverid = serverid,
begintime = begintime,
endtime = endtime
});
return data;
}
public List<Models.ServerWatch.DataHttpRequest> GetChartHttpRequest(CCF.DB.DbConn dbconn, int serverid, DateTime begintime, DateTime endtime)
{
string sql = "select * from datahttprequest where serverid=@serverid and timestamp>=@begintime and timestamp<=@endtime order by timestamp desc limit " + ChartMaxItmes + ";";
var data = dbconn.Query<Models.ServerWatch.DataHttpRequest>(sql, new
{
serverid = serverid,
begintime = begintime,
endtime = endtime
});
return data;
}
}
}
|
using ArquiteturaLimpaMVC.Aplicacao.DTOs;
using ArquiteturaLimpaMVC.Aplicacao.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace ArquiteturaLimpaMVC.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProdutosController : ControllerBase
{
private readonly IProdutoService _produtoService;
public ProdutosController(IProdutoService produtoService)
{
_produtoService = produtoService;
}
[HttpGet(Name = nameof(TodosProdutos))]
public async Task<IActionResult> TodosProdutos()
{
var produtos = await _produtoService.TodosProdutosAsync();
if (produtos is null)
return NotFound("Os produtos não foram encontrados!");
return Ok(produtos);
}
[HttpGet("{id:int}", Name = nameof(ProdutoPorId))]
public async Task<IActionResult> ProdutoPorId([FromRoute] int id)
{
var produto = await _produtoService.ProdutoPorIdAsync(id);
if (produto is null)
return NotFound("O produto não foi encontrado!");
return Ok(produto);
}
[HttpPost(Name = nameof(CriarProduto))]
public async Task<IActionResult> CriarProduto([FromBody] ProdutoDTO produtoDTO)
{
if (produtoDTO is null)
return BadRequest("Dado Inválido!");
await _produtoService.CriarAsync(produtoDTO);
return new CreatedAtRouteResult(nameof(ProdutoPorId), new { id = produtoDTO.Id });
}
[HttpPut("{id:int}", Name = nameof(AtualizarProduto))]
public async Task<IActionResult> AtualizarProduto([FromRoute] int id, [FromBody] ProdutoDTO produtoDTO)
{
if (id != produtoDTO.Id)
return BadRequest();
if (produtoDTO is null)
return BadRequest("");
await _produtoService.AtualizarAsync(produtoDTO);
return Ok(produtoDTO);
}
[HttpDelete("{id:int}", Name = nameof(RemoverProduto))]
public async Task<IActionResult> RemoverProduto([FromRoute] int id)
{
var produtoDTO = await _produtoService.ProdutoPorIdAsync(id);
if (produtoDTO is null)
return NotFound("Produto não encontrado!");
await _produtoService.RemoverAsync(id);
return Ok(produtoDTO);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UseCoroutineColor : MonoBehaviour {
private Color _currentColor;
private bool _CoroStatus = false;
private void Start() {
_currentColor = this.GetComponent<MeshRenderer>().material.color;
Debug.Log(_currentColor);
StartCoroutine("ColorChange", _currentColor);
}
private void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
if (_CoroStatus == false) {
StopCoroutine("ColorChange");
_currentColor = this.GetComponent<MeshRenderer>().material.color;
_CoroStatus = true;
}else {
StartCoroutine("ColorChange", _currentColor);
_CoroStatus = false;
}
}
}
IEnumerator ColorChange(Color currentColor) {
for (float i = 0.0f; i <= 1.0f; i += 0.01f) {
this.GetComponent<MeshRenderer>().material.color = Color.Lerp(currentColor, Color.blue, i);
yield return new WaitForSeconds(0.1f);
}
Debug.Log("Coroutine ended.");
}
}
|
using System.Collections.Generic;
namespace Ofl.Atlassian.Jira.V3
{
public class ErrorCollection
{
public IReadOnlyCollection<string>? ErrorMessages { get; set; }
public IReadOnlyDictionary<string, string>? Errors { get; set; }
public int Status { get; set; }
}
}
|
using System;
using System.Collections;
namespace CustomIterator
{
public class People_A : IEnumerable
{
private Person[] _person;
public People_A(Person[] pArray)
{
_person = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_person[i] = pArray[i];
}
}
public IEnumerator GetEnumerator()
{
// Iterator Block
foreach (Person p in _person)
{
// this will return a person to the caller's foreach construct
// and stores the index of the current iteration in the container (array).
// So, the next iteration will start from the next index of the array.
yield return p;
}
}
}
public class Demo5
{
public static void Run()
{
Person[] actress = new Person[5]
{
new Person("Yui", "Aragaki"),
new Person("Haruka", "Ayase"),
new Person("Haruna", "kawaguchi"),
new Person("Ishihara", "Satomi"),
new Person("Mikako", "Tabe")
};
People_A peopleList = new People_A(actress);
// Get each 'Person' in 'People' type
foreach (Person p in peopleList)
{
Console.WriteLine("{0} {1}", p.firstName, p.lastName);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
Rigidbody rb;
public GameObject joystick;
private float speed;
public float currentSpeed;
private float maxSpeed = 8f;
public bool isFinished = false;
public bool isDead = false;
private float moveHorizontaly;
private float moveVerticaly;
[HideInInspector]
public Vector3 startPosition;
private void Start()
{
rb = GetComponent<Rigidbody>();
speed = 200f;
startPosition = new Vector3(0, 1f, 0);
}
private void FixedUpdate()
{
if (Camera.main.GetComponent<CameraMovement>().previewCamera || isFinished || Camera.main.GetComponent<CameraMovement>().isSpawning || isDead)
return;
if (SystemInfo.deviceType == DeviceType.Desktop)
{
//moveHorizontaly = Input.GetAxis("Horizontal");
//moveVerticaly = Input.GetAxis("Vertical");
if (GameManager.Instance.useJoystick == 0)
{
moveHorizontaly = Input.GetAxis("Horizontal");
moveVerticaly = Input.GetAxis("Vertical");
}
else
{
moveHorizontaly = joystick.GetComponent<Joystick>().Horizontal();
moveVerticaly = joystick.GetComponent<Joystick>().Vertical();
}
Vector3 movement = new Vector3(moveHorizontaly, 0, moveVerticaly);
rb.AddForce (movement * speed * Time.fixedDeltaTime);
currentSpeed = rb.velocity.magnitude;
if (rb.velocity.magnitude > maxSpeed)
rb.velocity = rb.velocity.normalized * maxSpeed;
}
else if(SystemInfo.deviceType == DeviceType.Handheld)
{
Vector3 movement;
if (GameManager.Instance.useJoystick == 0)
{
movement = new Vector3(Input.acceleration.x, 0f, Input.acceleration.y);
}
else
{
movement = new Vector3(moveHorizontaly, 0, moveVerticaly);
}
moveHorizontaly = joystick.GetComponent<Joystick>().Horizontal();
moveVerticaly = joystick.GetComponent<Joystick>().Vertical();
rb.AddForce(movement * speed * Time.fixedDeltaTime);
currentSpeed = rb.velocity.magnitude;
if (rb.velocity.magnitude > maxSpeed)
rb.velocity = rb.velocity.normalized * maxSpeed;
}
}
}
|
using System;
namespace ITCastOCSS.Model
{
/// <summary>
/// Teacher:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class Teacher : IConvertible
{
public Teacher()
{}
#region Model
private int _tid;
private string _tno;
private string _tname;
private string _tsex;
private string _tmajor;
private string _tpwd;
private string _tdepartment;
private string _ttitle;
private int? _tisadmin=0;
/// <summary>
///
/// </summary>
public int TID
{
set{ _tid=value;}
get{return _tid;}
}
/// <summary>
///
/// </summary>
public string TNo
{
set{ _tno=value;}
get{return _tno;}
}
/// <summary>
///
/// </summary>
public string TName
{
set{ _tname=value;}
get{return _tname;}
}
/// <summary>
///
/// </summary>
public string TSex
{
set{ _tsex=value;}
get{return _tsex;}
}
/// <summary>
///
/// </summary>
public string TMajor
{
set{ _tmajor=value;}
get{return _tmajor;}
}
/// <summary>
///
/// </summary>
public string TPwd
{
set{ _tpwd=value;}
get{return _tpwd;}
}
/// <summary>
///
/// </summary>
public string TDepartment
{
set{ _tdepartment=value;}
get{return _tdepartment;}
}
/// <summary>
///
/// </summary>
public string TTitle
{
set{ _ttitle=value;}
get{return _ttitle;}
}
/// <summary>
///
/// </summary>
public int? TIsAdmin
{
set{ _tisadmin=value;}
get{return _tisadmin;}
}
public TypeCode GetTypeCode()
{
throw new NotImplementedException();
}
public bool ToBoolean(IFormatProvider provider)
{
throw new NotImplementedException();
}
public char ToChar(IFormatProvider provider)
{
throw new NotImplementedException();
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
public byte ToByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
public short ToInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
public ushort ToUInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
public int ToInt32(IFormatProvider provider)
{
return this.TID;
}
public uint ToUInt32(IFormatProvider provider)
{
throw new NotImplementedException();
}
public long ToInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
public ulong ToUInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
public float ToSingle(IFormatProvider provider)
{
throw new NotImplementedException();
}
public double ToDouble(IFormatProvider provider)
{
throw new NotImplementedException();
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new NotImplementedException();
}
public DateTime ToDateTime(IFormatProvider provider)
{
throw new NotImplementedException();
}
public string ToString(IFormatProvider provider)
{
throw new NotImplementedException();
}
public object ToType(Type conversionType, IFormatProvider provider)
{
throw new NotImplementedException();
}
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.Core.DomainModels.Customers;
namespace WebAPI.Infrastructure.Repositories
{
public interface ICustomerRepository : IRepository<Customer>
{
Task<CustomerDTO> GetCustomerByIdAsync(int id);
Task<CustomerDTO> GetCustomerDTOByEmailAsync(string email);
Task<CustomerDTO> GetCustomerDTOByIdAndEmailAsync(int id, string email);
}
}
|
namespace IATenderService.Settings
{
public class ServiceSettings
{
public string ActionBenefitServiceUrl { get; set; }
public string DrugServiceUrl { get; set; }
public string TenderServiceUrl { get; set; }
public string PharmacySystemServiceUrl { get; set; }
}
}
|
using System;
namespace _03.Ferrari
{
class Program
{
static void Main(string[] args)
{
var driver = Console.ReadLine();
var car = new Ferrari(driver);
Console.WriteLine($"{car.Model}/{car.Brakes()}/{car.Gas()}/{car.Driver}");
}
}
}
|
using System.Windows.Forms.DataVisualization.Charting;
using Stock_Exchange_Analyzer.Data_Storage;
using Stock_Exchange_Analyzer.DataRepresentation;
using System;
using System.Collections.Generic;
namespace Stock_Exchange_Analyzer.Graph_Rendering
{
static class RenderGraph
{
/// <summary>
/// Renders the graph on the Portfolio UI
/// </summary>
/// <param name="c">Reference to the chart to be Rendered</param>
/// <param name="p">Portfolio Object to be Rendered in the graph</param>
public static void renderPortfolioGraph(ref Chart c, Portfolio p, CurrencyExchanger ce, Dictionary<Investment, string> data)
{
renderMainMenuGraph(ref c, p, ce, data);
}
public static void renderCompareAnalysisGraph(ref Chart c, QueryResult qr1, QueryResult qr2)
{
for (int i = 0; i < 2; i++)
{
QueryResult qr = i == 0 ? qr1 : qr2;
c.Series[4* i + 1].Points.AddXY("Average Trade Volume", Math.Round(qr.AverageTradeVolume, 3));
c.Series[4* i].Points.AddXY("Highest Value", Math.Round(qr.HighestValue, 3));
c.Series[4* i].Points.AddXY("Average Value", Math.Round(qr.AverageValue, 3));
c.Series[4* i].Points.AddXY("Lowest Value", Math.Round(qr.LowestValue, 3));
c.Series[4 * i + 2].Points.AddXY("Oscillation", Math.Round(qr1.Divergence, 3));
c.Series[4 * i + 3].Points.AddXY("Oscilation % in average value", Math.Round(qr.Divergence / qr.AverageValue, 3) * 100);
for (int j = 0; j < 4; j++)
c.Series[4 * i + j].Name += i == 0 ? " " + qr1.Company : qr2.Company;
}
}
/// <summary>
/// Renders the graph on the Compare Stocks UI
/// </summary>
/// <param name="c">Reference to the chart to be Rendered</param>
/// <param name="q1">QueryResult Object for the Company 1</param>
/// <param name="q2">QueryResult Object for the Company 2</param>
public static void renderCompareStocksGraph(ref Chart c, QueryResult q1, QueryResult q2)
{
foreach(StockDay s1 in q1.StockDays)
{
c.Series["Company1"].Points.AddXY(s1.Date, (double)s1.High, (double)s1.Low, (double)s1.OpeningValue, (double)s1.ClosingValue);
}
c.Series["Company1"].Name = q1.Company;
foreach (StockDay s2 in q2.StockDays)
{
c.Series["Company2"].Points.AddXY(s2.Date, (double)s2.High, (double)s2.Low, (double)s2.OpeningValue, (double)s2.ClosingValue);
}
c.Series["Company2"].Name = q2.Company;
}
/// <summary>
/// Renders the graph on the Main Menu
/// </summary>
/// <param name="c">Reference to the chart to be Rendered</param>
/// <param name="p">Portfolio Object to be Rendered in the graph</param>
public static void renderMainMenuGraph(ref Chart c, Portfolio p, CurrencyExchanger ce, Dictionary<Investment, string> data)
{
c.Series["Profit"].Points.Clear();
List<ProfitDay> points = p.calculateProfit(ce, data);
foreach(ProfitDay pd in points)
{
if (((pd.Day.DayOfWeek == DayOfWeek.Saturday || pd.Day.DayOfWeek == DayOfWeek.Sunday ) && pd.Profit == 0))
{
//empty days, what to do?
}
else
c.Series["Profit"].Points.AddXY(pd.Day, pd.Profit);
}
}
/// <summary>
/// Renders the graph on the Search Results UI
/// </summary>
/// <param name="c">Reference to the chart to be Rendered</param>
/// <param name="s1">StockDay Object for the search result Company</param>
public static void renderSearchResultGraph(ref Chart c, QueryResult qr)
{
c.Text = qr.Company;
//setup series
foreach(Series s in c.Series)
{
s.XValueType = ChartValueType.DateTime;
s.YValueType = ChartValueType.Double;
}
foreach(StockDay sd in qr.StockDays)
{
c.Series["High"].Points.AddXY(sd.Date.ToOADate(), (double)sd.High);
c.Series["Low"].Points.AddXY(sd.Date.ToOADate(), (double)sd.Low);
c.Series["Close"].Points.AddXY(sd.Date.ToOADate(), (double)sd.ClosingValue);
}
c.ChartAreas[0].AxisY.Maximum = (double)qr.HighestValue;
c.ChartAreas[0].AxisY.Minimum = (double)qr.LowestValue;
}
}
}
|
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBueno.Utility
{
static class RectangleHelper
{
public static Vector2 ToVector(this Rectangle rect)
{
return new Vector2(rect.X, rect.Y);
}
public static Rectangle XShift(this Rectangle rect, int xshift)
{
rect.X += xshift;
return rect;
}
public static Rectangle Scale(this Rectangle rect, int scale)
{
return new Rectangle(rect.X * scale, rect.Y * scale, rect.Width * scale, rect.Height * scale);
}
public static Rectangle ScaleSize(this Rectangle rect, float scale)
{
return new Rectangle(0, 0, (int)(rect.Width * scale), rect.Height);
}
public static Rectangle ScaleSize(this Rectangle rect, int scale, int div)
{
return new Rectangle(0, 0, rect.Width * scale / div, rect.Height);
}
public static Rectangle ToSize(this Rectangle rect)
{
return new Rectangle(0, 0, rect.Width, rect.Height);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PatronPrototipo
{
class CPersona:IPrototipo
{
private string nombre;
private int edad;
public string Nombre { get => nombre; set => nombre = value; }
public int Edad { get => edad; set => edad = value; }
public CPersona(string pNombre, int pEdad)
{
nombre = pNombre;
edad = pEdad;
}
public override string ToString()
{
return string.Format("{0}, {1}", nombre, edad);
}
public object Clonar()
{
CPersona clon = new CPersona(nombre, edad);
return clon;
}
}
}
|
using System.Net.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
namespace AspNetCore.Security.CAS
{
public class CasPostConfigureOptions :IPostConfigureOptions<CasOptions>
{
private readonly IDataProtectionProvider _dp;
public CasPostConfigureOptions(IDataProtectionProvider dataProtection)
{
_dp = dataProtection;
}
/// <summary>
/// Invoked to post configure a TOptions instance.
/// </summary>
/// <param name="name">The name of the options instance being configured.</param>
/// <param name="options">The options instance to configure.</param>
public void PostConfigure(string name, CasOptions options)
{
options.DataProtectionProvider = options.DataProtectionProvider ?? _dp;
if (options.StateDataFormat == null)
{
var dataProtector = options.DataProtectionProvider.CreateProtector(typeof(CasHandler).FullName, name, "v1");
options.StateDataFormat = new PropertiesDataFormat(dataProtector);
}
if (options.Backchannel == null)
{
options.Backchannel = new HttpClient(options.BackchannelHttpHandler ?? new HttpClientHandler());
options.Backchannel.Timeout = options.BackchannelTimeout;
options.Backchannel.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
options.Backchannel.DefaultRequestHeaders.Accept.ParseAdd("*/*");
options.Backchannel.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft ASP.NET Core CAS handler");
options.Backchannel.DefaultRequestHeaders.ExpectContinue = false;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Values
{
public static float gridSize = 4.0f;
public static float innerWallThicknessScale = 0.5f;
public static float outerWallThicknessScale = 1f;
public static int cellCount = 9;
public static string[,] keys = {{ "W", "A", "S", "D", "Q", "E", "Space"}, { "UpArrow", "LeftArrow", "DownArrow", "RightArrow", "N", "M", "K"}};
public static int lastSceneIndex = 0;
public static float GetCellSize()
{
return (float)(gridSize / cellCount);
}
public static string[] playerColor = {"red", "green"};
public static string[] playerName = {"Wilfréd", "Alfons"};
public static string gameMode = "local";
}
public static class Colors
{
public static Color RED = ConvertColor( 168, 0, 102);
public static Color GREEN = ConvertColor( 168, 229, 48);
public static Color BLUE = ConvertColor(7, 212, 213);
public static Color YELLOW = ConvertColor( 250, 228, 8);
public static Color fadedRED = ConvertColor(120, 4, 74);
public static Color fadedGREEN = ConvertColor(103, 164, 4);
public static Color fadedBLUE = ConvertColor(0, 134, 137);
public static Color fadedYELLOW = ConvertColor( 234, 187, 4);
static Color ConvertColor (float r, float g, float b)
{
return new Color(r/255.0f, g/255.0f, b/255.0f);
}
} |
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;
[assembly: OwinStartup(typeof(Livefeed.Api.Startup))]
namespace Livefeed.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
ConfigureSignalR(app);
}
private void ConfigureSignalR(IAppBuilder app)
{
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJavaScriptProxies = false,
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
//EnableJSONP = true
};
// Require authentication for all hubs
//var queryStringAuthorizer = new QueryStringBearerAuthorizeAttribute();
//var authorizeModule = new AuthorizeModule(queryStringAuthorizer, queryStringAuthorizer);
//GlobalHost.HubPipeline.AddModule(authorizeModule);
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace _2_Class_Courses
{
class Student
{
public int id;
public string name;
public DateTime registerDate;
public Student(string name, int id)
{
this.id = id;
this.name = name;
this.registerDate = DateTime.Now;
}
public void Print()
{
Console.WriteLine($"{id}: {name}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EnsorExternSimulation
{
class EnsorIOSocketAdaptor
{
private EnsorIOController ensorIOController;
private SocketClient socketClient;
private Thread waitForReceive;
private Thread pollData;
private ExternSimulationPackage receivePackage;
private ExternSimulationPackage sendPackage;
private int pollFreq;
private int checkReceiveFreq;
private bool allowReceive;
private Stopwatch stopWatch;
private long lastTimeSend;
private long lastTimeReceived;
private long deltaTime;
private bool connectionAlive = false;
public EnsorIOSocketAdaptor(ref EnsorIOController ioController)
{
stopWatch = new Stopwatch();
stopWatch.Start();
ensorIOController = ioController;
checkReceiveFreq = 50; //Hz
}
public bool MakeConnection(string _ip, int _port)
{
try
{
// Make socket connection
socketClient = new SocketClient(_ip, _port);
socketClient.Connect();
try
{
// Set up data thread
allowReceive = true;
waitForReceive = new Thread(new ThreadStart(this.WaitForReceive));
waitForReceive.Start();
// Send first poll message to start ping pong systen
this.PollData();
return true;
}
catch (Exception exp)
{
MessageBox.Show("Unable to start data thread!\n" + exp.Message);
return false;
}
}
catch (Exception exp)
{
// Display error message
MessageBox.Show("Unable to connect!\n" + exp.Message);
return false;
}
}
public bool CloseConnection()
{
try
{
// Stop data thread
allowReceive = false;
// Wait for thread to finish
long startTerminateThreadTime = stopWatch.ElapsedMilliseconds;
while (waitForReceive.IsAlive)
{
//Check elapsed time
if (stopWatch.ElapsedMilliseconds - startTerminateThreadTime > 100)
{
// Display error message
MessageBox.Show("Unable to stop data thread!");
}
}
try
{
// Close socket connection
socketClient.CloseConnection();
return true;
}
catch (Exception exp)
{
// Display error message
MessageBox.Show("Unable to close socket connection!\n" + exp.Message);
return false;
}
}
catch (Exception exp)
{
// Display error message
MessageBox.Show("Unable to close connection!\n" + exp.Message);
return false;
}
}
public long GetTimeToLastReceive()
{
return stopWatch.ElapsedMilliseconds - lastTimeReceived;
}
public bool SendIOUpdate()
{
// convert EnsorIOcontroller in to Extern simulation packege
sendPackage = new ExternSimulationPackage();
// convert dig inputs
foreach (DigInput digInput in ensorIOController.digInputs)
{
int byteNr = (int)Math.Floor((double)digInput.IdxNr / 8.0);
int bitNr = digInput.IdxNr % 8;
byte mask = (byte)((digInput.CurrentVal?1:0) << bitNr);
sendPackage.digInputs[byteNr] |= mask;
}
// convert dig outputs
foreach (DigOutput digOutput in ensorIOController.digOutputs)
{
int byteNr = (int)Math.Floor((double)digOutput.IdxNr / 8.0);
int bitNr = digOutput.IdxNr % 8;
sendPackage.digOutputs[byteNr] |= (byte)((digOutput.CurrentVal?1:0) << bitNr);
}
// convert num inputs
foreach (NumInput numInput in ensorIOController.numInputs)
{
sendPackage.numInputs[numInput.IdxNr] = numInput.CurrentVal;
}
// convert num outputs
foreach (NumOutput numOutput in ensorIOController.numOutputs)
{
sendPackage.numOutputs[numOutput.IdxNr] = numOutput.CurrentVal;
}
if (socketClient.SendData(sendPackage.ToByteArray(), sendPackage.ToByteArray().Length))
{
ensorIOController.ResetGUIBusyWriting();
return true;
}
else
{
return false;
}
}
private bool PollData()
{
Byte[] tempArray = new Byte[1];
tempArray[0] = 0x70; //'p'
if (socketClient.SendData(tempArray, tempArray.Length))
{
lastTimeSend = stopWatch.ElapsedMilliseconds;
return true;
}
return false;
}
private void WaitForReceive(){
while (allowReceive)
{
int sleep = (int)((1.0 / (double)checkReceiveFreq) * 1000);
Thread.Sleep(sleep);
if (socketClient.DataAvailable())
{
// Update receive time
lastTimeReceived = stopWatch.ElapsedMilliseconds;
// Read bytes
ExternSimulationPackage tempP = new ExternSimulationPackage();
Byte[] tempBuffer = new Byte[tempP.GetSize()];
socketClient.ReadData(tempBuffer, tempP.GetSize());
receivePackage = new ExternSimulationPackage(tempBuffer);
Console.WriteLine("Recevied" + receivePackage.numInputs[3].ToString());
// read dig inputs
// loop bytes
for (int i = 0; i < receivePackage.digInputs.Length; i++)
{
//loop bits
for(int j = 0; j<8 ; j++){
ensorIOController.SetDigInputBySocket(i*8+j,(receivePackage.digInputs[i] & (1 << j)) != 0);
}
}
// read dig outputs
// loop bytes
for (int i = 0; i < receivePackage.digOutputs.Length; i++)
{
//loop bits
for (int j = 0; j < 8; j++)
{
ensorIOController.SetDigOutputBySocket(i*8 + j, (receivePackage.digOutputs[i] & (1 << j)) != 0);
}
}
// read num outputs
for (int i = 0; i < receivePackage.numOutputs.Length; i++)
{
ensorIOController.SetNumOutputBySocket(i, receivePackage.numOutputs[i]);
}
// read num inputs
for (int i = 0; i < receivePackage.numInputs.Length; i++)
{
ensorIOController.SetNumInputBySocket(i, receivePackage.numInputs[i]);
}
// Resend poll message
if (!ensorIOController.GetGUIBusyWriting())
{
connectionAlive = this.PollData();
}
else
{
connectionAlive = SendIOUpdate();
}
if (!connectionAlive)
{
// Stop sending data untin new connection is made
allowReceive = false;
}
else
{
// Last time valid send
lastTimeSend = stopWatch.ElapsedMilliseconds;
}
}
}
}
public bool ConnectionAlive()
{
return connectionAlive && GetTimeToLastReceive() < (((1.0 / (double)checkReceiveFreq) * 1000) * 2);
}
}
}
|
using System.Collections.Generic;
using DFC.ServiceTaxonomy.VersionComparison.Models;
using Newtonsoft.Json.Linq;
namespace DFC.ServiceTaxonomy.VersionComparison.Services.PropertyServices
{
public interface IPropertyService
{
bool CanProcess(JToken? jToken, string? propertyName = null);
IList<PropertyExtract> Process(string propertyName, JToken? jToken);
}
}
|
using Microsoft.Extensions.DependencyInjection;
using System;
namespace DDMedi.DependencyInjection
{
public class SupplierScopeFactory : ISupplierScopeFactory
{
IServiceScopeFactory _factory;
public SupplierScopeFactory(IServiceScopeFactory factory)
{
_factory = factory;
}
public ISupplierScope CreateScope() => new SupplierScope(_factory.CreateScope());
}
public class SupplierScope : ISupplierScope
{
IServiceScope _scope;
public SupplierScope(IServiceScope scope)
{
_scope = scope;
}
public IServiceProvider ServiceProvider => _scope.ServiceProvider;
public void Dispose()
{
_scope.Dispose();
_scope = null;
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddDDMediFactory(this IServiceCollection services, Action<DDMediCollection> ddCollectionAction)
{
var ddCollection = new DDMediCollection();
ddCollectionAction(ddCollection);
return services.AddDDMediFactory(ddCollection.BuildSuppliers());
}
public static IServiceCollection AddDDMediFactory(this IServiceCollection services, DDMediCollection ddCollection)
=> services.AddDDMediFactory(ddCollection.BuildSuppliers());
public static IServiceCollection AddDDMediFactory(this IServiceCollection services, DDMediFactory ddFactory)
{
services.AddSingleton<ISupplierScopeFactory, SupplierScopeFactory>();
foreach (var descriptor in ddFactory.BaseDescriptorCollection.Descriptors)
{
if(descriptor.ImplementType != null)
services.Add(ServiceDescriptor.Describe(descriptor.RegisterType, descriptor.ImplementType, (ServiceLifetime)descriptor.Lifetime));
else
services.Add(ServiceDescriptor.Describe(descriptor.RegisterType, descriptor.GetInstance, (ServiceLifetime)descriptor.Lifetime));
}
return services;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Автошкола
{
public class GroupsDA
{
private SqlDataAdapter dataAdapter;
// сохранить изменения строки
public void Save(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr)
{
dataAdapter = new SqlDataAdapter();
// на обновление
dataAdapter.UpdateCommand = new SqlCommand("UPDATE Groups SET ID = @ID, Name = @Name, StartLearning = @StartLearning, " +
"EndLearning = @EndLearning, Category = @Category, Teacher = @Teacher " +
"WHERE ID = @OldID", conn.getConnection(), tr.getTransaction());
dataAdapter.UpdateCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID");
dataAdapter.UpdateCommand.Parameters.Add("@Name", System.Data.SqlDbType.Text, 255, "Name");
dataAdapter.UpdateCommand.Parameters.Add("@StartLearning", System.Data.SqlDbType.Date, 255, "StartLearning");
dataAdapter.UpdateCommand.Parameters.Add("@EndLearning", System.Data.SqlDbType.Date, 255, "EndLearning");
dataAdapter.UpdateCommand.Parameters.Add("@Category", System.Data.SqlDbType.Int, 255, "Category");
dataAdapter.UpdateCommand.Parameters.Add("@Teacher", System.Data.SqlDbType.Int, 255, "Teacher");
dataAdapter.UpdateCommand.Parameters.Add("@OldID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original;
// на вставку
dataAdapter.InsertCommand = new SqlCommand("INSERT INTO Groups (ID, Name, StartLearning, EndLearning, " +
"Category, Teacher) VALUES (@ID, @Name, @StartLearning, @EndLearning, @Category, @Teacher)",
conn.getConnection(), tr.getTransaction());
dataAdapter.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID");
dataAdapter.InsertCommand.Parameters.Add("@Name", System.Data.SqlDbType.Text, 255, "Name");
dataAdapter.InsertCommand.Parameters.Add("@StartLearning", System.Data.SqlDbType.Date, 255, "StartLearning");
dataAdapter.InsertCommand.Parameters.Add("@EndLearning", System.Data.SqlDbType.Date, 255, "EndLearning");
dataAdapter.InsertCommand.Parameters.Add("@Category", System.Data.SqlDbType.Int, 255, "Category");
dataAdapter.InsertCommand.Parameters.Add("@Teacher", System.Data.SqlDbType.Int, 255, "Teacher");
// на удаление
dataAdapter.DeleteCommand = new SqlCommand("DELETE Groups WHERE ID = @ID", conn.getConnection(), tr.getTransaction());
dataAdapter.DeleteCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original;
dataAdapter.Update(dataSet, "Groups");
}
// прочитать таблицу
public void Read(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM Groups", conn.getConnection(), tr.getTransaction());
dataAdapter.Fill(dataSet, "Groups");
}
public void ReadGroupByName(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, string Name)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM Groups WHERE Name = @Name", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@Name", Name);
dataAdapter.Fill(dataSet, "Groups");
}
public void ReadGroupByID(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int GroupID)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM Groups WHERE ID = @ID", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@ID", GroupID);
dataAdapter.Fill(dataSet, "Groups");
}
}
}
|
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using Alabo.Validations.Aspects;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Alabo.Datas.Stores.Update.Mongo {
public abstract class UpdateMongoStore<TEntity, TKey> : UpdateAsyncMongoStore<TEntity, TKey>,
IUpdateStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected UpdateMongoStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public void AddUpdateOrDelete(IEnumerable<TEntity> entities, Expression<Func<TEntity, bool>> predicate) {
throw new NotImplementedException();
}
public bool Update(Action<TEntity> updateAction, Expression<Func<TEntity, bool>> predicate = null) {
//TODO: mongodb批量操作数据库
throw new NotImplementedException();
//var expression = IdPredicate(entity.Id);
//var filter = ToFilter(entity.Id);
////var updateModel = Collection.FindOneAndReplace(filter, entity);
////if (updateModel != null) {
//// return true;
////}
//if (entity == null)
// throw new NullReferenceException();
//var type = entity.GetType();
//// 修改的属性集合
//var updateDefinition = Builders<TEntity>.Update.Set(propert.Name, replaceValue);
//foreach (var propert in type.GetProperties()) {
// if (propert.Name.ToLower() != "id" || propert.Name != "CreateTime") {
// var replaceValue = propert.GetValue(entity);
// list.Add();
// }
//}
//#region 有可修改的属性
//if (list.Count > 0) {
// // 合并多个修改//new List<UpdateDefinition<T>>() { Builders<T>.Update.Set("Name", "111") }
// var builders = Builders<TEntity>.Update.Combine(updateDefinition);
// // 执行提交修改
// var result = Collection.UpdateMany(filter, updateDefinition);
//}
//#endregion 有可修改的属性
//return true;
}
public void UpdateMany(IEnumerable<TEntity> entities) {
throw new NotImplementedException();
}
public void UpdateMany(Action<TEntity> updateAction, Expression<Func<TEntity, bool>> predicate = null) {
throw new NotImplementedException();
}
public bool UpdateNoTracking([Valid] TEntity model) {
throw new NotImplementedException();
}
public bool UpdateSingle([Valid] TEntity entity) {
var expression = IdPredicate(entity.Id);
var filter = ToFilter(entity.Id);
var updateModel = Collection.FindOneAndReplace(filter, entity);
if (updateModel != null) {
return true;
}
return true;
}
}
} |
namespace TalkExamples.SOLID.OCP.Example1
{
public abstract class Cargo
{
public virtual decimal PercentualBonificacao()
{
return 0;
}
}
public class Diretor: Cargo
{
public override decimal PercentualBonificacao()
{
return 0.1M;
}
}
public class Desenvolvedor : Cargo
{
public override decimal PercentualBonificacao()
{
return 0.2M;
}
}
public class Testador : Cargo
{
public override decimal PercentualBonificacao()
{
return 0.2M;
}
}
public class Marketing : Cargo
{
}
}
|
using DiscomonProject.Discord.Entities;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Reflection;
using System.Threading.Tasks;
namespace DiscomonProject.Discord
{
public class Connection
{
private readonly DiscordSocketClient _client;
private readonly CommandService _commands;
private readonly DiscordLogger _logger;
public Connection(DiscordLogger logger, DiscordSocketClient client, CommandService commands)
{
_logger = logger;
_commands = commands;
_client = client;
}
public async Task ConnectAsync(MonBotConfig config)
{
_client.Log += _logger.Log;
await _client.LoginAsync(TokenType.Bot, config.Token);
await _client.StartAsync();
_commands.CommandExecuted += CommandExecutedAsync;
_client.MessageReceived += HandleCommandAsync;
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);
await Task.Delay(-1);
}
private async Task HandleCommandAsync(SocketMessage messageParam)
{
// Don't process the command if it was a system message
var message = messageParam as SocketUserMessage;
if (message == null) return;
// Create a number to track where the prefix ends and the command begins
int argPos = 0;
// Determine if the message is a command based on the prefix and make sure no bots trigger commands
if (!(message.HasCharPrefix('!', ref argPos) ||
message.HasMentionPrefix(_client.CurrentUser, ref argPos)) ||
message.Author.IsBot)
return;
// Create a WebSocket-based command context based on the message
var context = new SocketCommandContext(_client, message);
// Execute the command with the command context we just
// created, along with the service provider for precondition checks.
await _commands.ExecuteAsync(context, argPos, services: null);
}
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
{
// if a command isn't found, log that info to console and exit this method
if (!command.IsSpecified)
{
System.Console.WriteLine($"Command failed to execute for [{context.User.Username}] <-> [{result.ErrorReason}]!");
return;
}
// log success to the console and exit this method
if (result.IsSuccess)
{
System.Console.WriteLine($"Command [{command.Value.Name}] executed for -> [{context.User.Username}]");
return;
}
// failure scenario, let's let the user know
await context.Channel.SendMessageAsync($"Sorry, {context.User.Username}... something went wrong -> [{result}]!");
}
}
} |
using System.Collections.Generic;
using EdjCase.JsonRpc.Core.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using System;
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Local
// ReSharper disable UnusedMember.Local
namespace EdjCase.JsonRpc.Core
{
/// <summary>
/// Model representing a Rpc request
/// </summary>
[JsonObject]
public class RpcRequest
{
[JsonConstructor]
private RpcRequest()
{
}
/// <param name="id">Request id</param>
/// <param name="method">Target method name</param>
/// <param name="parameterList">Json parameters for the target method</param>
public RpcRequest(string id, string method, JToken parameters)
{
this.Id = id;
this.JsonRpcVersion = JsonRpcContants.JsonRpcVersion;
this.Method = method;
this.Parameters = parameters;
}
/// <summary>
/// Request Id (Optional)
/// </summary>
[JsonProperty("id")]
public string Id { get; private set; }
/// <summary>
/// Version of the JsonRpc to be used (Required)
/// </summary>
[JsonProperty("jsonrpc", Required = Required.Always)]
public string JsonRpcVersion { get; private set; }
/// <summary>
/// Name of the target method (Required)
/// </summary>
[JsonProperty("method", Required = Required.Always)]
public string Method { get; private set; }
/// <summary>
/// Parameters to invoke the method with (Optional)
/// </summary>
[JsonProperty("params")]
public JToken Parameters { get; private set; }
public static RpcRequest WithNoParameters(string id, string method)
{
return RpcRequest.ConvertInternal(id, method, null, null);
}
public static RpcRequest WithNoParameters(string method)
{
return RpcRequest.ConvertInternal(default, method, null, null);
}
public static RpcRequest WithParameterList(string id, string method, IList<object> parameters, JsonSerializer jsonSerializer = null)
{
return RpcRequest.ConvertInternal(id, method, parameters, jsonSerializer);
}
public static RpcRequest WithParameterList(int id, string method, IList<object> parameters, JsonSerializer jsonSerializer = null)
{
return RpcRequest.ConvertInternal(id.ToString(), method, parameters, jsonSerializer);
}
public static RpcRequest WithParameterList(string method, IList<object> parameters, JsonSerializer jsonSerializer = null)
{
return RpcRequest.ConvertInternal(default, method, parameters, jsonSerializer);
}
public static RpcRequest WithParameterMap(string id, string method, IDictionary<string, object> parameters, JsonSerializer jsonSerializer = null)
{
return RpcRequest.ConvertInternal(id, method, parameters, jsonSerializer);
}
public static RpcRequest WithParameterMap(int id, string method, IDictionary<string, object> parameters, JsonSerializer jsonSerializer = null)
{
return RpcRequest.ConvertInternal(id.ToString(), method, parameters, jsonSerializer);
}
public static RpcRequest WithParameterMap(string method, IDictionary<string, object> parameters, JsonSerializer jsonSerializer = null)
{
return RpcRequest.ConvertInternal(default, method, parameters, jsonSerializer);
}
private static RpcRequest ConvertInternal(string id, string method, object parameters, JsonSerializer jsonSerializer = null)
{
if(method == null)
{
throw new ArgumentNullException(nameof(method));
}
JToken sParameters = parameters == null
? null
: jsonSerializer == null
? JToken.FromObject(parameters)
: JToken.FromObject(parameters, jsonSerializer);
return new RpcRequest(id, method, sParameters);
}
}
}
|
using Domain;
namespace RepositoryInterface
{
public interface IUserRepository : IRepository<TUSR>
{
TUSR GetUserRolesByCompanyAndUsername(TUSR user);
TUSR GetUserRolesByPrimaryKey(TUSR user);
}
} |
using System;
namespace Assignemnt_1
{
class Program
{
static void Main(string[] args)
{
fruit ex1 = new fruit();
fruit ex2 = new fruit();
ex1.amount = 5;
ex2 = ex1;
ex2.amount = 6;
Console.WriteLine(ex1.amount);
Console.WriteLine(ex2.amount);
}
struct fruit
{
public string name;
public int amount;
}
}
} |
using System.ComponentModel.DataAnnotations;
namespace StudyMateLibrary.Enities
{
public class Subject : Entity
{
public string Description { get; set; }
[Required]
public string SubjectText { get; set; }
}
} |
namespace TagProLeague.Models
{
public class GameFormat : Document
{
public int Accel { get; set; }
public int TopSpeed { get; set; }
public int Bounce { get; set; }
public int PlayerRespawn { get; set; }
public int BoostRespawn { get; set; }
public int BombRespawn { get; set; }
public int PowerupRespawn { get; set; }
public int PotatoTime { get; set; }
public int PowerupDelay { get; set; }
public bool NoScript { get; set; }
public bool RespawnWarnings { get; set; }
}
}
|
using Microsoft.SqlServer.XEvent.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using XESmartTarget.Core.Responses;
namespace XESmartTarget.Core.Utils
{
class XEventDataTableAdapter
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public DataTable eventsTable { get; }
public List<OutputColumn> OutputColumns { get; set; }
public string Filter { get; set; }
public XEventDataTableAdapter(DataTable table)
{
eventsTable = table;
}
private void Prepare()
{
lock (eventsTable)
{
//
// Add Collection Time column
//
if (!eventsTable.Columns.Contains("collection_time") && (OutputColumns.Count == 0 || OutputColumns.Exists(x => x.Name == "collection_time") || (Filter != null && Filter.Contains("collection_time"))))
{
DataColumn cl_dt = new DataColumn("collection_time", typeof(DateTime))
{
DefaultValue = DateTime.Now
};
cl_dt.ExtendedProperties.Add("auto_column", true);
SetColHiddenProperty(cl_dt);
eventsTable.Columns.Add(cl_dt);
}
//
// Add Collection Time ISO
//
if (!eventsTable.Columns.Contains("collection_time_iso") && (OutputColumns.Count == 0 || OutputColumns.Exists(x => x.Name == "collection_time_iso") || (Filter != null && Filter.Contains("collection_time_iso"))))
{
DataColumn cl_dt = new DataColumn("collection_time_iso", typeof(String))
{
DefaultValue = DateTime.Now.ToString("o")
};
cl_dt.ExtendedProperties.Add("auto_column", true);
SetColHiddenProperty(cl_dt);
eventsTable.Columns.Add(cl_dt);
}
//
// Add Name column
//
if (!eventsTable.Columns.Contains("name") && (OutputColumns.Count == 0 || OutputColumns.Exists(x => x.Name == "name") || (Filter != null && Filter.Contains("name"))))
{
eventsTable.Columns.Add("name", typeof(String));
eventsTable.Columns["name"].ExtendedProperties.Add("auto_column", true);
}
}
}
// sets the column as hidden when not present in the list of visible columns
private void SetColHiddenProperty(DataColumn cl_dt)
{
OutputColumn currentCol = OutputColumns.FirstOrDefault(x => x.Name == cl_dt.ColumnName);
if (currentCol != null)
{
cl_dt.ExtendedProperties.Add("hidden", currentCol.Hidden);
}
else
{
cl_dt.ExtendedProperties.Add("hidden", false);
}
}
public void ReadEvent(PublishedEvent evt)
{
Prepare();
//
// Read event data
//
lock (eventsTable)
{
foreach (PublishedEventField fld in evt.Fields)
{
if (
!eventsTable.Columns.Contains(fld.Name)
&& (
OutputColumns.Count == 0
|| OutputColumns.Exists(x => x.Name == fld.Name)
|| OutputColumns.Exists(x => x.Calculated && Regex.IsMatch(x.Name, @"\s+AS\s+.*" + fld.Name, RegexOptions.IgnoreCase))
|| (Filter != null && Filter.Contains(fld.Name))
)
)
{
OutputColumn col = OutputColumns.FirstOrDefault(x => x.Name == fld.Name);
if(col == null)
{
col = new OutputColumn()
{
Name = fld.Name,
ColumnType = OutputColumn.ColType.Column
};
}
Type t;
DataColumn dc;
bool disallowed = false;
if (DataTableTSQLAdapter.AllowedDataTypes.Contains(fld.Type.ToString()))
{
t = fld.Type;
}
else
{
t = Type.GetType("System.String");
}
dc = eventsTable.Columns.Add(fld.Name, t);
dc.ExtendedProperties.Add("subtype", "field");
dc.ExtendedProperties.Add("disallowedtype", disallowed);
dc.ExtendedProperties.Add("calculated", false);
dc.ExtendedProperties.Add("coltype", col.ColumnType);
SetColHiddenProperty(dc);
}
}
foreach (PublishedAction act in evt.Actions)
{
if (
!eventsTable.Columns.Contains(act.Name)
&& (
OutputColumns.Count == 0
|| OutputColumns.Exists(x => x.Name == act.Name)
|| OutputColumns.Exists(x => x.Calculated && Regex.IsMatch(x.Name, @"\s+AS\s+.*" + act.Name, RegexOptions.IgnoreCase))
)
)
{
OutputColumn col = OutputColumns.FirstOrDefault(x => x.Name == act.Name);
if (col == null)
{
col = new OutputColumn()
{
Name = act.Name,
ColumnType = OutputColumn.ColType.Column
};
}
Type t;
DataColumn dc;
bool disallowed = false;
if (DataTableTSQLAdapter.AllowedDataTypes.Contains(act.Type.ToString()))
{
t = act.Type;
}
else
{
t = Type.GetType("System.String");
}
dc = eventsTable.Columns.Add(act.Name, t);
dc.ExtendedProperties.Add("subtype", "action");
dc.ExtendedProperties.Add("disallowedtype", disallowed);
dc.ExtendedProperties.Add("calculated", false);
dc.ExtendedProperties.Add("coltype", col.ColumnType);
SetColHiddenProperty(dc);
}
}
// add calculated columns
for(int i=0;i<OutputColumns.Count;i++)
{
string outCol = OutputColumns[i].Name;
if (!eventsTable.Columns.Contains(outCol))
{
if (Regex.IsMatch(outCol,@"\s+AS\s+",RegexOptions.IgnoreCase))
{
var tokens = Regex.Split(outCol, @"\s+AS\s+", RegexOptions.IgnoreCase);
string colName = tokens[0];
string colDefinition = tokens[1];
if (!eventsTable.Columns.Contains(colName))
{
DataColumn dc;
dc = eventsTable.Columns.Add();
dc.ColumnName = colName;
dc.Expression = colDefinition;
dc.ExtendedProperties.Add("subtype", "calculated");
dc.ExtendedProperties.Add("disallowedtype", false);
dc.ExtendedProperties.Add("calculated", true);
dc.ExtendedProperties.Add("coltype", OutputColumns[i].ColumnType);
SetColHiddenProperty(dc);
}
//change OutputColumns
OutputColumns[i].Name = colName;
}
}
}
}
DataTable tmpTab = eventsTable.Clone();
DataRow row = tmpTab.NewRow();
if (row.Table.Columns.Contains("name"))
{
row.SetField("name", evt.Name);
}
if (row.Table.Columns.Contains("collection_time"))
{
row.SetField("collection_time", evt.Timestamp.LocalDateTime);
}
if (row.Table.Columns.Contains("collection_time_iso"))
{
row.SetField("collection_time_iso", evt.Timestamp.ToString("o"));
}
foreach (PublishedEventField fld in evt.Fields)
{
if (row.Table.Columns.Contains(fld.Name))
{
if ((bool)row.Table.Columns[fld.Name].ExtendedProperties["disallowedtype"])
{
row.SetField(fld.Name, fld.Value.ToString());
}
else
{
row.SetField(fld.Name, fld.Value);
}
}
}
foreach (PublishedAction act in evt.Actions)
{
if (row.Table.Columns.Contains(act.Name))
{
if ((bool)row.Table.Columns[act.Name].ExtendedProperties["disallowedtype"])
{
row.SetField(act.Name, act.Value.ToString());
}
else
{
row.SetField(act.Name, act.Value);
}
}
}
if (!String.IsNullOrEmpty(Filter))
{
DataView dv = new DataView(tmpTab);
dv.RowFilter = Filter;
tmpTab.Rows.Add(row);
lock (eventsTable)
{
foreach (DataRow dr in dv.ToTable().Rows)
{
eventsTable.ImportRow(dr);
}
}
}
else
{
tmpTab.Rows.Add(row);
lock (eventsTable)
{
foreach (DataRow dr in tmpTab.Rows)
{
eventsTable.ImportRow(dr);
}
}
}
}
}
}
|
using AudioText.DAL;
using AudioText.Models;
using AudioText.Models.DataModels;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
namespace AudioText.Services
{
public class EmailService
{
public static async Task<bool> SendMessageFromCustomer(ContactModel model)
{
return await Task.Run(async () =>
{
MailMessage email = new MailMessage();
email.Body = String.Format("Message: {0} \n\nRespond To: {1}", model.Message, model.Email);
email.Subject = string.Format("{0} -- {1} {2}", model.Subject, model.FirstName, model.LastName);
try
{
var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
email.To.Add(section.Network.UserName);
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(email);
return true;
}
}
catch (Exception exception)
{
return false;
}
});
}
public static async Task<bool> SendMessageToCustomer(ContactModel model)
{
return await Task.Run(async () =>
{
MailMessage email = new MailMessage();
email.Body = model.Message;
email.Subject = model.Subject;
try
{
var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
email.To.Add(model.Email);
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(email);
return true;
}
}
catch (Exception exception)
{
return false;
}
});
}
public static async Task<bool> saveEmail(string email)
{
return await Task.Run(() =>
{
email = email.ToLower();
var manager = new RepositoryManager();
try
{
manager.AccountRepository.Insert(new AccountInformation() { Email = email });
manager.save();
return true;
}
catch (Exception e)
{
return false;
}
});
}
}
} |
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 WebsiteQuanLyPhatHanhSach.Models;
using WebsiteQuanLyPhatHanhSach.ViewModels;
namespace WebsiteQuanLyPhatHanhSach.Controllers
{
public class BookSoldController : Controller
{
private QLPhatHanhSachEntities db = new QLPhatHanhSachEntities();
// GET: BookSold
public ActionResult Index()
{
return View();
}
// GET: BookSold/Details/2013
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var report = db.ReportSolds.Where(a => a.AgencyID == id && a.AdminConfirm == null);
var booksold = db.ReportSoldDetails.Join(report, a => a.ReportID, b => b.ReportID, (a, b) => new
{
AgencyID = b.AgencyID,
ReportID = a.ReportID,
ISBN = a.ISBN,
QuatitySold = a.QuatitySold,
BookPrice = a.BookPrice,
BookTotal = a.BookTotal,
}).Join(db.Books, x => x.ISBN, y => y.ISBN, (x, y) => new BookSoldVM
{
AgencyID = x.AgencyID,
ReportID = x.ReportID,
ISBN = x.ISBN,
BookName = y.BookName,
QuatitySold = x.QuatitySold,
BookPrice = x.BookPrice,
BookTotal = x.BookTotal,
});
if (booksold == null)
{
return HttpNotFound();
}
return View(booksold.ToList());
}
private string CreateID()
{
string id = "";
int count = db.IssueInvoices.ToList().Count();
if (count == 0) id = "1";
else id = (count + 1).ToString();
id = "DLTT-" + id;
return id;
}
private decimal GetDebtSum(int agencyid)
{
decimal debt = 0m;
if (db.Agency_Debt.Where(b => b.AgencyID == agencyid).Count() == 0) return 0m;
else
{
//lấy công nợ đang nợ của đại lý của ngày lớn nhất và Id max.
DateTime d = db.Agency_Debt.Where(b => b.AgencyID == agencyid).Max(b => b.DateCreate);
int id = db.Agency_Debt.Where(b => b.DateCreate == d && b.AgencyID == agencyid).Max(b => b.ADebtID);
Agency_Debt age = db.Agency_Debt.Find(id);
decimal iss = age.AgencyDebt;
debt = iss;
return debt;
}
}
private decimal GetRevenue()
{
decimal debt = 0m;
if (db.Revenues.Count() == 0) return 0m;
else
{
//lấy doanh thu hiện tại.
int id = db.Revenues.Max(b => b.Id);
Revenue rev = db.Revenues.Find(id);
decimal iss = rev.RevenueTotal;
debt = iss;
return debt;
}
}
public JsonResult SubmitPay(InvoiceVM I)
{
bool status = false;
if (!ModelState.IsValid)
{
//Lưu thông tin phiếu thanh toán vào bảng IssueInvoice
IssueInvoice ii = new IssueInvoice {
InvoiceID = CreateID(), AgencyID = I.AgencyID, AdminID = I.AdminID,
InvoiceCreate = DateTime.Now, InvoiceAmount = I.InvoiceAmount
};
db.IssueInvoices.Add(ii);
//Chỉnh sửa bảng ReportSold đã đc admin xác nhận, và update cột InvoiceID
foreach(var id in I.ListReportID)
{
ReportSold rep = db.ReportSolds.Find(id);
rep.InvoiceID = ii.InvoiceID;
rep.AdminConfirm = ii.AdminID;
db.Entry(rep).State = EntityState.Modified;
}
//Thêm thông tin vào bảng Agency_Debt
Agency_Debt a_debt = new Agency_Debt
{
AgencyID = I.AgencyID,
InvoiceID = ii.InvoiceID,
DateCreate = ii.InvoiceCreate,
AgencyInvoicePaid = I.InvoiceAmount,
AgencyDebt = Decimal.Subtract(GetDebtSum(I.AgencyID), I.InvoiceAmount),
};
db.Agency_Debt.Add(a_debt);
//Cập nhật lại nợ vào bảng Agency_Paid_Debt
Agency_Paid_Debt a_paid_debt = db.Agency_Paid_Debt.Find(I.AgencyID);
a_paid_debt.Paid = Decimal.Add(a_paid_debt.Paid, I.InvoiceAmount);
a_paid_debt.Debt = Decimal.Subtract(a_paid_debt.Debt, I.InvoiceAmount);
db.Entry(a_paid_debt).State = EntityState.Modified;
//Tính doanh thu và //Tính tiền phải trả cho Nhà xuất bản
decimal revenue = 0m, pay = 0m;
var booksold = db.ReportSoldDetails.Join(db.BookPrices, a => a.ISBN, b => b.ISBN, (a, b) => new
{
ReportID = a.ReportID,
ISBN = a.ISBN,
QuatitySold = a.QuatitySold,
BookTotal = a.BookTotal,
Price = b.PurchasePrice * a.QuatitySold
}).Where(x => I.ListReportID.Contains(x.ReportID)).ToList();
foreach(var item in booksold)
{
pay = Decimal.Add(pay, item.Price);
}
//doanh thu
revenue = Decimal.Subtract(I.InvoiceAmount, pay);
Revenue rev = new Revenue {
InvoiceID = ii.InvoiceID, InvoiceRevenue = revenue,
RevenueTotal = Decimal.Add(revenue, GetRevenue()), RevenueDate = ii.InvoiceCreate};
db.Revenues.Add(rev);
//doanh thu
//phải trả cho nxb
var pubpay = db.ReportSoldDetails.Join(db.BookPrices, a => a.ISBN, b => b.ISBN, (a, b) => new
{
ReportID = a.ReportID,
ISBN = a.ISBN,
QuatitySold = a.QuatitySold,
BookTotal = a.BookTotal,
Price = b.PurchasePrice * a.QuatitySold
}).Join(db.Books, c => c.ISBN, d => d.ISBN, (c, d) => new {
ReportID = c.ReportID,
ISBN = c.ISBN,
PubID = d.PubID,
QuatitySold = c.QuatitySold,
BookTotal = c.BookTotal,
Price = c.Price
}).Where(x => I.ListReportID.Contains(x.ReportID)).GroupBy(x => x.PubID).Select(x => new {
PubID = x.Key,
Pay = x.Sum(y => y.Price)
}).ToList();
foreach (var item in pubpay)
{
PayForPub pfp = new PayForPub
{
PubID = item.PubID,
InvoiceID = ii.InvoiceID,
PayTotal = item.Pay,
DateCreate = ii.InvoiceCreate
};//chưa cập nhật AdminID và PaymentID vì chưa thực hiện thanh toán cho NXB
db.PayForPubs.Add(pfp);
}
//phải trả cho nxb
status = true;
db.SaveChanges();
}
return new JsonResult { Data = new { status = status } };
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToDoList
{
public class CTaskManager
{
private Dictionary<CTodoTask, DateTime> todoTaskList;
public CTaskManager()
{
this.todoTaskList = new Dictionary<CTodoTask, DateTime>();
}
public void AddTodoTask(CTodoTask task)
{
this.todoTaskList.Add(task, task.taskDateLast);
}
public void DelTodoTask(CTodoTask task)
{
this.todoTaskList.Remove(task);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Docller.Common;
using Docller.Core.Common;
using Docller.Core.Models;
using Newtonsoft.Json;
namespace Docller.Models
{
public class TransmittalViewModel
{
private string _fileJson;
private long _statusId;
public TransmittalViewModel(IEnumerable<File> files, IEnumerable<SelectListItem> statuses )
{
this.To = new SubscriberItemCollection();
this.Cc = new SubscriberItemCollection();
this.TransmittedFiles = new List<TransmittedFile>();
this.StatusList = statuses;
this.Init(files);
}
public TransmittalViewModel(Transmittal transmittal, IEnumerable<SelectListItem> statuses )
{
this.To = new SubscriberItemCollection();
this.Cc = new SubscriberItemCollection();
this.StatusList = statuses;
this.Init(transmittal);
}
public TransmittalViewModel()
{
this.To = new SubscriberItemCollection();
this.Cc = new SubscriberItemCollection();
this.StatusList = new List<SelectListItem>();
}
public TransmittalViewModel(IEnumerable<SelectListItem> statuses)
{
this.To = new SubscriberItemCollection();
this.Cc = new SubscriberItemCollection();
this.StatusList = statuses;
}
public long TransmittalId { get; set; }
[DataType(DataType.Text)]
[Display(Name = "To")]
[RequiredForTransmittal]
public SubscriberItemCollection To { get; set; }
public SubscriberItemCollection Cc { get; set; }
[DataType(DataType.Text)]
[RequiredForTransmittal]
[Display(Name = "Transmittal Number")]
public string TransmittalNumber { get; set; }
[DataType(DataType.Text)]
[Required]
[Display(Name = "Subject")]
public string Subject { get; set; }
[Display(Name = "Message")]
public string Message { get; set; }
public List<TransmittedFile> TransmittedFiles { get; set; }
[Range(1,Int32.MaxValue,ErrorMessage = "You must add files to your transmittal")]
public int FileCount
{
get { return this.TransmittedFiles != null ? this.TransmittedFiles.Count : 0; }
}
public string Action { get; set; }
[RequiredForTransmittal]
[Display(Name = "Status")]
public long StatusId
{
get { return _statusId; }
set
{
_statusId = value;
var selected = (from s in this.StatusList
where s.Value == _statusId.ToString(CultureInfo.InvariantCulture)
select s).FirstOrDefault();
if (selected != null)
{
selected.Selected = true;
}
}
}
public string FileJson {
get
{
if (string.IsNullOrEmpty(_fileJson))
{
JsonNetResult result = new JsonNetResult {Data = this.TransmittedFiles};
_fileJson = result.GetRawJson();
}
return _fileJson;
}
}
public IEnumerable<SelectListItem> StatusList { get; set; }
private void Init(IEnumerable<File> files)
{
foreach (File file in files)
{
this.TransmittedFiles.Add(new TransmittedFile()
{
FileId = file.FileId,
FileInternalName = file.FileInternalName,
FileName = file.FileName,
Status = file.Status,
Revision = file.Revision,
Title = file.Title
});
}
}
private void Init(Transmittal transmittal)
{
this.Subject = transmittal.Subject;
this.Message = transmittal.Message;
this.TransmittalNumber = transmittal.TransmittalNumber;
this.TransmittedFiles = transmittal.Files;
this.TransmittalId = transmittal.TransmittalId;
if (transmittal.Distribution != null)
{
var to = from d in transmittal.Distribution
where d.IsCced == false
select d;
this.To = new SubscriberItemCollection(to);
var cc = from d in transmittal.Distribution
where d.IsCced == true
select d;
this.Cc = new SubscriberItemCollection(cc);
}
}
public Transmittal Convert(IDocllerContext context)
{
Transmittal transmittal = new Transmittal
{
TransmittalNumber = this.TransmittalNumber,
Subject = this.Subject,
Message = this.Message,
CreatedBy = new User() {UserName = context.UserName},
ProjectId = context.ProjectId,
TransmittalStatus = new Status() {StatusId = this.StatusId},
Files = this.TransmittedFiles,
TransmittalId = this.TransmittalId
};
return transmittal;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Assignment2
{
public class TodoRepository : ITodoRepository {
private readonly IGenericList<TodoItem> _inMemoryTodoDatabase;
public TodoRepository(IGenericList<TodoItem> initialDbState = null)
{
_inMemoryTodoDatabase = initialDbState ?? new GenericList<TodoItem>();
}
public TodoItem Get(Guid todoId)
{
if (_inMemoryTodoDatabase.Count == 0) return null;
return _inMemoryTodoDatabase.FirstOrDefault(t => t.Id == todoId);
}
public TodoItem Add(TodoItem todoItem)
{
if (_inMemoryTodoDatabase.Contains(todoItem))
throw new DuplicateTodoItemException("duplicate id: {" + todoItem.Id + "}");
_inMemoryTodoDatabase.Add(todoItem);
return _inMemoryTodoDatabase.Last();
}
public bool Remove(Guid todoId)
{
if (_inMemoryTodoDatabase.Count == 0 || Get(todoId) == null) return false;
return _inMemoryTodoDatabase.Remove(_inMemoryTodoDatabase.FirstOrDefault(t => t.Id == todoId));
}
public TodoItem Update(TodoItem todoItem)
{
if (_inMemoryTodoDatabase.Contains(todoItem) == false)
{
return Add(todoItem);
}
_inMemoryTodoDatabase.Remove(todoItem);
return Add(todoItem);
}
public bool MarkAsCompleted(Guid todoId)
{
if (_inMemoryTodoDatabase.Count == 0 || Get(todoId) == null) return false;
return _inMemoryTodoDatabase.First(t => t.Id == todoId).MarkAsCompleted();
}
public List<TodoItem> GetAll()
{
return _inMemoryTodoDatabase.OrderByDescending(t => t.DateCreated).ToList();
}
public List<TodoItem> GetActive()
{
return _inMemoryTodoDatabase.Where(t => t.IsCompleted == false).ToList();
}
public List<TodoItem> GetCompleted()
{
return _inMemoryTodoDatabase.Where(t => t.IsCompleted == true).ToList();
}
public List<TodoItem> GetFiltered(Func<TodoItem, bool> filterFunction)
{
return _inMemoryTodoDatabase.Where(t => filterFunction(t) == true).ToList();
}
}
}
|
using System;
using System.Threading.Tasks;
namespace Barebone.Common.Services.Interfaces
{
public interface IConnectivityService
{
bool HasNetworkConnection { get; }
event EventHandler<ConnectivityChangedEventArgs> ConnectivityChanged;
Task<bool> IsRemoteReachable();
void FakeToggleInternetConnection(bool value);
}
}
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class TempDB : MonoBehaviour {
public string userID;
public int userLEVEL;
public int userMMR;
public int userEXP;
public int userWIN;
public int userLOSE;
public int userGOLD;
public bool userONLINE;
public string[] userHERO;
public string[] userHeroITEM;
public List<string> HeroList;
public List<string> HeroItemList;
// Use this for initialization
void Start () {
userHERO = new string[10];
userHeroITEM = new string[40];
}
// Update is called once per frame
void Update () {
}
public void FillUserInfo(string info){
print (info);
info = info.Substring (info.IndexOf("#"));
string[] sp;
print (info);
sp = info.Split ('#');
List<string> infolist = new List<string> (sp.Length);
infolist.AddRange (sp);
userID = infolist [1];
userLEVEL = Int32.Parse (infolist [2]);
userMMR = Int32.Parse (infolist [3]);
userEXP = Int32.Parse (infolist [4]);
userWIN = Int32.Parse (infolist [5]);
userLOSE =Int32.Parse (infolist [6]);
userGOLD = Int32.Parse (infolist[7]);
userONLINE = true;
Debug.Log (userID+userLEVEL+userMMR+userEXP+userWIN+userLOSE+userGOLD+userONLINE);
}
public void FillHero(string info)
{
Debug.Log ("Fill Hero");
info = info.Substring (info.IndexOf("#"));
info = info.Substring (1);
print (info);
userHERO = info.Split ('#');
HeroList.AddRange (userHERO);
}
public void FillHeroItem(string info)
{
Debug.Log ("Fill Hero Item");
info = info.Substring (info.IndexOf("#"));
info = info.Substring (1);
print (info);
userHeroITEM = info.Split ('#');
HeroItemList.AddRange (userHeroITEM);
}
}
|
using Crystal.Plot2D;
using Crystal.Plot2D.Charts;
using Crystal.Plot2D.DataSources;
using System;
using System.Data;
using System.Windows;
using System.Windows.Media;
namespace S002MarkerGraph
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var table = new DataTable();
table.Columns.Add("Sine", typeof(double));
table.Columns.Add("Time", typeof(DateTime));
table.Columns.Add("Index", typeof(int));
table.Columns.Add("Sqrt", typeof(double));
table.Columns.Add("Cosine", typeof(double));
for (int i = 0; i < 1000; i++)
{
table.Rows.Add(Math.Sin(i / 100.0), DateTime.Now + new TimeSpan(0, 0, i), i,
Math.Sqrt(i / 100.0),
Math.Cos(i / 100.0));
}
var data1 = new TableDataSource(table)
{
XMapping = row => ((DateTime)row["Time"] - (DateTime)table.Rows[0][1]).TotalSeconds,
YMapping = row => 10 * (double)row["Sine"]
};
// Map HSB color computes from "Index" column to dependency property Brush of marker
data1.AddMapping(ShapePointMarker.FillBrushProperty, row => new SolidColorBrush(new HsbColor(15 * (int)row["Index"], 1, 1).ToArgbColor()));
// Map "Sqrt" based values to marker size
data1.AddMapping(ShapePointMarker.DiameterProperty, row => 3 * (double)row["Sqrt"]);
// Plot first graph
plotter.AddMarkerPointsGraph(data1);
// Plot second graph
var data2 = new TableDataSource(table)
{
XMapping = row => ((DateTime)row["Time"] - (DateTime)table.Rows[0][1]).TotalSeconds,
YMapping = row => 10 * (double)row["Cosine"]
};
data2.AddMapping(ShapePointMarker.FillBrushProperty, row => new SolidColorBrush(new HsbColor(15 * (int)row["Index"], 1, 1).ToArgbColor()));
data2.AddMapping(ShapePointMarker.DiameterProperty, row => 3 * (double)row["Sqrt"]);
var circleMarker = new CirclePointMarker()
{
OutlinePen = new Pen { Brush = new SolidColorBrush(Colors.Black) }
};
var triangleMarker = new TrianglePointMarker()
{
OutlinePen = new Pen { Brush = new SolidColorBrush(Colors.Black) }
};
triangleMarker.OutlinePen.Freeze();
var rectangleMarker = new RectanglePointMarker()
{
OutlinePen = new Pen { Brush = new SolidColorBrush(Colors.Black) }
};
plotter.AddMarkerPointsGraph(pointSource: data2, triangleMarker);
plotter.AddCursor(new CursorCoordinateGraph());
}
}
}
|
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Appnotics.Library.UI.UserControls
{
/// <summary>
/// Interaction logic for IntegerUpDown.xaml
/// </summary>
public partial class TimePicker : UserControl, INotifyPropertyChanged
{
public event EventHandler TimeChanged;
public void OnTimeChanged()
{
EventHandler handler = TimeChanged;
if (null != handler)
handler(this, EventArgs.Empty);
}
private int selecting = 0;
private int minValue = 0;
public int MinValue
{
get { return minValue; }
set {
minValue = value;
useMinMax = true;
}
}
private int maxValue = 10;
public int MaxValue
{
get { return maxValue; }
set {
maxValue = value;
useMinMax = true;
}
}
private int defaultValue = 1;
public int DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; }
}
private int stepValue = 1;
public int StepValue
{
get { return stepValue; }
set { stepValue = value; }
}
private int currentHoursValue;
public int CurrentHoursValue
{
get { return currentHoursValue; }
set {
currentHoursValue = value;
SetDisplayValue();
OnPropertyChanged("CurrentHoursValue");
}
}
private int currentMinutesValue;
public int CurrentMinutesValue
{
get { return currentMinutesValue; }
set
{
currentMinutesValue = value;
SetDisplayValue();
OnPropertyChanged("CurrentMinutesValue");
}
}
private int currentSecondsValue;
public int CurrentSecondsValue
{
get { return currentSecondsValue; }
set
{
currentSecondsValue = value;
SetDisplayValue();
OnPropertyChanged("CurrentSecondsValue");
}
}
public DateTime CurrentDateTime
{
get
{
DateTime retVal;
if (!DateTime.TryParse(CurrentValue, out retVal))
retVal = DateTime.Now;
return retVal;
}
}
public static readonly DependencyProperty TimeProperty = DependencyProperty.Register("TimeString", typeof(string), typeof(TimePicker));
public string TimeString
{
get {
string cv = CurrentValue;
return cv;
}
set {
SetValue(TimeProperty, value);
CurrentValue = value;
}
}
public string CurrentValue
{
set
{
string[] timeStrings = value.Split(':');
if (timeStrings.Length == 3)
{
int num;
if (int.TryParse(timeStrings[0], out num))
{
if ((num >= 0) && (num <= 23))
CurrentHoursValue = num;
}
if (int.TryParse(timeStrings[1], out num))
{
if ((num >= 0) && (num <= 59))
CurrentMinutesValue = num;
}
if (int.TryParse(timeStrings[2], out num))
{
if ((num >= 0) && (num <= 59))
CurrentSecondsValue = num;
}
}
}
get
{
string sumText = HoursText.Text + ":" + MinutesText.Text + ":" + SecondsText.Text;
return sumText;
}
}
private bool useMinMax = false;
public bool UseMinMax
{
get { return useMinMax; }
set { useMinMax = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private static bool settingText = false;
public TimePicker()
{
InitializeComponent();
currentHoursValue = 0;
currentMinutesValue = 0;
CurrentSecondsValue = 0;
}
private void SetDisplayValue()
{
settingText = true;
HoursText.Text = currentHoursValue.ToString("00");
MinutesText.Text = currentMinutesValue.ToString("00");
SecondsText.Text = currentSecondsValue.ToString("00");
OnTimeChanged();
settingText = false;
}
private void SetSelection()
{
if (selecting == 0)
{
HoursText.SelectAll();
HoursText.Focus();
}
else if (selecting == 1)
{
MinutesText.SelectAll();
MinutesText.Focus();
}
else if (selecting == 2)
{
SecondsText.SelectAll();
SecondsText.Focus();
}
}
private void SetCurrentValue(int number)
{
if (selecting == 0)
{
if (number > 23)
currentHoursValue = 0;
else if (number < 0)
currentHoursValue = 23;
else
currentHoursValue = number;
}
else if (selecting == 1)
{
if (number > 59)
currentMinutesValue = 0;
else if (number < 0)
currentMinutesValue = 59;
else
currentMinutesValue = number;
}
else if (selecting == 2)
{
if (number > 59)
currentSecondsValue = 0;
else if (number < 0)
currentSecondsValue = 59;
else
currentSecondsValue = number;
}
SetDisplayValue();
}
private void OnUp(object sender, RoutedEventArgs e)
{
if (selecting == 0)
{
currentHoursValue += 1;
if (currentHoursValue > 23)
currentHoursValue = 0;
}
else if (selecting == 1)
{
currentMinutesValue += 1;
if (currentMinutesValue > 59)
currentMinutesValue = 0;
}
else if (selecting == 2)
{
currentSecondsValue += 1;
if (currentSecondsValue > 59)
currentSecondsValue = 0;
}
SetDisplayValue();
SetSelection();
}
private void OnDown(object sender, RoutedEventArgs e)
{
if (selecting == 0)
{
currentHoursValue -= 1;
if (currentHoursValue < 0)
currentHoursValue = 23;
}
else if (selecting == 1)
{
currentMinutesValue -= 1;
if (currentMinutesValue < 0)
currentMinutesValue = 59;
}
else if (selecting == 2)
{
currentSecondsValue -= 1;
if (currentSecondsValue < 0)
currentSecondsValue = 59;
}
SetDisplayValue();
SetSelection();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
{
NUDButtonUP.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { true });
}
if (e.Key == Key.Down)
{
NUDButtonDown.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { true });
}
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonUP, new object[] { false });
if (e.Key == Key.Down)
typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(NUDButtonDown, new object[] { false });
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (settingText == false)
{
TextBox tb = sender as TextBox;
int number = 0;
if (tb.Text != "")
{
if (!int.TryParse(tb.Text, out number))
{
if (selecting == 0)
currentHoursValue = 0;
else if (selecting == 1)
currentMinutesValue = 0;
else if (selecting == 2)
currentSecondsValue = 0;
return;
}
SetCurrentValue(number);
// tb.SelectAll();
// tb.SelectionStart = tb.Text.Length;
}
}
}
private string DoubleCharacter(int num)
{
string s = num.ToString("00");
return s;
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb == HoursText)
{
selecting = 0;
}
else if (tb == MinutesText)
{
selecting = 1;
}
else if (tb == SecondsText)
{
selecting = 2;
}
tb.SelectAll();
// tb.SelectionStart = tb.Text.Length;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TimeSheet
{
/// <summary>
/// AnimationItems.xaml 的交互逻辑
public class AnimationObject
{
public virtual string getName() { return null; }
public virtual string getIcon() { return null; }
public TimeSheetControl.TimeCurve mCurve = null;
private AnimationtItem _mUI = null;
public AnimationtItem mUI
{
get
{
if(_mUI == null)
{
_mUI = new AnimationtItem();
(_mUI as AnimationtItem).m_choosen_button.Background = new SolidColorBrush(Colors.Black);
_mUI.name = getName();
_mUI.icon = getIcon();
}
return _mUI;
}
}
public void resetUI()
{
_mUI = null;
}
public virtual AnimationProperty createProperty()
{
return null;
}
public virtual AnimationProperty addProperty(TimeSheetControl.TimeCurve.TimeKey key)
{
var prop = createProperty();
prop.m_animation_object = this;
if(key != null)
{
key.attachProperty = prop;
}
return prop;
}
public virtual Object toObject()
{
return this;
}
public virtual AnimationObject newInstance()
{
return null;
}
}
public abstract class AnimationProperty //automatic UI
{
public Panel mPanel = null;
public AnimationObject m_animation_object = null;
public virtual AnimationObject getAnimationObject()
{
return m_animation_object;
}
public virtual void attackObject(Object obj) { }
public virtual Object getObject()//转换接口
{
return this;
}
public abstract void copyFrom(AnimationProperty other);//属性的拷贝
public abstract AnimationProperty clone();
public virtual bool compare(AnimationProperty other)//属性的拷贝
{
return false;
}
public AnimationProperty undoListCurrent()
{
if(m_undoList.Count != 0)
{
return m_undoList.Last();
}
return null;
}
public bool isChange()
{
var undoAp = undoListCurrent();
if (undoAp == null) return true;
return !this.compare(undoAp);
}
const int maxRedo = 5;
int undoIdx = -1;
List<AnimationProperty> m_undoList = new List<AnimationProperty>();
public void undo()
{
if (undoIdx <= 0) return;
undoIdx--;
this.copyFrom(m_undoList[undoIdx]);
}
public void redo()
{
if (undoIdx+1 == m_undoList.Count) return;
undoIdx++;
this.copyFrom(m_undoList[undoIdx]);
}
public bool record()
{
if (!isChange()) return false;
AnimationProperty ap = this.clone();
if(undoIdx + 1 != m_undoList.Count)
{
m_undoList.RemoveRange(undoIdx + 1, m_undoList.Count - (undoIdx + 1));
}
m_undoList.Add(ap);
undoIdx++;
return true;
}
public virtual void changeNotify()
{
if (record())
{
//drawUI(mPanel);
}
}
Button m_record = null;
Button m_redo = null;
Button m_undo = null;
public virtual void drawUI(Panel parent)
{
mPanel = parent;
parent.Children.Clear();
StackPanel sp = new StackPanel();
parent.Children.Add(sp);
sp.Orientation = Orientation.Horizontal;
if(undoIdx == -1)
record();
//撤销
Button m_undo = new Button();
sp.Children.Add(m_undo);
m_undo.Content = "撤销";
m_undo.Width = 60;
//if (undoIdx <= 0)
//{
// m_undo.IsEnabled = false;
//}
//else
{
m_undo.Click += (s, arg) =>
{
undo();
drawUI(mPanel);
};
}
//重做
m_redo = new Button();
sp.Children.Add(m_redo);
m_redo.Content = "重做";
m_redo.Width = 60;
//if (undoIdx+1 >= m_undoList.Count)
//{
// m_undo.IsEnabled = false;
//}
//else
{
m_redo.Click += (s, arg) =>
{
redo();
drawUI(mPanel);
};
}
//记录
m_record = new Button();
sp.Children.Add(m_record);
m_record.Content = "记录";
m_record.Width = 60;
//if(!isChange() )
//{
// m_record.IsEnabled = false;
//}
//else
{
m_record.Click += (s, arg) =>
{
record();
drawUI(parent);
};
}
}
public TimeSheetControl.TimeCurve.TimeKey mKey;
}
public partial class AnimationItemsCtrl : UserControl
{
ContextMenu mContextMenu = null;
public AnimationItemsCtrl()
{
InitializeComponent();
}
List<AnimationObject> mAnimationType = new List<AnimationObject>();
//注册类型
public void RegAnimationObjectType(AnimationObject proto)
{
reset();
mAnimationType.Clear();
mAnimationType.Add(proto);
draw();
}
private void BtnAddAnimation(object sender, RoutedEventArgs e)
{
//弹出右键菜单
mContextMenu = new ContextMenu();
foreach(var proto in mAnimationType)
{
MenuItem mi = new MenuItem();
mi.Header = proto.getName();
mi.Click += new RoutedEventHandler( (obj, arg) =>
{
var item = proto.newInstance();
var tl = m_timesheet.addTimeLine(" ");
tl.attackObject = item;
m_timesheet.timeCurveSelected = tl;
draw();
});
mContextMenu.Items.Add(mi);
}
mContextMenu.IsOpen = true;
}
TextBlock _ObjectTitle = null;
TextBlock xm_object_name
{
get
{
if(_ObjectTitle == null)
{
_ObjectTitle = UIHelper.FindChild<TextBlock>(this, "object_name");
}
return _ObjectTitle;
}
}
StackPanel _ObjectPanel = null;
StackPanel xm_objects
{
get
{
if (_ObjectPanel == null)
{
_ObjectPanel = m_objects;
}
return _ObjectPanel;
}
}
bool bKeyBind = false;
void reset()
{
m_timesheet.reset();
m_objects.Children.Clear();
m_object_name.Text = "no objects";
if(!bKeyBind)
{
var window = Window.GetWindow(this);
window.PreviewKeyDown += window_KeyDown;
bKeyBind = true;
}
}
void OnAddKey(TimeSheetControl.TimeCurve tc, TimeSheetControl.TimeCurve.TimeKey tk)
{
//temly not use
}
void OnRemoveKey(TimeSheetControl.TimeCurve tc, TimeSheetControl.TimeCurve.TimeKey tk)
{
//temply not use
}
//TimeSheetControl.TimeCurve oldCurve = null;
//TimeSheetControl.TimeCurve.TimeKey oldKey = null;
AnimationProperty _editProperty = null;
AnimationProperty editProperty
{
get
{
var tk = m_timesheet.timeKeySelected;
var tc = m_timesheet.timeCurveSelected;
if(tk != null)
{
if (tk.attachProperty == null)
{
var ao = tc.attackObject as AnimationObject;
_editProperty = ao.addProperty(tk);
}
return tk.attachProperty as AnimationProperty;
}
if(tc != null)
{
var ao = tc.attackObject as AnimationObject;
if(_editProperty == null || _editProperty.getAnimationObject() != ao)
{
_editProperty = ao.addProperty(tk);
}
}
return _editProperty;
}
}
void OnSelectChange(TimeSheetControl.TimeCurve oc, TimeSheetControl.TimeCurve.TimeKey ok,
TimeSheetControl.TimeCurve nc, TimeSheetControl.TimeCurve.TimeKey nk)
{
if(nc != oc)
{
if (oc != null)
{
var ao = (oc.attackObject as AnimationObject);
if (ao == null) return;
if (ao.mUI == null) return;
ao.mUI.m_choosen_button.Background = new SolidColorBrush(Colors.Black);
}
}
if (nc != null)
{
var ao = (nc.attackObject as AnimationObject);
if (ao == null) return;
ao.mUI.m_choosen_button.Background = new SolidColorBrush(Color.FromArgb(127, 0, 0, 255));
}
if(nk != ok)
{
editProperty.drawUI(m_propertys);
}
}
void draw()
{
m_objects.Children.Clear();
m_object_name.Text = "属性";
m_propertys.Children.Clear();
//draw property
var choosenCurve = m_timesheet.timeCurveSelected;
if(choosenCurve != null)
{
var item = choosenCurve.attackObject as AnimationObject;
m_object_name.Text = item.getName()+"属性";
}
else
{
m_object_name.Text = "属性";
}
if(editProperty != null)
{
editProperty.drawUI(m_propertys);//属性UI
}
//draw object list
foreach(var curve in m_timesheet.timeCurves)
{
var tmpCurve = curve;//for closure use
var ao = curve.attackObject as AnimationObject;
m_objects.Children.Add(ao.mUI);
ao.mUI.m_choosen_button.Click += delegate(object sender, RoutedEventArgs e)
{
var ao1 = m_timesheet.timeCurveSelected.attackObject as AnimationObject;
if(m_timesheet.timeCurveSelected != tmpCurve)
{
if (m_timesheet.timeKeySelected != null)
{
m_timesheet.timeKeySelected = null;
}
m_timesheet.timeCurveSelected = tmpCurve;
}
//ao1 = m_timesheet.timeCurveSelected.attackObject as AnimationObject;
//ao1.mUI.m_choosen_button.Background = new SolidColorBrush(Colors.YellowGreen);
m_timesheet.repaint();
};
}
m_timesheet.repaint();
}
private void onPlaying(bool pause, double t)
{
if(pause)
{
if ((string)m_play.Content != "播")
m_play.Content = "播";
}
else
{
if ((string)m_play.Content != "暂")
m_play.Content = "暂";
}
//Console.WriteLine("onTime: " + t);
}
private void BtnOnPlay(object sender, RoutedEventArgs e)
{
//TimeSheetControl.evtOnPlaying -= onPlaying;
//TimeSheetControl.evtOnPlaying += onPlaying;
if (m_timesheet.m_stopwatch.isPause())
m_timesheet.timePlay();
else
m_timesheet.timePause();
}
private void BtnRemoveAnimation(object sender, RoutedEventArgs e)
{
var cv = m_timesheet.timeCurveSelected;
if(cv != null)
{
var ao = (cv.attackObject as AnimationObject);
((ao.mUI.Parent) as Panel).Children.Remove(ao.mUI);
m_timesheet.removeTimeLine(cv);
}
}
private void m_reset_Click(object sender, RoutedEventArgs e)
{
m_timesheet.timeReset();
}
private void m_nextkey_Click(object sender, RoutedEventArgs e)
{
m_timesheet.selectNextKey();
}
private void m_prekey_Click(object sender, RoutedEventArgs e)
{
m_timesheet.selectPreviewKey();
}
private void m_scroll_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
m_timesheet.scrollY = e.VerticalOffset;
m_timesheet.repaint();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
//这里只放绑定
TimeSheetControl.evtOnAddTimeKey += OnAddKey;
TimeSheetControl.evtOnRemoveTimeKey += OnRemoveKey;
TimeSheetControl.evtOnSelectChanged += OnSelectChange;
TimeSheetControl.evtOnPlaying += onPlaying;//时间轴播放
TimeSheetControl.evtOnPickTime += t =>//鼠标点击事件
{
m_time_box.Text = t;
};
}
private void window_KeyDown(object sender, RoutedEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Z) && Keyboard.IsKeyDown(Key.LeftCtrl))
{
var ao = editProperty;
if (ao != null)
{
ao.undo();
ao.drawUI(ao.mPanel);
}
}
else if (Keyboard.IsKeyDown(Key.Y) && Keyboard.IsKeyDown(Key.LeftCtrl))
{
var ao = editProperty;
if (ao != null)
{
ao.redo();
ao.drawUI(ao.mPanel);
}
}
}
}
}
|
using System;
using System.Drawing;
using System.IO;
using System.Web;
using log4net;
namespace mssngrrr
{
public class Upload : BaseHandler
{
protected override AjaxResult ProcessRequestInternal(HttpContext context)
{
if(context.Request.Files.Count == 0)
throw new AjaxException("No files uploaded");
if(context.Request.Files.Count > 1)
throw new AjaxException("Uploading multiple files not allowed");
var uploadPath = context.Server.MapPath(Settings.UploadPath);
Directory.CreateDirectory(uploadPath);
var file = context.Request.Files[0];
string filename;
string extension;
try
{
filename = Path.GetFileName(file.FileName);
extension = Path.GetExtension(filename);
}
catch(ArgumentException e)
{
throw new AjaxException("Invalid filename", e);
}
if(string.IsNullOrEmpty(filename))
throw new AjaxException("Invalid filename");
if(file.ContentLength > Settings.MaxFileSize)
throw new AjaxException(string.Format("File too large (max {0} bytes)", Settings.MaxFileSize));
if(!(Settings.AllowedMimeTypes.Contains(file.ContentType) && Settings.AllowedExtensions.Contains(extension)))
throw new AjaxException("File type not allowed");
int width, height;
try
{
using(var img = Image.FromStream(file.InputStream))
{
width = img.Width;
height = img.Height;
}
}
catch(Exception e)
{
throw new AjaxException("Failed to open image", e);
}
if(width > Settings.MaxImageWidth || height > Settings.MaxImageHeight)
throw new AjaxException(string.Format("Image too large (max {0}x{1})", Settings.MaxImageWidth, Settings.MaxImageHeight));
var userid = AuthModule.GetUserId();
var dir = Path.Combine(uploadPath, userid.ToString("N"));
Directory.CreateDirectory(dir);
var filepath = Path.Combine(dir, filename);
file.SaveAs(filepath);
Log.InfoFormat("Saved image '{0}'", filepath);
return new AjaxResult {Name = filename, Length = file.ContentLength};
}
private static readonly ILog Log = LogManager.GetLogger(typeof(Upload));
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoGrabberMod.Models;
using Microsoft.Xna.Framework;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.TerrainFeatures;
namespace AutoGrabberMod.Features
{
using SVObject = StardewValley.Object;
class Forage : Feature
{
public override string FeatureName { get => "Auto Forage / Coop / Truffles"; }
public override string FeatureConfig => "forage";
public override int Order => 1;
public override bool IsAllowed => Utilities.Config.AllowAutoForage;
public Forage()
{
Value = false;
}
public override void Action()
{
if (!IsAllowed || !(bool)Value) return;
Utilities.Monitor.Log($" {Grabber.InstanceName} Attempting to forage items", StardewModdingAPI.LogLevel.Trace);
Vector2[] nearbyTiles = (Grabber.RangeEntireMap ? Utilities.GetLocationObjectTiles(Grabber.Location) : Grabber.NearbyTilesRange).ToArray();
Random random = new Random();
//Handle animal houses
foreach (Vector2 tile in nearbyTiles.Where(tile => Grabber.Location.Objects.ContainsKey(tile) && Utilities.IsGrabbableCoop(Grabber.Location.Objects[tile])).ToArray())
{
if (Grabber.IsChestFull) break;
if (tile != null && Grabber.Location.objects.ContainsKey(tile)
&& Grabber.Location.objects[tile].Name != null
&& Grabber.Location.objects[tile].Name.Contains("Slime Ball"))
{
Random rr = new Random((int)Game1.stats.daysPlayed + (int)Game1.uniqueIDForThisGame + (int)tile.X * 77 + (int)tile.Y * 777 + 2);
Grabber.GrabberChest.addItem(new SVObject(766, random.Next(10, 21), false, -1, 0));
int i = 0;
while (random.NextDouble() < 0.33) i++;
if (i > 0) Grabber.GrabberChest.addItem(new SVObject(557, i, false, -1, 0));
}
else if (Grabber.GrabberChest.addItem(Grabber.Location.Objects[tile]) != null) continue;
//Utilities.Monitor.Log($" {Grabber.InstanceName} foraged: {Grabber.Location.Objects[tile].Name} {tile.X},{tile.Y}", StardewModdingAPI.LogLevel.Trace);
Grabber.Location.Objects.Remove(tile);
if (Grabber.GainExperience) Utilities.GainExperience(Grabber.FORAGING, 5);
}
//Handle Spring onions
foreach (Vector2 tile in nearbyTiles.Where((tile) => Grabber.Location.terrainFeatures.ContainsKey(tile) && Grabber.Location.terrainFeatures[tile] is HoeDirt dirt && dirt.crop != null && dirt.crop.forageCrop.Value && dirt.crop.whichForageCrop.Value == 1))
{
if (Grabber.IsChestFull) break;
if (tile == null || !Grabber.Location.terrainFeatures.ContainsKey(tile)) continue;
SVObject onion = new SVObject(399, 1, false, -1, 0);
if (Game1.player.professions.Contains(16)) onion.Quality = 4;
else if (random.NextDouble() < Game1.player.ForagingLevel / 30.0) onion.Quality = 2;
else if (random.NextDouble() < Game1.player.ForagingLevel / 15.0) onion.Quality = 1;
if (Game1.player.professions.Contains(13))
{
while (random.NextDouble() < 0.2) onion.Stack += 1;
}
Utilities.Monitor.Log($" {Grabber.InstanceName} foraged: {onion.Name} {onion.Stack} {tile.X}, {tile.Y}", StardewModdingAPI.LogLevel.Trace);
Grabber.GrabberChest.addItem(onion);
(Grabber.Location.terrainFeatures[tile] as HoeDirt).crop = null;
if (Grabber.GainExperience) Utilities.GainExperience(Grabber.FORAGING, 3);
}
//Handle world forageables
foreach (Vector2 tile in nearbyTiles.Where(tile => Grabber.Location.Objects.ContainsKey(tile) && (Utilities.IsGrabbableWorld(Grabber.Location.Objects[tile]) || Grabber.Location.Objects[tile].isForage(null))).ToArray())
{
if (Grabber.IsChestFull) break;
if (tile == null || !Grabber.Location.Objects.ContainsKey(tile)) continue;
SVObject obj = Grabber.Location.Objects[tile];
if (Game1.player.professions.Contains(16)) obj.Quality = 4;
else if (random.NextDouble() < Game1.player.ForagingLevel / 30.0) obj.Quality = 2;
else if (random.NextDouble() < Game1.player.ForagingLevel / 15.0) obj.Quality = 1;
if (Game1.player.professions.Contains(13))
{
while (random.NextDouble() < 0.2) obj.Stack += 1;
}
Utilities.Monitor.Log($" {Grabber.InstanceName} foraged: {obj.Name} {obj.Stack} {tile.X},{tile.Y}", StardewModdingAPI.LogLevel.Trace);
Item item = Grabber.GrabberChest.addItem(obj);
Grabber.Location.Objects.Remove(tile);
if (Grabber.GainExperience) Utilities.GainExperience(Grabber.FORAGING, 7);
}
//Handle berry bushes
if (Grabber.RangeEntireMap)
{
int berryIndex;
foreach (LargeTerrainFeature feature in Grabber.Location.largeTerrainFeatures)
{
if (Grabber.IsChestFull) break;
if (Game1.currentSeason == "spring") berryIndex = 296;
else if (Game1.currentSeason == "fall") berryIndex = 410;
else break;
if (feature is Bush bush)
{
if (bush.inBloom(Game1.currentSeason, Game1.dayOfMonth) && bush.tileSheetOffset.Value == 1)
{
SVObject berry = new SVObject(berryIndex, 1 + Game1.player.FarmingLevel / 4, false, -1, 0);
if (Game1.player.professions.Contains(16))
{
berry.Quality = 4;
}
Utilities.Monitor.Log($" {Grabber.InstanceName} foraged: {berry.Name} {berry.Stack}", StardewModdingAPI.LogLevel.Trace);
bush.tileSheetOffset.Value = 0;
bush.setUpSourceRect();
Grabber.GrabberChest.addItem(berry);
}
}
}
}
Grabber.Grabber.showNextIndex.Value |= Grabber.GrabberChest.items.Count != 0;
}
public void ActionItemAddedRemoved(object sender, EventArgsLocationObjectsChanged e)
{
if (!IsAllowed || !(bool)Value || Grabber.IsChestFull) return;
//Utilities.Monitor.Log($" {Grabber.InstanceName} Attempting to forage truffle items", StardewModdingAPI.LogLevel.Trace);
System.Random random = new System.Random();
Vector2[] nearbyTiles = Grabber.RangeEntireMap ? Utilities.GetLocationObjectTiles(Grabber.Location).ToArray() : Grabber.NearbyTilesRange;
foreach (KeyValuePair<Vector2, SVObject> pair in e.Added)
{
if (pair.Value.ParentSheetIndex != 430 || pair.Value.bigCraftable.Value || !nearbyTiles.Contains(pair.Key)) continue;
SVObject obj = pair.Value;
if (obj.Stack == 0) obj.Stack = 1;
//make sure its a forageable and grabable
if (!obj.isForage(null) && !Utilities.IsGrabbableWorld(obj)) continue;
if (Game1.player.professions.Contains(16)) obj.Quality = 4;
else if (random.NextDouble() < Game1.player.ForagingLevel / 30.0) obj.Quality = 2;
else if (random.NextDouble() < Game1.player.ForagingLevel / 15.0) obj.Quality = 1;
if (Game1.player.professions.Contains(13))
{
while (random.NextDouble() < 0.2) obj.Stack += 1;
}
//Utilities.Monitor.Log($" {Grabber.InstanceName} foraged: {obj.Name} {obj.Stack} {pair.Key.X},{pair.Key.Y}", StardewModdingAPI.LogLevel.Trace);
Grabber.GrabberChest.addItem(obj);
e.Location.Objects.Remove(pair.Key);
if (Grabber.GainExperience) Utilities.GainExperience(Grabber.FORAGING, 7);
}
}
}
}
|
using AspNet.Security.OAuth.GitHub;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
public static class GitHubAuthenticationExtensions
{
public static AuthenticationBuilder AddGitHub(this AuthenticationBuilder builder, IConfiguration options)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
/*builder.AddGitHub(new GitHubAuthenticationOptions
{
DisplayName = options.GetSection("Name").Value,
ClientId = options.GetSection("ClientId").Value,
ClientSecret = options.GetSection("ClientSecret").Value,
AuthenticationScheme = GitHubAuthenticationDefaults.AuthenticationScheme,
SignInScheme = "idsrv.external"
});*/
return builder;
}
}
}
|
using System;
using System.IO;
namespace WordGuessGame
{
public class Program
{
static void Main(string[] args)
{
//string path = "../../../../wordbank.txt";
//ShowWordBank(path);
//ShowMysteryWord(path);
ShowMenu();
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadLine();
}
/**
* FILE METHODS
**/
/// <summary>
/// ReadWordBank takes a path to text file and then opens (and closes) it using File.AllLines. The text read from File.AllLines is placed in an array and return to the method that call it.
/// </summary>
/// <param name="path"></param>
/// <returns>An array of strings</returns>
public static string[] ReadWordBank (string path)
{
try
{
string[] words = File.ReadAllLines(path);
return words;
}
catch (Exception error)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(error.Message);
}
return null;
}
/// <summary>
/// This method takes a path to a text file, an array of words, and a new word to add to the array. The method creates a new array of a size equal to the original array plus the new word and uses a for loop to iterate over the new array and assign it the values of the old one. When at the last element of the array, the new word is inserted. The WriteAllLines method of the File class is then used to write the content of the new array into the file. The method then calls the ReadWordBank method which returns an array of words from the updated file.
/// </summary>
/// <param name="path"></param>
/// <param name="newWord"></param>
/// <param name="words"></param>
/// <returns>An array of words including the added word</returns>
public static string[] AddWord(string path, string newWord, string[] words)
{
try
{
string[] updatedWords = new string[(words.Length + 1)];
for (int i = 0; i < updatedWords.Length; i++)
{
if (i == (updatedWords.Length - 1))
{
updatedWords[i] = newWord;
}
else
{
updatedWords[i] = words[i];
}
}
File.WriteAllLines(path, updatedWords);
return ReadWordBank(path);
}
catch (Exception error)
{
Console.WriteLine("The word could not be added:");
Console.WriteLine(error.Message);
}
return null;
}
/// <summary>
/// This method takes a path to a text file, an array of words, an old word that will be edited, and a new word that is the edited version of the original (old) word. The method creates a new array of a size equal to the original array uses a for loop to iterate over the new array and assign the values of the old one. When an index contains the value of the old word, then new word is inserted in it's stead and the iteration continues. The WriteAllLines method of the File class is then used to write the content of the new array into the file. The method then calls the ReadWordBank method which returns an array of words from the updated file.
/// </summary>
/// <param name="path"></param>
/// <param name="oldWord"></param>
/// <param name="newWord"></param>
/// <param name="words"></param>
/// <returns>An array of words including the edited word</returns>
public static string[] EditWord(string path, string oldWord, string newWord, string[] words)
{
try
{
string[] updatedWords = new string[(words.Length)];
for (int i = 0; i < updatedWords.Length; i++)
{
if (words[i].Contains(oldWord))
{
updatedWords[i] = newWord;
}
else
{
updatedWords[i] = words[i];
}
}
File.WriteAllLines(path, updatedWords);
return ReadWordBank(path);
}
catch (Exception error)
{
Console.WriteLine("The word could not be added:");
Console.WriteLine(error.Message);
}
return null;
}
/// <summary>
/// This method takes a path, an array of words, and a word to be deleted. A new array is created that is equal to the length of the original array minus one, since a word needs to be deleted. A for loop is used to iterate over the new array while assigning values from the original array to it. When the value at i index of the original array is equal to the word to be deleted, the next value in the original array is assigned and the iterator is updated twice. File.WriteAllLines is used to write the contents of the new array to the file and then the contents of the file are returned when ReadWordBank is called.
/// </summary>
/// <param name="path"></param>
/// <param name="deleteWord"></param>
/// <param name="words"></param>
/// <returns>An array of words minus the deleted word</returns>
public static string[] DeleteWord(string path, string deleteWord, string[] words)
{
try
{
string[] updatedWords = new string[(words.Length - 1)];
for (int i = 0; i < updatedWords.Length; i++)
{
if (words[i].Contains(deleteWord))
{
updatedWords[i] = words[i + 1];
i++;
}
else
{
updatedWords[i] = words[i];
}
}
File.WriteAllLines(path, updatedWords);
return ReadWordBank(path);
}
catch (Exception error)
{
Console.WriteLine("The word could not be added:");
Console.WriteLine(error.Message);
}
return null;
}
/**
* GAMEPLAY METHODS
**/
/// <summary>
/// This method takes a file path and sends it to ReadWordBank to fill up a newly created string array with the contents of the file. Then a Random object is instantiated and a random index created using the Next method of the Random class and the length of the array. A random word variable is created and set to the value of the array at the random index. The method then returns the random word.
/// </summary>
/// <param name="path"></param>
/// <returns>A random word.</returns>
static string GetRandomWord(string path)
{
try
{
string[] wordBank = ReadWordBank(path);
Random random = new Random();
int index = random.Next(wordBank.Length);
string randomWord = wordBank[index];
return randomWord;
}
catch (Exception error)
{
Console.WriteLine("The word could not be retrieved: ");
Console.WriteLine(error.Message);
}
return null;
}
/// <summary>
/// This method takes the user's input and converts it to char.
/// </summary>
/// <returns>A character</returns>
static char GetGuess()
{
try
{
Console.Write("\n\nWhat letter do you think is in the word? ");
string guess = Console.ReadLine();
return Convert.ToChar(guess);
}
catch (Exception error)
{
Console.WriteLine("I am sorry but I was unable to collect your input:");
Console.WriteLine(error.Message);
}
return '_';
}
/// <summary>
/// This method takes in the word and a guess and returns true or false depending on if the word contains the guess.
/// </summary>
/// <param name="guess"></param>
/// <param name="mysterWord"></param>
/// <returns>True if the guess is correct, false if it isn't.</returns>
public static bool CheckGuess(char guess, string mysterWord)
{
if (mysterWord.Contains(guess)) return true;
return false;
}
/**
* INTERFACE METHODS
**/
/// <summary>
/// ShowWordBank takes a path to text file and then sends it to ReadWordBank. ReadWordBank returns an array that is assigned to a words array and then the words are rendered in the console. The user is able to add, edit, or delete words
/// </summary>
static void ShowWordBank(string path)
{
Console.Clear();
string[] words = ReadWordBank(path);
foreach (string word in words)
{
Console.WriteLine(word);
}
string userInput = "";
while (userInput.ToUpper() != "X")
{
Console.Write("What would you like to do? \t");
Console.Write("(A)dd a word \t");
Console.Write("(E)dit a word \t");
Console.Write("(D)elete a word \t");
Console.WriteLine("E(x)it");
userInput = Console.ReadLine();
switch (userInput.ToUpper())
{
case "A":
Console.Write("\n\nWhat word would you like to add? ");
string addWord = Console.ReadLine();
string[] addWords = ReadWordBank(path);
AddWord(path, addWord, addWords);
ShowWordBank(path);
break;
case "E":
Console.Write("\n\nWhat word would you like to edit? ");
string oldWord = Console.ReadLine();
Console.Write("\n\nWhat would you like to change it to? ");
string newWord = Console.ReadLine();
string[] editWords = ReadWordBank(path);
EditWord(path, oldWord, newWord, editWords);
ShowWordBank(path);
break;
case "D":
Console.Write("\n\nWhat word would you like to delete? ");
string deleteWord = Console.ReadLine();
string[] deleteWords = ReadWordBank(path);
DeleteWord(path, deleteWord, deleteWords);
ShowWordBank(path);
break;
case "X":
ShowMenu();
break;
default:
Console.WriteLine("Please enter a valid menu option");
break;
}
}
}
/// <summary>
/// This method takes a path and sends it to get a random word. It then creates an array of the same length as the random word and uses iteration to fill up the empty spaces with underscores and display them on the screen
/// </summary>
/// <param name="path"></param>
static void ShowMysteryWord(string path)
{
Console.Clear();
string mysteryWord = GetRandomWord(path);
int lettersInWord = mysteryWord.Length;
string [] displayWord = new string[mysteryWord.Length];
string guesses = "";
for (int i = 0; i < displayWord.Length; i++)
{
displayWord[i] = " _ ";
Console.Write(displayWord[i]);
}
Console.WriteLine("\n\nGuesses: ");
char guess;
bool isCorrect;
while (!string.Equals(mysteryWord, displayWord.ToString()))
{
Console.Write("\n\nGuess a letter in the word: ");
guess = GetGuess();
isCorrect = CheckGuess(guess, mysteryWord);
if (!isCorrect)
{
guesses += guess;
}
for (int j = 0; j < displayWord.Length; j++)
{
if (mysteryWord[j] == guess)
{
displayWord[j] = $"{ guess }";
lettersInWord--;
}
Console.Write(displayWord[j]);
}
Console.WriteLine($"\n\nGuesses: { guesses }");
if (lettersInWord == 0)
{
Console.WriteLine($"\n\nYou correctly guessed { string.Join("", displayWord)}!");
Console.WriteLine("Congratulations!");
return;
}
}
}
/// <summary>
/// Show menu shows the menu in console and keep the app open until the user decides to exit.
/// </summary>
static void ShowMenu()
{
try
{
string path = "../../../../wordbank.txt";
string userInput = "";
while (userInput != "3")
{
Console.Clear();
Console.WriteLine("\n 1. Play the Word Guess Game");
Console.WriteLine("\n 2. View the word bank");
Console.WriteLine("\n 3. Exit\n\n");
Console.Write("What would you like to do? ");
userInput = Console.ReadLine();
switch (int.Parse(userInput))
{
case 1:
ShowMysteryWord(path);
break;
case 2:
ShowWordBank(path);
break;
case 3:
return;
default:
Console.WriteLine("Please enter a valid menu option");
break;
}
}
}
catch (Exception error)
{
Console.WriteLine("Your input may have been invalid:");
Console.WriteLine(error.Message);
}
}
}
}
|
using System.Threading.Tasks;
using TaxiService.Order.Models;
using System.Collections.Generic;
namespace TaxiService.Order.Repositories
{
public interface IOrderRepository
{
Task<IEnumerable<Reservation>> GetAllOrders();
Task<Reservation> GetOrderByUserId(string userId);
Task<IEnumerable<Reservation>> GetOrdersByUsername(string userName);
Task<Reservation> CreateOrder(Reservation reservation);
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestStack.White;
using System.IO;
using System.Threading;
/// <summary>
/// Test UI with TestStack.White
/// </summary>
namespace tWhiteTestApp.MainWindowTests
{
[TestClass]
public class MainWindowTests
{
private const string BINARY_TO_LAUNCH = @"tWhiteTestApp.exe"; //binary to launch
private const string WINDOW_NAME = "Calculator";
private static string m_ApplicationPath; //path to application to launch
[ClassInitialize]
public static void Initialize(TestContext context)
{
var applicationDirectory = Directory.GetCurrentDirectory();//path to the binary
m_ApplicationPath = Path.Combine(applicationDirectory, BINARY_TO_LAUNCH); //initialize path to application
}
#region SuccessfulCalculation
[TestMethod]
public void SuccessfulPlusCalculation()
{
var window = WindowExtension.GetAppWindow(out Application application, m_ApplicationPath, WINDOW_NAME); //get window
//test data
var firstNumber = -15;
var secondNumber = 2;
window.SetTextBox("tbFirstNumber", firstNumber.ToString()); //set first textBox value
Thread.Sleep(1000);
window.SetTextBox("tbSecondNumber", secondNumber.ToString()); //set second textBox value
Thread.Sleep(1000);
window.ClickButton("btnPlus"); //perform calculation
Thread.Sleep(1000);
var result = window.GetTextBoxValue("tbResults"); //get result text
var expected = $"Calculation result> {firstNumber} + {secondNumber} = {firstNumber + secondNumber}\n"; //set expected results
Thread.Sleep(3000);
application.Close(); //close opened application
Assert.AreEqual(expected, result); //evaluate results
}
[TestMethod]
public void SuccessfulMinusCalculation()
{
var window = WindowExtension.GetAppWindow(out Application application, m_ApplicationPath, WINDOW_NAME); //get window
//test data
var firstNumber = -15;
var secondNumber = 2;
window.SetTextBox("tbFirstNumber", firstNumber.ToString()); //set first textBox value
Thread.Sleep(1000);
window.SetTextBox("tbSecondNumber", secondNumber.ToString()); //set second textBox value
Thread.Sleep(1000);
window.ClickButton("btnMinus"); //perform calculation
Thread.Sleep(1000);
var result = window.GetTextBoxValue("tbResults"); //get result text
var expected = $"Calculation result> {firstNumber} - {secondNumber} = {firstNumber - secondNumber}\n"; //set expected results
Thread.Sleep(3000);
application.Close(); //close opened application
Assert.AreEqual(expected, result); //evaluate results
}
[TestMethod]
public void SuccessfulMultiplyCalculation()
{
var window = WindowExtension.GetAppWindow(out Application application, m_ApplicationPath, WINDOW_NAME); //get window
//test data
var firstNumber = -15;
var secondNumber = 2;
window.SetTextBox("tbFirstNumber", firstNumber.ToString()); //set first textBox value
Thread.Sleep(1000);
window.SetTextBox("tbSecondNumber", secondNumber.ToString()); //set second textBox value
Thread.Sleep(1000);
window.ClickButton("btnMultiply"); //perform calculation
Thread.Sleep(1000);
var result = window.GetTextBoxValue("tbResults"); //get result text
var expected = $"Calculation result> {firstNumber} * {secondNumber} = {firstNumber * secondNumber}\n"; //set expected results
Thread.Sleep(3000);
application.Close(); //close opened application
Assert.AreEqual(expected, result); //evaluate results
}
[TestMethod]
public void SuccessfulDivideCalculation()
{
var window = WindowExtension.GetAppWindow(out Application application, m_ApplicationPath, WINDOW_NAME); //get window
//test data
var firstNumber = -15.0;
var secondNumber = 2.0;
window.SetTextBox("tbFirstNumber", firstNumber.ToString()); //set first textBox value
Thread.Sleep(1000);
window.SetTextBox("tbSecondNumber", secondNumber.ToString()); //set second textBox value
Thread.Sleep(1000);
window.ClickButton("btnDivide"); //perform calculation
Thread.Sleep(1000);
var result = window.GetTextBoxValue("tbResults"); //get result text
var expected = $"Calculation result> {firstNumber} / {secondNumber} = {firstNumber / secondNumber}\n"; //set expected results
Thread.Sleep(3000);
application.Close(); //close opened application
Assert.AreEqual(expected, result); //evaluate results
}
#endregion
#region exception
[TestMethod]
public void CantDivideByZero()
{
var window = WindowExtension.GetAppWindow(out Application application, m_ApplicationPath, WINDOW_NAME); //get window
//test data
var firstNumber = -15.0;
var secondNumber = 0;
window.SetTextBox("tbFirstNumber", firstNumber.ToString()); //set first textBox value
Thread.Sleep(1000);
window.SetTextBox("tbSecondNumber", secondNumber.ToString()); //set second textBox value
Thread.Sleep(1000);
window.ClickButton("btnDivide"); //perform calculation
Thread.Sleep(1000);
var messageBox = window.MessageBox("Can't perform divide operation"); //check message box with given caption
Assert.IsNotNull(messageBox); //check is message box was created
messageBox.Close(); //close message box
application.Close(); //close appliation
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace testMonogame
{
class UnlimitedBombs : ICommand
{
IPlayer player;
public UnlimitedBombs(IPlayer playerIn)
{
player = playerIn;
}
public void Execute()
{
player.Bombs = 10000;
}
}
}
|
using gView.Framework.Carto;
using gView.Framework.Data;
using System.Linq;
namespace gView.MxUtil.Lib
{
public class MapPersist : Map
{
public void SetDataset(int datasetId, IDataset dataset)
{
if (datasetId >= 0 && datasetId < _datasets.Count())
{
_datasets[datasetId] = dataset;
}
}
}
}
|
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Reflection;
namespace Pe.Stracon.SGC.Infraestructura.Core.Context
{
/// <summary>
/// Proveedor del contexto de base de datos
/// </summary>
/// <remarks>
/// Creación: GMD 22122014 <br />
/// Modificación: <br />
/// </remarks>
public class SGCDbContextProvider : DbContext, IDbContextProvider
{
/// <summary>
/// Establece la configuración de creación de la base de datos
/// </summary>
/// <param name="modelBuilder">contructor del modelo de base de datos</param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
this.MapEntitiesFromMappingConfigurations(modelBuilder);
}
/// <summary>
/// Permite inicializar el mapping de cada entidad
/// </summary>
/// <param name="modelBuilder">contructor del modelo de base de datos</param>
private void MapEntitiesFromMappingConfigurations(DbModelBuilder modelBuilder)
{
string assemblyName = ConfigurationManager.AppSettings["SGCModelAssembly"];
if (!string.IsNullOrEmpty(assemblyName))
{
Assembly assemblyModel = Assembly.Load(assemblyName);
List<Type> list = assemblyModel.GetTypes()
.Where(type =>
type.BaseType != null &&
type.BaseType.IsGenericType &&
type.BaseType.GetGenericTypeDefinition() == typeof(BaseEntityMapping<>))
.ToList<Type>();
list.ForEach(type =>
{
object obj = Activator.CreateInstance(type);
var methot = obj.GetType().GetMethod("ConfigureAuditMapping");
methot.Invoke(obj, new object[] { false });
modelBuilder.Configurations.Add((dynamic)obj);
});
}
}
/// <summary>
/// Indicador de carga perezosa
/// </summary>
public bool LazyLoadingEnabled
{
get { return this.Configuration.LazyLoadingEnabled; }
set { this.Configuration.LazyLoadingEnabled = value; }
}
/// <summary>
/// Inidicador de implementación de proxy
/// </summary>
public bool ProxyCreationEnabled
{
get { return this.Configuration.ProxyCreationEnabled; }
set { this.Configuration.ProxyCreationEnabled = value; }
}
/// <summary>
/// Cadena de conexión
/// </summary>
public string ConnectionString
{
get { return this.Database.Connection.ConnectionString; }
set { this.Database.Connection.ConnectionString = value; }
}
/// <summary>
/// Base de datos asociado al contexto
/// </summary>
public Database DataBase
{
get { return this.Database; }
}
/// <summary>
/// genera el DbSet de una entidad
/// </summary>
/// <typeparam name="T">entidad asociada</typeparam>
/// <returns>DbSet de la entidad asociada</returns>
public IDbSet<T> DbSet<T>() where T : CommandModel.Base.Entity
{
return this.Set<T>();
}
/// <summary>
/// Setea el estado de la entidad a modificado
/// </summary>
/// <typeparam name="T">Tipo entidad</typeparam>
/// <param name="entidad">Entidad</param>
/// <returns>Entidad modificada</returns>
public T Modified<T>(T entity) where T : CommandModel.Base.Entity
{
this.Entry(entity).State = System.Data.Entity.EntityState.Modified;
return entity;
}
/// <summary>
/// Persiste los cambios
/// </summary>
/// <returns>Registros afectados</returns>
public int Persist()
{
return this.SaveChanges();
}
/// <summary>
/// Ejecuta un store procedure del tipo consulta
/// </summary>
/// <typeparam name="T">Tipo de entidad de resultado</typeparam>
/// <param name="query">Nombre del store procedure</param>
/// <param name="parameters">Parametros</param>
/// <returns>Resultado</returns>
public IEnumerable<T> ExecuteStoreProcedure<T>(string query, params object[] parameters)
{
query = this.GenerateQueryString(query, parameters);
return this.Database.SqlQuery<T>(query, parameters);
}
/// <summary>
/// Ejecuta un store procedure del tipo escalar
/// </summary>
/// <param name="query">Nombre del store procedure</param>
/// <param name="parameters">Parametros</param>
/// <returns>Resultado</returns>
public T ExecuteStoreProcedureScalar<T>(string query, params object[] parameters)
{
T result = this.ExecuteStoreProcedure<T>(query, parameters).FirstOrDefault();
return result;
}
/// <summary>
/// Ejecuta un store procedure del tipo transacción
/// </summary>
/// <param name="query">Nombre del store procedure</param>
/// <param name="parameters">Parametros</param>
/// <returns>Resultado</returns>
public int ExecuteStoreProcedureNonQuery(string query, params object[] parameters)
{
query = this.GenerateQueryString(query, parameters);
return this.Database.ExecuteSqlCommand(query, parameters);
}
/// <summary>
/// Permite generar la sentencia a ejecutar
/// </summary>
/// <param name="query">nombre de store procedure</param>
/// <param name="parameters">parametros de entrada del store procedure</param>
/// <returns>Sentencia a ejecutar</returns>
private string GenerateQueryString(string query, params object[] parameters)
{
if (!query.Contains("@"))
{
for (var i = 0; i < parameters.Length; i++)
{
if (i == 0)
{
query += " @" + ((System.Data.SqlClient.SqlParameter)(parameters[i])).ParameterName;
}
else
{
query += ", @" + ((System.Data.SqlClient.SqlParameter)(parameters[i])).ParameterName;
}
}
}
return query;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TraceWizard.Entities;
using TraceWizard.Logging;
using TraceWizard.Logging.Adapters;
namespace TraceWizard.TwApp {
public partial class HourlyReportPanel : UserControl {
public Analysis Analysis;
public HourlyReportPanel() {
InitializeComponent();
}
public void Initialize() {
GeneralProperties.Analysis = Analysis;
GeneralProperties.Initialize();
HourlyTotalsDetail.Analysis = Analysis;
HourlyTotalsDetail.Initialize();
DailyTotalsDetail.Analysis = Analysis;
DailyTotalsDetail.Initialize();
LogMeter log = Analysis.Log as LogMeter;
if (log != null) {
LogPropertiesDetail.Log = log;
LogPropertiesDetail.Initialize();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Pokemon_Internal_Blades_CSharp
{
class Constants
{
/// <summary>
/// Defines all constants needed for entire program
/// </summary>
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// NONE should be used only when the program is asking for a second type and the pokemon does not technically have one.
/// </summary>
const int NONE = 0;
/// <summary>
/// Normal Type
/// Supereffective Against: N/A
/// Half Damage Dealt: Fighting
/// No Damage to: Ghost
/// No Damage from: Ghost
/// </summary>
const int NORMAL = 1;
/// <summary>
/// Fighting Type
/// Supereffective Against: Normal, Ice, Rock, Dark, Steel
/// Half Damage Dealt: Poison, Flying, Psychic, Bug
/// No Damage to: Ghost
/// No Damage from: N/A
/// </summary>
const int FIGHTING = 2;
/// <summary>
/// Fire Type
/// Supereffective Against: Grass, Ice, Steel, Bug
/// Half Damage Dealt: Fire, Water, Rock, Dragon
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int FIRE = 3;
/// <summary>
/// Water Type
/// Supereffective Against: Fire, Ground, Rock
/// Half Damage Dealt: Water, Grass, Dragon
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int WATER = 4;
/// <summary>
/// Ice Type
/// Supereffective Against: Grass, Flying, Ground, Dragon
/// Half Damage Dealt: Fire, Water, Ice, Steel
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int ICE = 5;
/// <summary>
/// Grass Type
/// Supereffective Against: Water, Ground, Rock
/// Half Damage Dealt: Fire, Grass, Poison, Flying, Bug, Dragon, Steel
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int GRASS = 6;
/// <summary>
/// Bug Type
/// Supereffective Against: Psychic, Dark, Grass
/// Half Damage Dealt: Fire, Fighting, Poison, Fighting, Ghost, Steel
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int BUG = 7;
/// <summary>
/// Poison Type
/// Supereffective Against: Grass
/// Half Damage Dealt: Poison, Ground, Rock, Ghost
/// No Damage to: Steel
/// No Damage from: N/A
/// </summary>
const int POISON = 8;
/// <summary>
/// Flying Type
/// Supereffective Against: Bug, Grass, Fighting
/// Half Damage Dealt: Electric, Rock, Steel
/// No Damage to: N/A
/// No Damage from: Ground
/// </summary>
const int FLYING = 9;
/// <summary>
/// Psychic Type
/// Supereffective Against: Fighting, Poison
/// Half Damage Dealt: Psychic, Steel
/// No Damage to: Dark
/// No Damage from: N/A
/// </summary>
const int PSYCHIC = 10;
/// <summary>
/// Ghost Type
/// Supereffective Against: Psychic, Ghost
/// Half Damage Dealt: Dark, Steel
/// No Damage to: Normal
/// No Damage from: Normal, Fighting
/// </summary>
const int GHOST = 11;
/// <summary>
/// Dark Type
/// Supereffective Against: Psychic, Ghost
/// Half Damage Dealt: Fighting, Dark, Steel
/// No Damage to: N/A
/// No Damage from: Psychic
/// </summary>
const int DARK = 12;
/// <summary>
/// Ground Type
/// Supereffective Against: Fire, Electric, Poison, Rock, Steel
/// Half Damage Dealt: Water, Grass, Ice
/// No Damage to: Flying
/// No Damage from: Electric
/// </summary>
const int GROUND = 13;
/// <summary>
/// Steel Type
/// Supereffective Against: Ice, Bug
/// Half Damage Dealt: Fire, Ice, Ground
/// No Damage to: N/A
/// No Damage from: Poison
/// </summary>
const int STEEL = 14;
/// <summary>
/// Rock Type
/// Supereffective Against: Fire, Ice, Flying, Bug
/// Half Damage Dealt: Fighting, Ground, Steel
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int ROCK = 15;
/// <summary>
/// Electric Type
/// Supereffective Against: Water, Flying
/// Half Damage Dealt: Electric, Grass, Dragon
/// No Damage to: Ground
/// No Damage from: N/A
/// </summary>
const int ELECTRIC = 16;
/// <summary>
/// Dragon Type
/// Supereffective Against: Dragon
/// Half Damage Dealt: Dragon, Ice
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int DRAGON = 17;
/// <summary>
/// Shadow Type
/// Supereffective Against: All but Shadow
/// Half Damage Dealt: Shadow
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int SHADOW = 18;
/// <summary>
/// ??? Type
/// Supereffective Against: N/A
/// Double Damage taken: N/A
/// Half Damage Dealt: N/A
/// No Damage to: N/A
/// No Damage from: N/A
/// </summary>
const int UNKNOWN = 19;
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Base MP of 5
/// </summary>
const int LOW_MP = 5;
/// <summary>
/// Base MP of 10
/// </summary>
const int LOW_MED_MP = 10;
/// <summary>
/// Base MP of 15
/// </summary>
const int MEDIUM_MP = 15;
/// <summary>
/// Base MP of 20
/// </summary>
const int MED_HIGH_MP = 20;
/// <summary>
/// Base MP of 30
/// </summary>
const int HIGH_MP = 30;
// ---------------------------------------------------------------------------------------------------------------------
// Nature Definitions
// Used to modify stats in Nature Class
/// <summary>
/// Increases the stat by 1.1
/// </summary>
const double INCREASE_STAT = 1.1;
/// <summary>
/// Normal Stat: 1.0
/// </summary>
const double NORMAL_STAT = 1.0;
/// <summary>
/// Decreases the stat by 0.9
/// </summary>
const double DECREASE_STAT = 0.9;
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// True
/// </summary>
const bool YES = true;
/// <summary>
/// False
/// </summary>
const bool NO = false;
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Blank Name Definition
/// Defines EMPTY as ""
/// </summary>
const string EMPTY = " ";
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Poisoned Effects: The Pokémon loses 1/8th Max HP each turn;
/// For every 4 steps the trainer takes, the Pokémon loses 1 HP until it reaches 1 HP remaining
/// </summary>
const int POISONED = 1;
/// <summary>
/// Paralysis Effects: The Pokémon afflicted's Speed stat is reduced to 25% of it's Maximum.
/// Pokémon with the Quick Feet ability are not affected by the Speed reduction
/// The Pokémon has a 25% chance of being unable to attack each turn
/// </summary>
const int PARALYZED = 2;
/// <summary>
/// Burned Effects: Each turn, the Pokémon afflicted with the Burn loses 1/8th of it's Max HP
/// The Pokémon's Physical Attack Stat is cut by Half. This effect does not work on Pokémon with the Guts ability
/// The Pokémon's Special Attack Stat is doubled on Pokémon with the Heat Rampage ability
/// </summary>
const int BURNED = 3;
/// <summary>
/// Frozen Effects: The Pokémon cannot use any attacks (apart from those that thaw it)
/// </summary>
const int FROZEN = 4;
/// <summary>
/// Sleeping Effects: The Pokémon cannot attack for 1 to 7 turns, the turn count is lowered with the Early Bird ability
/// Sleep Talk & Snore can be used
/// Allows the attacks Dream Eater & Nightmare as well as the ability Bad Dreams to be used against you
/// </summary>
const int SLEEPING = 5;
/// <summary>
/// Attracted Effects: The Pokémon afflicted cannot attack 50% of the time
/// </summary>
const int ATTRACTED = 6;
/// <summary>
/// Confusion Effects: The Pokémon afflicted cannot attack 50% of the time for 1-4 turns
/// Raises Evasion for Pokémon with the Tangled Feed ability
/// </summary>
const int CONFUSED = 7;
/// <summary>
/// Cursed Effects: The Pokémon afflicted loses 1/4 of it's Max HP each turn
/// </summary>
const int CURSED = 8;
/// <summary>
/// Badly Poisoned Effects: The Pokémon loses 1/16th Max HP for the first turn and then adds 1/16th to the amount to be lost
/// so on 2nd turn 2/16th, 3rd 3/16th and so on until the Pokémon faints
/// </summary>
const int BAD_POISON = 9;
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Gender Definition: Male
/// </summary>
const int MALE = 0;
/// <summary>
/// Gender Definition: Female
/// </summary>
const int FEMALE = 1;
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Default Trainer ID Definition
/// </summary>
const long DEFAULT_ID = 100000;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Newtonsoft.Json;
namespace AspNetCoreDemo.Provider
{
public class SessionStore : OAuthSPA.ITicketStore
{
//private StackExchange.Redis.ConnectionMultiplexer mul=StackExchange.Redis.ConnectionMultiplexer.Connect(;
//删除
public Task RemoveAsync(string key)
{
throw new NotImplementedException();
}
//更新
public Task RenewAsync(string key, AuthenticationTicket ticket)
{
throw new NotImplementedException();
}
//获取
public Task<AuthenticationTicket> RetrieveAsync(string key)
{
throw new NotImplementedException();
}
//保存
public Task<string> StoreAsync(AuthenticationTicket ticket)
{
throw new NotImplementedException();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftHandOrientationController : MonoBehaviour
{
public Transform leftHandTarget;
private Rotate rotate;
private float speed = 1.0f;
private float ang = 90.0f;
public bool ReOrient(string initialOrientation, string finalOrientation, float speed, float waitTime)
{
rotate = GameObject.Find("LeftArmTarget").GetComponent<Rotate>();
this.speed = speed;
Orient(initialOrientation);
StartCoroutine(Wait(waitTime));
Orient(finalOrientation);
return true;
}
IEnumerator Wait(float waitTime)
{
yield return new WaitForSeconds(waitTime);
}
private bool Orient(string ori)
{
switch (ori)
{
case "A": rotate_x(0.0f); rotate_y(0.0f); rotate_z(0.0f); return true;
case "B": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "C": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "D": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "E": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "F": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "G": rotate_x(-ang); rotate_y(-ang); rotate_z(0f); return true;
case "H": rotate_x(-ang); rotate_y(0f); rotate_z(0f); return true;
case "I": rotate_x(-ang); rotate_y(ang); rotate_z(0f); return true;
case "J": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "K": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
case "L": rotate_x(0f); rotate_y(0f); rotate_z(0f); return true;
default: return false;
}
}
void rotate_x(float angle)
{
rotate.RotateTarget(leftHandTarget, new float[] { angle, 0, 0 }, speed);
}
void rotate_y(float angle)
{
rotate.RotateTarget(leftHandTarget, new float[] { 0, angle, 0 }, speed);
}
void rotate_z(float angle)
{
rotate.RotateTarget(leftHandTarget, new float[] { 0, 0, angle }, speed);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Collections;
using System.Reflection;
using Microsoft.VisualBasic.CompilerServices;
using AC.ExtendedRenderer.Toolkit.Drawing;
namespace AC.StdControls.Toolkit.GridView
{
public class DataGridViewImageCellEmptyRow : DataGridViewImageCell
{
// Methods
public DataGridViewImageCellEmptyRow()
{
}
public DataGridViewImageCellEmptyRow(bool valueIsIcon)
: base(valueIsIcon)
{
}
// Properties
public override object DefaultNewRowValue
{
get
{
return DBNull.Value;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Generic;
namespace Vapoteur.Models
{
public class TestBox : Box
{
public string Nom { get; set; }
public string Test { get; set; }
}
} |
using System;
using System.Runtime;
using System.Text;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rwd.Framework.Extensions;
namespace Rwd.FrameworkTests.ExtensionsTests
{
/// <summary>
/// Summary description for DataTableExtensionTest
/// </summary>
[TestClass]
public class DataTableExtensionTest
{
public DataTableExtensionTest()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
SetEmployees();
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
_employees = null;
}
#endregion
private class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public string Phone { get; set; }
}
private List<Employee> _employees = null;
private List<Employee> SetEmployees()
{
_employees = new List<Employee>
{
new Employee {FirstName = "Ann", LastName = "Stevens", Title = "Manager", Phone = "6154543322"},
new Employee {FirstName = "Rick", LastName = "Adams", Title = "Developer", Phone = "6157443322"},
new Employee {FirstName = "Jenn",LastName = "Lawerence",Title = "Sales Associate", Phone = "6158113322"}
};
return _employees;
}
[TestMethod]
public void ToDataTableCanConvert()
{
try
{
var dt = _employees.ToDataTable();
}
catch (Exception ex)
{
Assert.Fail("Could not convert list to datatable");
}
}
[TestMethod]
public void HasRows()
{
var dt = _employees.ToDataTable();
if (dt.Rows.Count == 0)
{
Assert.Fail("Has no rows");
}
}
[TestMethod]
public void HasColumns()
{
var dt = _employees.ToDataTable();
if (dt.Columns.Count == 0)
{
Assert.Fail("Has no columns");
}
}
[TestMethod]
public void HasFirstNameColumn()
{
var dt = _employees.ToDataTable();
if (dt.Columns[0].ColumnName != "FirstName")
{
Assert.Fail("The first column is not FirstName");
}
}
[TestMethod]
public void FirstRecordOfFirstColumnHasValue()
{
var dt = _employees.ToDataTable();
var row = dt.Rows[0];
if (row["FirstName"].ToString() != "Ann")
{
Assert.Fail("The first column of the first row, doesn't contain the explected value.");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.EfStuff.Model.Energy
{
public class PersonalAccount : BaseModel
{
public string Number { get; set; }
public DateTime DateRegistration { get; set; }
public DateTime DateLastPayment { get; set; }
public long TariffId { get; set; }
public virtual Tariff Tariff { get; set; }
public long ElectricityMeterId { get; set; }
public virtual ElectricityMeter Meter { get; set; }
public long CitizenId { get; set; }
public virtual Citizen Citizen { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class GameDoor : MonoBehaviour {
public int waitTime;
public static bool zoomedIn = false;
public GameObject back;
void OnMouseDown ()
{
zoomIn ();
Instantiate (back);
}
void zoomIn ()
{
// Zoom Camera in
Vector3 pos;
pos.x = -2;
pos.y = 0;
pos.z = -2.5f;
GameObject player = GameObject.FindWithTag ("Player");
player.transform.position = pos;
zoomedIn = true;
}
}
|
using Business.Abstract;
using Entities.Concrete;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProducerController : Controller
{
IProducerService _producerService;
public ProducerController(IProducerService producerService)
{
_producerService = producerService;
}
[HttpGet("getall")]
public IActionResult GetAll()
{
var result = _producerService.GetAll();
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
[HttpGet("getbyid")]
public IActionResult GetById(int id)
{
var result = _producerService.GetById(id);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
//[HttpPatch("update")]
//public IActionResult UpdateProducer(int id,Producer producer)
//{
//}
//[HttpDelete("delete")]
//public IActionResult DeleteProducer(int id)
//{
// var result =_producerService.de
//}
}
}
|
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using ClosedXML.Excel;
using System.IO;
using Elmah;
using CreamBell_DMS_WebApps.App_Code;
namespace CreamBell_DMS_WebApps
{
public partial class CustomerPartyMaster : System.Web.UI.Page
{
CreamBell_DMS_WebApps.App_Code.Global baseObj = new CreamBell_DMS_WebApps.App_Code.Global();
SqlConnection conn = null;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USERID"] == null)
{
//Amol
Response.Redirect("Login.aspx");
return;
}
if (!IsPostBack)
{
baseObj.FillSaleHierarchy_Active();
fillHOS();
//RunningSite();
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
// DataView DtSaleHierarchy = (DataTable)HttpContext.Current.Session["SaleHierarchy"];
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
if (dt.Rows.Count > 0)
{
var dr_row = dt.AsEnumerable();
var test = (from r in dr_row
select r.Field<string>("SALEPOSITION")).First<string>();
//string dr1 = dt.Select("SALEPOSITION").ToString();
if (test == "VP")
{
chkListHOS.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
// chkAll_CheckedChanged(null, null);
}
else if (test == "GM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
// chkAll_CheckedChanged(null, null);
}
else if (test == "DGM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
//chkAll_CheckedChanged(null, null);
}
else if (test == "RM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
//chkAll_CheckedChanged(null, null);
}
else if (test == "ZM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkListRM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
CheckBox4.Enabled = false;
CheckBox4.Checked = true;
// chkAll_CheckedChanged(null, null);
}
else if (test == "ASM")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkListRM.Enabled = false;
chkListZM.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
CheckBox4.Enabled = false;
CheckBox4.Checked = true;
CheckBox5.Enabled = false;
CheckBox5.Checked = true;
// chkAll_CheckedChanged(null, null);
}
else if (test == "EXECUTIVE")
{
chkListHOS.Enabled = false;
chkListVP.Enabled = false;
chkListGM.Enabled = false;
chkListDGM.Enabled = false;
chkListRM.Enabled = false;
chkListZM.Enabled = false;
chkListEXECUTIVE.Enabled = false;
chkAll.Enabled = false;
chkAll.Checked = true;
CheckBox1.Enabled = false;
CheckBox1.Checked = true;
CheckBox2.Enabled = false;
CheckBox2.Checked = true;
CheckBox3.Enabled = false;
CheckBox3.Checked = true;
CheckBox4.Enabled = false;
CheckBox4.Checked = true;
CheckBox5.Enabled = false;
CheckBox5.Checked = true;
CheckBox6.Enabled = false;
CheckBox6.Checked = true;
// chkAll_CheckedChanged(null, null);
}
ddlCountry_SelectedIndexChanged(null, null);
}
}
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
//tclabel.Width = "90%";
Panel1.Visible = true;
}
else
{
//tclabel.Width = "100%";
Panel1.Visible = false;
}
if (Convert.ToString(Session["LOGINTYPE"]) == "0" && Convert.ToString(Session["ISDISTRIBUTOR"]) == "Y")
{
ShowCustomerMaster();
}
}
}
private void ShowCustomerMaster()
{
try
{
CreamBell_DMS_WebApps.App_Code.Global obj = new CreamBell_DMS_WebApps.App_Code.Global();
if (lstSiteId.SelectedValue == string.Empty)
{
gridViewCustomers.DataSource = null;
gridViewCustomers.DataBind();
ViewState["dtCustomer"] = null;
string message = "alert('Please Select The SiteID !');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
}
string siteid = "";
int count = 0;
foreach (System.Web.UI.WebControls.ListItem litem in lstSiteId.Items)
{
if (litem.Selected)
{
count += 1;
if (siteid.Length == 0)
siteid = "" + litem.Value.ToString() + "";
else
siteid += "," + litem.Value.ToString() + "";
}
}
if (count > 5)
{
// string message = "alert('Click On Export to Excel Only.If more than 5 Distributor Selected!');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Click On Export to Excel Only.If more than 5 Distributor Selected!');", true);
return;
}
string block = "";
if (rdRunningC.Checked == true)
{
block = "0";
}
else if (rdBlockC.Checked == true)
{
block = "1";
}
string query = "EXEC ACX_GETALLCUSTOMERDETAILS '" + siteid.ToString() + "','" + Session["DATAAREAID"].ToString() + "','" + block + "'";
List<SqlParameter> sqlParameters = new List<SqlParameter>();
SqlParameter siteCodeParam = new SqlParameter("@SiteID", SqlDbType.NVarChar, 5000);
siteCodeParam.Value = siteid.ToString();
sqlParameters.Add(siteCodeParam);
SqlParameter dataAreaIdParam = new SqlParameter("@DATAAREAID", SqlDbType.NVarChar, 4);
dataAreaIdParam.Value = Session["DATAAREAID"].ToString();
sqlParameters.Add(dataAreaIdParam);
SqlParameter blockParam = new SqlParameter("@BLOCK", SqlDbType.NVarChar, 10);
blockParam.Value = block;
sqlParameters.Add(blockParam);
DataTable dtCustomer = CreamBellFramework.GetDataFromStoredProcedure("ACX_GETALLCUSTOMERDETAILS", sqlParameters.ToArray());
//DataTable dtCustomer = obj.GetData(query);
if (dtCustomer.Rows.Count > 0)
{
gridViewCustomers.DataSource = dtCustomer;
//gridViewCustomers.Columns[0].Visible = false; //Column Index 1 for Customer Code
gridViewCustomers.DataBind();
ViewState["dtCustomer"] = dtCustomer;
gridViewCustomers.HeaderRow.TableSection = TableRowSection.TableHeader;
}
else
{
gridViewCustomers.Columns[1].Visible = false; //Column Index 1 for Customer Code
gridViewCustomers.DataBind();
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
private bool ValidateInput()
{
bool value = true;
if (lstSiteId.SelectedValue == string.Empty)
{
value = false;
string message = "alert('Please Select The SiteID !');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
}
return value;
}
protected void BtnShowReport_Click(object sender, EventArgs e)
{
try
{
gridViewCustomers.DataSource = null;
gridViewCustomers.DataBind();
bool b = ValidateInput();
if (b == true)
{
ShowCustomerMaster();
}
uppanel.Update();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void btnSearchCustomer_Click(object sender, EventArgs e)
{
try
{
if (txtSearch.Text == string.Empty)
{
this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please provide the Searching Keyword !');", true);
txtSearch.Focus();
gridViewCustomers.DataSource = ViewState["dtCustomer"];
gridViewCustomers.DataBind();
}
else
{
ShowCustomerByFilter();
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void fillSiteAndState(DataTable dt)
{
try
{
string sqlstr = "";
if (Convert.ToString(Session["ISDISTRIBUTOR"]) == "Y")
{
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
DataTable dtState = dt.DefaultView.ToTable(true, "STATE", "STATENAME");
dtState.Columns.Add("STATENAMES", typeof(string), "STATE + ' - ' + STATENAME");
lstState.Items.Clear();
DataRow dr = dtState.NewRow();
lstState.DataSource = dtState;
lstState.DataTextField = "STATENAMES";
lstState.DataValueField = "STATE";
lstState.DataBind();
}
else
{
sqlstr = "Select Distinct I.StateCode Code,I.StateCode + ' - ' + LS.Name AS Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' AND I.SITEID='" + Convert.ToString(Session["SiteCode"]) + "' order by Name";
//ddlState.Items.Add("Select...");
// baseObj.BindToDropDown(ddlState, sqlstr, "Name", "Code");
DataTable dt1 = baseObj.GetData(sqlstr);
lstState.DataSource = dt1;
lstState.DataTextField = "Name";
lstState.DataValueField = "Code";
lstState.DataBind();
}
}
else
{
sqlstr = "Select Distinct I.StateCode Code,I.StateCode + ' - ' + LS.Name AS Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' order by Name ";
lstState.Items.Add("Select...");
// baseObj.BindToDropDown(ddlState, sqlstr, "Name", "Code");
DataTable dt1 = baseObj.GetData(sqlstr);
lstState.DataSource = dt1;
lstState.DataTextField = "Name";
lstState.DataValueField = "Code";
lstState.DataBind();
}
if (lstState.Items.Count == 1)
{
foreach (System.Web.UI.WebControls.ListItem litem in lstState.Items)
{
litem.Selected = true;
}
ddlCountry_SelectedIndexChanged(null, null);
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string statesel = "";
foreach (System.Web.UI.WebControls.ListItem litem1 in lstState.Items)
{
if (litem1.Selected)
{
if (statesel.Length == 0)
statesel = "'" + litem1.Value.ToString() + "'";
else
statesel += ",'" + litem1.Value.ToString() + "'";
}
}
if (lstState.SelectedValue == string.Empty)
{
lstSiteId.Items.Clear();
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataView view = new DataView(dt);
DataTable distinctValues = view.ToTable(true, "Distributor", "DistributorName");
lstSiteId.DataSource = distinctValues;
string AllSitesFromHierarchy = "";
foreach (DataRow row in distinctValues.Rows)
{
if (AllSitesFromHierarchy == "")
{
AllSitesFromHierarchy += "'" + row["Distributor"].ToString() + "'";
}
else
{
AllSitesFromHierarchy += ",'" + row["Distributor"].ToString() + "'";
}
}
if (AllSitesFromHierarchy != "")
{
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID +' - '+ Name AS Name,Name as SiteName from [ax].[INVENTSITE] IV LEFT JOIN AX.ACXUSERMASTER UM on IV.SITEID = UM.SITE_CODE where SITEID IN (" + AllSitesFromHierarchy + ") Order by SiteName ";
dt = baseObj.GetData(sqlstr1);
lstSiteId.DataSource = dt;
lstSiteId.DataTextField = "Name";
lstSiteId.DataValueField = "Code";
lstSiteId.DataBind();
}
}
else
{
string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'";
object objcheckSitecode = baseObj.GetScalarValue(sqlstr);
if (objcheckSitecode != null)
{
lstSiteId.Items.Clear();
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID + ' - ' + NAME AS NAME,Name as SiteName from [ax].[INVENTSITE] IV JOIN AX.ACXUSERMASTER UM on IV.SITEID=UM.SITE_CODE where STATECODE in (" + statesel + ") Order by SiteName";
DataTable dt = baseObj.GetData(sqlstr1);
lstSiteId.DataSource = dt;
lstSiteId.DataTextField = "Name";
lstSiteId.DataValueField = "Code";
lstSiteId.DataBind();
}
else
{
lstSiteId.Items.Clear();
if (Convert.ToString(Session["LOGINTYPE"]) == "3")
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
dt.DefaultView.RowFilter = "STATE in (" + statesel + ")";
DataTable uniqueCols = dt.DefaultView.ToTable(true, "Distributor", "DistributorName");
string AllSitesFromHierarchy = "";
foreach (DataRow row in uniqueCols.Rows)
{
if (AllSitesFromHierarchy == "")
{
AllSitesFromHierarchy += "'" + row["Distributor"].ToString() + "'";
}
else
{
AllSitesFromHierarchy += ",'" + row["Distributor"].ToString() + "'";
}
}
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID +' - '+ Name AS Name,Name as SiteName from [ax].[INVENTSITE] IV LEFT JOIN AX.ACXUSERMASTER UM on IV.SITEID = UM.SITE_CODE where SITEID IN (" + AllSitesFromHierarchy + ") Order by SiteName ";
dt = baseObj.GetData(sqlstr1);
lstSiteId.DataSource = dt;
lstSiteId.DataTextField = "Name";
lstSiteId.DataValueField = "Code";
lstSiteId.DataBind();
}
else
{
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID + ' - ' + NAME AS NAME from [ax].[INVENTSITE] IV JOIN AX.ACXUSERMASTER UM on IV.SITEID=UM.SITE_CODE where SITEID = '" + Session["SiteCode"].ToString() + "'";
DataTable dt = baseObj.GetData(sqlstr1);
lstSiteId.DataSource = dt;
lstSiteId.DataTextField = "Name";
lstSiteId.DataValueField = "Code";
lstSiteId.DataBind();
}
}
}
if (lstSiteId.Items.Count == 1)
{
foreach (System.Web.UI.WebControls.ListItem litem in lstSiteId.Items)
{
litem.Selected = true;
}
}
Session["SalesData"] = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
RunningSite();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void fillHOS()
{
try
{
chkListHOS.Items.Clear();
DataTable dtHOS = (DataTable)Session["SaleHierarchy"];
DataTable uniqueCols = dtHOS.DefaultView.ToTable(true, "HOSNAME", "HOSCODE");
chkListHOS.DataSource = uniqueCols;
chkListHOS.DataTextField = "HOSNAME";
chkListHOS.DataValueField = "HOSCODE";
chkListHOS.DataBind();
if (uniqueCols.Rows.Count == 1)
{
chkListHOS.Items[0].Selected = true;
lstHOS_SelectedIndexChanged(null, null);
}
fillSiteAndState(dtHOS);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstHOS_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
chkListVP.Items.Clear();
chkListGM.Items.Clear();
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListHOS))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
//chkListVP.Items.Clear();
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "VPNAME", "VPCODE");
chkListVP.DataSource = uniqueCols2;
chkListVP.DataTextField = "VPNAME";
chkListVP.DataValueField = "VPCODE";
chkListVP.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListVP.Items[0].Selected = true;
lstVP_SelectedIndexChanged(null, null);
}
else
{
chkListVP.Items[0].Selected = false;
}
fillSiteAndState(dt);
uppanel.Update();
// chkListGM.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstVP_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
chkListGM.Items.Clear();
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListVP))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "GMNAME", "GMCODE");
chkListGM.DataSource = uniqueCols2;
chkListGM.DataTextField = "GMNAME";
chkListGM.DataValueField = "GMCODE";
chkListGM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListGM.Items[0].Selected = true;
lstGM_SelectedIndexChanged(null, null);
}
else
{
chkListGM.Items[0].Selected = false;
}
fillSiteAndState(dt);
uppanel.Update();
}
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstGM_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListGM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "DGMNAME", "DGMCODE");
chkListDGM.DataSource = uniqueCols2;
chkListDGM.DataTextField = "DGMNAME";
chkListDGM.DataValueField = "DGMCODE";
chkListDGM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListDGM.Items[0].Selected = true;
lstDGM_SelectedIndexChanged(null, null);
}
else
{
chkListDGM.Items[0].Selected = false;
}
fillSiteAndState(dt);
uppanel.Update();
}
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstDGM_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListDGM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "RMNAME", "RMCODE");
chkListRM.DataSource = uniqueCols2;
chkListRM.DataTextField = "RMNAME";
chkListRM.DataValueField = "RMCODE";
chkListRM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListRM.Items[0].Selected = true;
lstRM_SelectedIndexChanged(null, null);
}
else
{
chkListRM.Items[0].Selected = false;
}
fillSiteAndState(dt);
uppanel.Update();
}
ddlCountry_SelectedIndexChanged(null, null);
//upsale.Update()
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
public Boolean CheckSelect(ref CheckBoxList ChkList)
{
foreach (System.Web.UI.WebControls.ListItem litem in ChkList.Items)
{
if (litem.Selected)
{
return true;
}
}
return false;
}
protected void lstRM_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListRM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "ZMNAME", "ZMCODE");
chkListZM.DataSource = uniqueCols2;
chkListZM.DataTextField = "ZMNAME";
chkListZM.DataValueField = "ZMCODE";
chkListZM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListZM.Items[0].Selected = true;
lstZM_SelectedIndexChanged(null, null);
}
else
{
}
fillSiteAndState(dt);
uppanel.Update();
}
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstZM_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListZM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
chkListASM.Items.Clear();
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "ASMNAME", "ASMCODE");
chkListASM.DataSource = uniqueCols2;
chkListASM.DataTextField = "ASMNAME";
chkListASM.DataValueField = "ASMCODE";
chkListASM.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListASM.Items[0].Selected = true;
lstASM_SelectedIndexChanged(null, null);
}
fillSiteAndState(dt);
uppanel.Update();
}
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstASM_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
if (CheckSelect(ref chkListASM))
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
chkListEXECUTIVE.Items.Clear();
DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "EXECUTIVENAME", "EXECUTIVECODE");
chkListEXECUTIVE.DataSource = uniqueCols2;
chkListEXECUTIVE.DataTextField = "EXECUTIVENAME";
chkListEXECUTIVE.DataValueField = "EXECUTIVECODE";
chkListEXECUTIVE.DataBind();
if (uniqueCols2.Rows.Count == 1)
{
chkListEXECUTIVE.Items[0].Selected = true;
}
fillSiteAndState(dt);
uppanel.Update();
}
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void lstEXECUTIVE_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
fillSiteAndState(dt);
uppanel.Update();
ddlCountry_SelectedIndexChanged(null, null);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(chkAll, chkListHOS);
lstHOS_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(chkAll, chkListHOS);
chkListVP.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox1, chkListVP);
lstVP_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox1, chkListVP);
// chkListVP.Items.Clear();
chkListGM.Items.Clear();
//chkListRM.Items.Clear();
//chkListZM.Items.Clear();
//chkListASM.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox2, chkListGM);
lstGM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox2, chkListGM);
// chkListGM.Items.Clear();
chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox3, chkListDGM);
lstDGM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox3, chkListDGM);
//chkListGM.Items.Clear();
// chkListDGM.Items.Clear();
chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox4_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox4, chkListRM);
lstRM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox4, chkListRM);
//chkListGM.Items.Clear();
// chkListDGM.Items.Clear();
//chkListRM.Items.Clear();
chkListZM.Items.Clear();
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox5_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox5, chkListZM);
// chkListASM.Items.Clear();
lstZM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox5, chkListZM);
chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox6_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
CheckAll_CheckedChanged(CheckBox6, chkListASM);
// chkListASM.Items.Clear();
lstASM_SelectedIndexChanged(null, null);
}
else
{
CheckAll_CheckedChanged(CheckBox6, chkListASM);
//chkListASM.Items.Clear();
chkListEXECUTIVE.Items.Clear();
}
ddlCountry_SelectedIndexChanged(null, null);
}
protected void CheckBox7_CheckedChanged(object sender, EventArgs e)
{
CheckAll_CheckedChanged(CheckBox7, chkListEXECUTIVE);
ddlCountry_SelectedIndexChanged(null, null);
// chkListASM.DataSource = null;
}
protected void CheckAll_CheckedChanged(CheckBox CheckAll, CheckBoxList ChkList)
{
if (CheckAll.Checked == true)
{
for (int i = 0; i < ChkList.Items.Count; i++)
{
ChkList.Items[i].Selected = true;
}
}
else
{
for (int i = 0; i < ChkList.Items.Count; i++)
{
ChkList.Items[i].Selected = false;
}
}
}
private void ShowCustomerByFilter()
{
try
{
if (lstSiteId.SelectedValue == string.Empty)
{
string message = "alert('Please Select The SiteID !');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
return;
}
string siteid = "";
foreach (System.Web.UI.WebControls.ListItem litem in lstSiteId.Items)
{
if (litem.Selected)
{
if (siteid.Length == 0)
siteid = "'" + litem.Value.ToString() + "'";
else
siteid += ",'" + litem.Value.ToString() + "'";
}
}
CreamBell_DMS_WebApps.App_Code.Global obj = new CreamBell_DMS_WebApps.App_Code.Global();
//string query = " Select A.CHANNELGROUP AS CHANNELGROUPCODE,SS.DESCRIPTION AS CHANNELGROUPNAME,A.CHANNELTYPE AS CHANNELTYPECODE,SG.SUBSEGMENTDESCRIPTION AS CHANNELTYPENAME," +
// "Customer_Code,Customer_Name,A.PHONE_NO,A.EMAILID,A.Cust_Group,B.CUSTGROUP_NAME,A.Site_Code as DistributorCode,E.Name as DistributorName,Address1 as BILLTOADDRESS,City,A.ADDRESS2 AS SHIPTOADDRESS1,A.SHIPTOSTATE1,A.SHIPTOADDRESS2,A.SHIPTOSTATE2,A.GSTINNo,A.GSTREGISTRATIONDATE,CASE WHEN A.COMPOSITIONSCHEME =0 THEN 'NO' ELSE 'YES' END AS COMPOSITIONSCHEME,A.Area,A.District,ZipCode " +
// //" ,A.Scheme_Discount as CustomerType "+ //7th Apr 2017
// ",A.PAN,A.TAN,A.VAT,CASE A.BLOCKED WHEN 0 THEN 'NO' ELSE 'YES' END BLOCKED,CASE A.CARTOPERATOR WHEN 0 THEN 'NO' ELSE 'YES' END CARTOPERATOR,A.OUTLET_TYPE,A.CLOSING_DATE,CASE WHEN A.KEY_CUSTOMER=1 THEN 'YES' ELSE 'NO' END KEY_CUSTOMER," +
// "A.PAYMENT_MODE,A.PAYMENT_TERM,A.PRICEGROUP,A.PSR_DAY,A.REGISTER_DATE,case A.MONDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END MONDAY,case A.TUESDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END TUESDAY,case A.WEDNESDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END WEDNESDAY," +
// "CASE A.THURSDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END THURSDAY,CASE A.FRIDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END FRIDAY,CASE A.SATURDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END SATURDAY,CASE A.SUNDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END SUNDAY," +
// "A.VISITFREQUENCY,A.REPEATWEEK,A.SEQUENCENO,A.CST,A.AADHARNO," +
// " F.Name as State,A.PSR_CODE,isnull(C.PSR_NAME ,'') PSR_NAME, D.BeatCode, PSR_BEAT, Mobile_No, DEEP_FRIZER, ( D.BeatCode + '-'+ D.BeatName) as PSRBEATNAME,A.Register_Date,A.PriceGroup,A.Vat,A.Contact_Name " +
// " ,case applicableschemediscount when 0 then 'None' when 1 then 'Scheme' when 2 then 'Discount' when 3 then 'Both' end CustomerType" + // 7th Apr 2017
// " from [ax].[ACXCUSTMASTER] A LEFT OUTER JOIN [ax].[ACXPSRBeatMaster] D ON A.PSR_BEAT = D.BeatCode and A.PSR_CODE = D.PSRCode and A.Site_Code = D.Site_Code"+
// " left outer join [ax].[ACXCUSTGROUPMASTER] B on B.custgroup_code=A.Cust_Group "+
// " left outer join [ax].[ACXPSRMaster] C on C.PSR_Code=A.PSR_Code "+
// " LEFT OUTER JOIN [AX].[ACXSMMBUSRELSEGMENTGROUP] SS ON SS.SEGMENTID = A.CHANNELGROUP "+
// " LEFT OUTER JOIN [AX].[ACXSMMBUSRELSUBSEGMENTGROUP] SG ON SG.SUBSEGMENTID = A.CHANNELTYPE "+
// " left outer join [ax].[LOGISTICSADDRESSSTATE] F on F.Stateid=A.State " +
// " left Outer Join ax.inventsite E on E.Siteid=A.Site_Code" ;
string query = " SELECT A.SITE_CODE AS DISTRIBUTORCODE,A.CUSTOMER_CODE AS CUSTOMER_CODE,A.CUSTOMER_NAME,A.CONTACT_NAME,A.MOBILE_NO,A.PHONE_NO,A.EMAILID,A.ADDRESS1 as BILLTOADDRESS,A.CITY,F.NAME AS STATE,A.ZIPCODE," +
"A.AREA,A.ADDRESS2 AS SHIPTOADDRESS1,G.SHIPTOSTATE1,G.SHIPTOADDRESS2,G.SHIPTOSTATE2,A.GSTINNo," +
"CASE WHEN A.GSTREGISTRATIONDATE = '1900-01-01 00:00:00.000' THEN '' ELSE CONVERT(NVARCHAR(20), A.GSTREGISTRATIONDATE, 104) END GSTREGISTRATIONDATE," +
//" ,A.Scheme_Discount as CustomerType "+ //7th Apr 2017
"CASE WHEN A.COMPOSITIONSCHEME =0 THEN 'NO' ELSE 'YES' END AS COMPOSITIONSCHEME,A.PAN,A.TAN,A.VAT," +
"CASE A.BLOCKED WHEN 0 THEN 'NO' ELSE 'YES' END BLOCKED,CASE A.CARTOPERATOR WHEN 0 THEN 'NO' ELSE 'YES' END CARTOPERATOR," +
"A.OUTLET_TYPE,A.CHANNELTYPE AS CHANNELTYPECODE," +
"CASE WHEN A.CLOSING_DATE = '1900-01-01 00:00:00.000' THEN '' ELSE CONVERT(NVARCHAR(20), A.CLOSING_DATE, 104) END CLOSING_DATE," +
"A.DEEP_FRIZER,CASE WHEN A.KEY_CUSTOMER=1 THEN 'YES' ELSE 'NO' END KEY_CUSTOMER," +
"A.PAYMENT_MODE,A.PAYMENT_TERM,A.PRICEGROUP,A.PSR_BEAT,A.PSR_CODE,A.PSR_DAY," +
"CASE WHEN A.REGISTER_DATE = '1900-01-01 00:00:00.000' THEN '' ELSE CONVERT(NVARCHAR(20), A.REGISTER_DATE, 104) END REGISTER_DATE," +
"CASE A.APPLICABLESCHEMEDISCOUNT WHEN 0 THEN 'NONE' WHEN 1 THEN 'SCHEME' WHEN 2 THEN 'DISCOUNT' WHEN 3 THEN 'BOTH' END CUSTOMERTYPE ," +
"A.CUST_GROUP,A.CHANNELGROUP AS CHANNELGROUPCODE,A.CHANNELTYPE AS CHANNEL_TYPE,A.AADHARNO,case A.MONDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END MONDAY," + // 7th Apr 2017
"case A.TUESDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END TUESDAY,case A.WEDNESDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END WEDNESDAY," +
"CASE A.THURSDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END THURSDAY,CASE A.FRIDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END FRIDAY," +
"CASE A.SATURDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END SATURDAY,CASE A.SUNDAY WHEN 0 THEN 'NO' WHEN 1 THEN ' YES' END SUNDAY," +
"A.VISITFREQUENCY,A.REPEATWEEK,A.SEQUENCENO,A.CST,SG.SUBSEGMENTDESCRIPTION AS CHANNELTYPENAME,A.DISTRICT,B.CUSTGROUP_NAME,SS.DESCRIPTION AS CHANNELGROUPNAME," +
"E.NAME AS DISTRIBUTORNAME,ISNULL(C.PSR_NAME ,'') PSR_NAME,( D.BEATCODE + '-'+ D.BEATNAME) AS PSRBEATNAME,D.BEATCODE" +
" FROM [AX].[ACXCUSTMASTER] A LEFT OUTER JOIN [AX].[ACXSMMBUSRELSEGMENTGROUP] SS ON SS.SEGMENTID=A.CHANNELGROUP" +
" LEFT OUTER JOIN [AX].[ACXSMMBUSRELSUBSEGMENTGROUP] SG ON SG.SUBSEGMENTID=A.CHANNELTYPE" +
" LEFT OUTER JOIN [AX].[ACXPSRBEATMASTER] D ON A.PSR_BEAT = D.BEATCODE AND A.PSR_CODE = D.PSRCODE AND A.SITE_CODE = D.SITE_CODE " +
" LEFT OUTER JOIN [AX].[ACXCUSTGROUPMASTER] B ON B.CUSTGROUP_CODE=A.CUST_GROUP " +
" LEFT OUTER JOIN [AX].[ACXCUSTMASTER] G ON G.SITE_CODE=A.SITE_CODE AND G.CUSTOMER_CODE=A.CUSTOMER_CODE " +
" LEFT OUTER JOIN [AX].[ACXPSRMASTER] C ON C.PSR_CODE=A.PSR_CODE" +
" LEFT OUTER JOIN AX.INVENTSITE E ON E.SITEID=A.SITE_CODE" +
" LEFT OUTER JOIN [AX].[LOGISTICSADDRESSSTATE] F ON F.STATEID=A.STATE";
if (rdRunningC.Checked == true)
{
if (DDLSearchType.Text == "Customer Code")
{
query = query + " where A.Customer_Code = '" + txtSearch.Text.Trim().ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED=0 ";
}
if (DDLSearchType.Text == "Customer Name")
{
query = query + " where A.Customer_Name Like '" + txtSearch.Text.Trim().ToString() + "%' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED=0 ";
}
if (DDLSearchType.Text == "PSR Code")
{
query = query + " where A.PSR_CODE = '" + txtSearch.Text.Trim().ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED=0 ";
}
}
else if (rdBlockC.Checked == true)
{
if (DDLSearchType.Text == "Customer Code")
{
query = query + " where A.Customer_Code = '" + txtSearch.Text.Trim().ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED=1 ";
}
if (DDLSearchType.Text == "Customer Name")
{
query = query + " where A.Customer_Name Like '" + txtSearch.Text.Trim().ToString() + "%' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED=1 ";
}
if (DDLSearchType.Text == "PSR Code")
{
query = query + " where A.PSR_CODE = '" + txtSearch.Text.Trim().ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED=1 ";
}
}
else
{
if (DDLSearchType.Text == "Customer Code")
{
query = query + " where A.Customer_Code = '" + txtSearch.Text.Trim().ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED in ('1','0') ";
}
if (DDLSearchType.Text == "Customer Name")
{
query = query + " where A.Customer_Name Like '" + txtSearch.Text.Trim().ToString() + "%' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED in ('1','0') ";
}
if (DDLSearchType.Text == "PSR Code")
{
query = query + " where A.PSR_CODE = '" + txtSearch.Text.Trim().ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and A.SITE_CODE in (" + siteid.ToString() + ") and A.CartOperator =0 and A.BLOCKED in ('1','0') ";
}
}
DataTable dtSearchRecord = obj.GetData(query);
if (dtSearchRecord.Rows.Count > 0)
{
ViewState["dtCustomer"] = dtSearchRecord;
gridViewCustomers.DataSource = dtSearchRecord;
//gridViewCustomers.Columns[1].Visible = false; //Column Index 1 for Customer Code
gridViewCustomers.DataBind();
}
else
{
this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('No Record Found !');", true);
gridViewCustomers.DataSource = ViewState["dtCustomer"];
//gridViewCustomers.Columns[1].Visible = false; //Column Index 1 for Customer Code
gridViewCustomers.DataBind();
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void gridViewCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex == 0)
e.Row.Style.Add("height", "50px");
}
//if (e.Row.RowType == DataControlRowType.DataRow)
//{
// LinkButton LB;
// String CustId = e.Row.Cells[1].Text; //for Customer ID value access//
// LB = (LinkButton)e.Row.FindControl("LnkView");
// //LB.Attributes.Add("onclick", "window.location.href = 'frmUserProfile.aspx?"; return false;");
//}
}
protected void LnkView_Click(object sender, EventArgs e)
{
string CustID = (sender as LinkButton).CommandArgument;
// Response.Redirect("frmCustomerPartyMasterNew.aspx?CustID=" + CustID);
Response.Redirect(String.Format("frmCustomerPartyMasterNew.aspx?CustID={0}&ID={1}", CustID, "CustParty"));
}
protected void gridViewCustomers_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridViewCustomers.PageIndex = e.NewPageIndex;
ShowCustomerMaster();
}
private void PrepareForExport(Control ctrl)
{
//iterate through all the grid controls
foreach (Control childControl in ctrl.Controls)
{
//if the control type is link button, remove it
//from the collection
if (childControl.GetType() == typeof(LinkButton))
{
ctrl.Controls.Remove(childControl);
}
//if the child control is not empty, repeat the process
// for all its controls
else if (childControl.HasControls())
{
PrepareForExport(childControl);
}
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void ExportToExcel()
{
try
{
Response.Clear();
Response.AddHeader("content-disposition",
"attachment;filename=CustomerPartyMaster.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(stringWriter);
gridViewCustomers.RenderControl(HtmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void btnExport2Excel_Click(object sender, EventArgs e)
{
ExportToExcelNew();
}
private void ShowData_ForExcel()
{
CreamBell_DMS_WebApps.App_Code.Global obj = new CreamBell_DMS_WebApps.App_Code.Global();
string FilterQuery = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
string query = string.Empty;
try
{
conn = new SqlConnection(obj.GetConnectionString());
conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["dtCustomer"];
string attachment = "attachment; filename=CustomerPartyMaster.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
finally
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
}
}
}
}
private void ExportToExcelNew()
{
try
{
//if (string.IsNullOrEmpty(rdbListExcelFileFormat.SelectedValue))
//{
// rdbListExcelFileFormat.SelectedValue = "XLSB";
//}
if (!ucRadioButtonList.GetXLS.Checked &&
!ucRadioButtonList.GetXLSX.Checked &&
!ucRadioButtonList.GetXLSB.Checked)
{
ucRadioButtonList.GetXLSB.Checked = true;
}
bool b = ValidateInput();
if (b == true)
{
//GridView gvvc = new GridView();
//CreamBell_DMS_WebApps.App_Code.Global obj = new CreamBell_DMS_WebApps.App_Code.Global();
if (lstSiteId.SelectedValue == string.Empty)
{
string message = "alert('Please Select The SiteID !');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
}
string siteid = "";
foreach (System.Web.UI.WebControls.ListItem litem in lstSiteId.Items)
{
if (litem.Selected)
{
if (siteid.Length == 0)
siteid = "" + litem.Value.ToString() + "";
else
siteid += "," + litem.Value.ToString() + "";
}
}
string block = "";
if (rdRunningC.Checked == true)
{
block = "0";
}
else if (rdBlockC.Checked == true)
{
block = "1";
}
string query = "EXEC ACX_GETALLCUSTOMERDETAILS '" + siteid.ToString() + "','" + Session["DATAAREAID"].ToString() + "','" + block + "'";
List<SqlParameter> sqlParameters = new List<SqlParameter>();
SqlParameter siteCodeParam = new SqlParameter("@SiteID", SqlDbType.NVarChar, 5000);
siteCodeParam.Value = siteid.ToString();
sqlParameters.Add(siteCodeParam);
SqlParameter dataAreaIdParam = new SqlParameter("@DATAAREAID", SqlDbType.NVarChar, 4);
dataAreaIdParam.Value = Session["DATAAREAID"].ToString();
sqlParameters.Add(dataAreaIdParam);
SqlParameter blockParam = new SqlParameter("@BLOCK", SqlDbType.NVarChar, 10);
blockParam.Value = block;
sqlParameters.Add(blockParam);
DataTable dtCustomer = CreamBellFramework.GetDataFromStoredProcedure("ACX_GETALLCUSTOMERDETAILS", sqlParameters.ToArray());
//using (SqlCommand cmd = new SqlCommand(query))
//{
// using (SqlDataAdapter sda = new SqlDataAdapter())
// {
// cmd.Connection = obj.GetConnection();
// sda.SelectCommand = cmd;
// using (DataTable dt = new DataTable())
// {
// sda.Fill(dt);
if (dtCustomer.Rows.Count > 0)
{
ExcelExport excelExport = new ExcelExport();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
//if ("XLSX".CompareTo(rdbListExcelFileFormat.SelectedValue) == 0)
if (ucRadioButtonList.GetXLSX.Checked)
{
excelExport.ExportXLSX(Response, dtCustomer, "Customers", "CustomerPartyMaster");
}
//if ("XLS".CompareTo(rdbListExcelFileFormat.SelectedValue) == 0)
if (ucRadioButtonList.GetXLS.Checked)
{
excelExport.ExportXLS(Response, dtCustomer, "Customers", "CustomerPartyMaster");
}
//if ("XLSB".CompareTo(rdbListExcelFileFormat.SelectedValue) == 0)
if (ucRadioButtonList.GetXLSB.Checked)
{
string tempXlsbFilePath = string.Empty;
foreach (var file in Directory.GetFiles(Server.MapPath("xlfiles")))
{
try
{
File.Delete(file);
}
catch { }
}
var tempFile = DateTime.Now.Ticks.ToString();
tempXlsbFilePath = Server.MapPath("xlfiles/tempXlsxFile_" + tempFile + ".xlsb");
excelExport.ExportXLSB(Response, dtCustomer, "Customers", "CustomerPartyMaster", tempXlsbFilePath);
}
Response.Flush();
Response.End();
}
//using (XLWorkbook wb = new XLWorkbook())
//{
// wb.Worksheets.Add(dt, "Customers");
// Response.Clear();
// Response.Buffer = true;
// Response.Charset = "";
// Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Response.AddHeader("content-disposition", "attachment;filename=CustomerPartyMaster.xlsx");
// using (MemoryStream MyMemoryStream = new MemoryStream())
// {
// wb.SaveAs(MyMemoryStream);
// MyMemoryStream.WriteTo(Response.OutputStream);
// Response.Flush();
// Response.End();
// }
//}
// }
// }
//}
//DataTable dtCustomer = obj.GetData(query);
//if (dtCustomer.Rows.Count > 0)
//{
// gvvc.DataSource = dtCustomer;
// gvvc.DataBind();
//}
//else
//{
// gvvc.DataSource = null;
// gvvc.DataBind();
//}
//if (gvvc.Rows.Count > 0)
//{
// string sFileName = "CustomerPartyMaster.xls";
//
// sFileName = sFileName.Replace("/", "");
// // SEND OUTPUT TO THE CLIENT MACHINE USING "RESPONSE OBJECT".
// Response.ClearContent();
// Response.Buffer = true;
// Response.AddHeader("content-disposition", "attachment; filename=" + sFileName);
// Response.ContentType = "application/vnd.ms-excel";
// EnableViewState = false;
//
// System.IO.StringWriter objSW = new System.IO.StringWriter();
// System.Web.UI.HtmlTextWriter objHTW = new System.Web.UI.HtmlTextWriter(objSW);
//
// foreach (DataRow row in dtCustomer.Rows)
// {
//
// row.Cells[0].CssClass = "textmode";
// }
//
// foreach (GridViewRow row in gvvc.Rows)
// {
// row.Cells[0].CssClass = "textmode";
// }
// gvvc.RenderControl(objHTW);
//
// string style = @"<style> .textmode { mso-number-format:\@; } </style>";
// Response.Write(style);
// Response.Output.Write(objSW.ToString());
// Response.Flush();
// Response.End();
//}
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void RunningSite()
{
try
{
string statesel = "";
foreach (System.Web.UI.WebControls.ListItem litem1 in lstState.Items)
{
if (litem1.Selected)
{
if (statesel.Length == 0)
statesel = "'" + litem1.Value.ToString() + "'";
else
statesel += ",'" + litem1.Value.ToString() + "'";
}
}
if (lstState.SelectedValue == string.Empty)
{
lstSiteId.Items.Clear();
DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE);
DataView view = new DataView(dt);
DataTable distinctValues = view.ToTable(true, "Distributor", "DistributorName");
lstSiteId.DataSource = distinctValues;
string AllSitesFromHierarchy = "";
foreach (DataRow row in distinctValues.Rows)
{
if (AllSitesFromHierarchy == "")
{
AllSitesFromHierarchy += "'" + row["Distributor"].ToString() + "'";
}
else
{
AllSitesFromHierarchy += ",'" + row["Distributor"].ToString() + "'";
}
}
if (AllSitesFromHierarchy != "")
{
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID +' - '+ Name AS Name,Name as SiteName from [ax].[INVENTSITE] IV LEFT JOIN AX.ACXUSERMASTER UM on IV.SITEID = UM.SITE_CODE where SITEID IN (" + AllSitesFromHierarchy + ") Order by SiteName ";
dt = baseObj.GetData(sqlstr1);
lstSiteId.DataSource = dt;
lstSiteId.DataTextField = "Name";
lstSiteId.DataValueField = "Code";
lstSiteId.DataBind();
}
}
else
{
string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'";
object objcheckSitecode = baseObj.GetScalarValue(sqlstr);
if (objcheckSitecode != null)
{
lstSiteId.Items.Clear();
string sqlstr1 = @"Select Distinct SITEID as Code,SITEID + ' - ' + NAME AS NAME,Name as SiteName from [ax].[INVENTSITE] IV JOIN AX.ACXUSERMASTER UM on IV.SITEID=UM.SITE_CODE where UM.DEACTIVATIONDATE='1900-01-01 00:00:00.000' AND STATECODE in (" + statesel + ") Order by SiteName";
DataTable dt = baseObj.GetData(sqlstr1);
lstSiteId.DataSource = dt;
lstSiteId.DataTextField = "Name";
lstSiteId.DataValueField = "Code";
lstSiteId.DataBind();
}
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void rdRunningC_CheckedChanged(object sender, EventArgs e)
{
// RunningSite();
}
}
} |
public interface IId
{
int Id {get;set;}
} |
/*
Description Script:
Name:
Date:
Upgrade:
*/
using UnityEngine;
using System.Collections;
using System;
public class BulletDefaultBehaviour : Bullet
{
/// <summary>
///
/// </summary>
void Update()
{
//Movimenta o objeto
move();
//verifica onde o objeto está para desliga-lo
checkEnds();
}
/// <summary>
/// verifica se a posição da bala está fora do quadro da tela
/// </summary>
public override void checkEnds()
{
if (transform.position.y < CameraManager.instance.bottomDown || transform.position.y > CameraManager.instance.bottomUp ||
transform.position.x > CameraManager.instance.bottomRight || transform.position.x < CameraManager.instance.bottomLeft)
{
//desliga o objeto se ele estive fora da Screen do Usuario
gameObject.SetActive(false);
}
}
/// <summary>
/// Movimenta da Bala
/// </summary>
public override void move()
{
//Movimenta o objeto sempre em Y positivo
transform.Translate(new Vector3(velocity.x, velocity.y * Time.deltaTime));
}
/// <summary>
/// Metodo que contem implementação unica
/// </summary>
public override void bulletSpecial()
{
throw new NotImplementedException();
}
/// <summary>
/// Metodo de uma coroutine se for necessario para usar
/// </summary>
/// <returns></returns>
public override IEnumerator bulletCoroutine()
{
throw new NotImplementedException();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.