text
stringlengths
13
6.01M
using System; namespace Data.Utils.QueryBuilder.SearchRules { public class WhereSearchRule : ISearchRule { private Func<string, object> _action; public string Field { get; set; } public string Statement { get; set; } public Func<string, object> Action { get { return _action ?? (x=>x); } set { _action = value; } } } }
using System.Collections.Generic; namespace Alabo.UI.Design.AutoReports { public interface IAutoReport { /// <summary> /// 报表类型 /// </summary> /// <param name="query"></param> /// <returns></returns> List<AutoReport> ResultList(object query, AutoBaseModel autoModel); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Win32 { public class DeviceInterface { private DeviceInformationSet DeviceInfoSet; private SP_DEVICE_INTERFACE_DATA InterfaceData; public DeviceInterface(DeviceInformationSet deviceInfoSet, SP_DEVICE_INTERFACE_DATA interfaceData) { DeviceInfoSet = deviceInfoSet; InterfaceData = interfaceData; } public Guid InterfaceClassGuid => InterfaceData.interfaceClassGuid; public int Flags => InterfaceData.flags; public string Path => SetupDi.GetDevicePath(DeviceInfoSet.HDevInfo, InterfaceData); } }
using Microsoft.WindowsAzure.Storage.Blob; namespace TryHardForum.Services { public interface IUploadService { // Тут полный треш, и потому я буду просто писать код. CloudBlobContainer GetBlobContainer(string connectionString); } }
using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace PingoSnake { class TextureManager { private IDictionary<string, Texture2D> Textures; public TextureManager() { this.Textures = new Dictionary<string, Texture2D>(); } public void AddTexture(string name, string newName = null) { string textureName = newName != null ? newName : name; if (Textures.ContainsKey(textureName)) { Trace.WriteLine($"WARNING: Trying to load texture: {name}, when it is already loaded!"); return; } Texture2D newTexture = GameState.Instance.GetContent().Load<Texture2D>(name); this.Textures.Add(textureName, newTexture); } public Texture2D GetTexture(string name) { return this.Textures[name]; } } }
using System; public class Class1 { public Class1() { } } { constructor(GPACs) { this.rawGPACs = GPACs; console.log(this.rawGPACs); } getGPA() { var credit = 0; var total = 0; for (var count = 0; count < this.rawGPACs.length; count++) { if (this.rawGPACs[count].getScore() != 0) { credit += parseFloat(this.rawGPACs[count].getCredit());//Import Credit total += this.rawGPACs[count].getGPA();//Adds all the raw GPA } } this.gpaFinal = (total / credit).toFixed(2); return this.gpaFinal; } getRank() { if (this.gpaFinal <= 3) { this.rank = " Try harder!"; } else if (this.gpaFinal >= 3) { this.rank = " Sweet!"; } else { this.rank = "Error!"; } return this.rank; } } export class Unit { constructor(name, credit, type) { this.rawName = name; this.rawCredit = credit; this.rawIdentifier = type; this.rawScore = 0; this.convertType(this.rawIdentifier); this.rawLevel = "S"; this.NLIBList = [0, 2.6, 3.0, 3.3, 3.6, 3.9, 4.2, 4.5]; this.NLAPList = [0, 2.6, 3.0, 3.3, 3.6, 3.9, 4.2, 4.5]; //Credits for Language AP IN ORDER this.NLHPLUSList = [0, 2.25, 2.65, 2.95, 3.25, 3.55, 3.85, 4.15]; //Credits for Language S+ IN ORDER this.NLHList = [0, 2.4, 2.8, 3.1, 3.4, 3.7, 4.0, 4.3]; //Credits for NonLanguage H IN ORDER this.NLSPLUSList = [0, 2.25, 2.65, 2.95, 3.25, 3.55, 3.85, 4.15]; //Credits for NonLanguage S+ IN ORDER this.NLSList = [0, 2.1, 2.5, 2.8, 3.1, 3.4, 3.7, 4.0]; //Credits for NonLanguage S IN ORDER this.LAPList = [0, 2.6, 3.0, 3.3, 3.6, 3.9, 4.2, 4.5]; //Credits for Language AP IN ORDER this.LHPLUSList = [0, 2.5, 2.9, 3.2, 3.5, 3.8, 4.1, 4.4]; //Credits for Language H+ IN ORDER this.LHList = [0, 2.4, 2.8, 3.1, 3.4, 3.7, 4.0, 4.3]; //Credits for Language H IN ORDER this.LSPLUSList = [0, 2.2, 2.6, 2.9, 3.2, 3.5, 3.8, 4.1]; //Credits for Language S+ IN ORDER this.LSList = [0, 2.1, 2.5, 2.8, 3.1, 3.4, 3.7, 4.0]; //Credits for Language S IN ORDER } convertType(type) { if (this.rawIdentifier == 0) { //0 is Non-Language, 1 is Language this.rawType = false; this.rawTypename = "Non-Language"; } else { this.rawType = true; this.rawTypename = "Language"; } } setCredit(credit) { this.rawCredit = credit; } setType(type) { this.rawType = type; } setScore(score) { this.rawScore = score; } setLevel(level) { this.rawLevel = level; } getLevel() { return this.rawLevel; } getScore() { return this.rawScore; } getCredit() { return this.rawCredit; } getType() { return this.rawType; } //Data Importation Function getGPA() { if (this.rawType == true) { //false is non-language, true is language return this.rawCredit * this.getL(); } else { return this.rawCredit * this.getNL(); } } //Subject Categorization Function getNL() { //console.log(Level); if (this.rawLevel == "AP") { return this.calGPA(this.NLAPList) } if (this.rawLevel == "H+") { return this.calGPA(this.NLHPLUSList) } if (this.rawLevel == "H") { return this.calGPA(this.NLHList) } if (this.rawLevel == "S+") { return this.calGPA(this.NLSPLUSList) } if (this.rawLevel == "S") { return this.calGPA(this.NLSList) } } getL() { //console.log(Level); if (this.rawLevel == "AP") { return this.calGPA(this.LAPList) } if (this.rawLevel == "H+") { return this.calGPA(this.LHPLUSList) } if (this.rawLevel == "H") { return this.calGPA(this.LHList) } if (this.rawLevel == "S+") { return this.calGPA(this.LSPLUSList) } if (this.rawLevel == "S") { return this.calGPA(this.LSList) } } calGPA(list) { //console.log(list); //console.log(listname); //console.log(this.data.[listname]) //console.log("AP",Score) if (this.rawScore <= 59) this.gpa = list[0]; if (this.rawScore > 59 && this.rawScore <= 67) this.gpa = list[1]; if (this.rawScore > 67 && this.rawScore <= 72) this.gpa = list[2]; if (this.rawScore > 72 && this.rawScore <= 77) this.gpa = list[3]; if (this.rawScore > 77 && this.rawScore <= 82) this.gpa = list[4]; if (this.rawScore > 82 && this.rawScore <= 87) this.gpa = list[5]; if (this.rawScore > 87 && this.rawScore <= 92) this.gpa = list[6]; if (this.rawScore > 92 && this.rawScore <= 100) this.gpa = list[7]; //console.log(gpa) return this.gpa; } toString() { return ("Subject Name: " + this.rawName + " Subject Credit: " + this.rawCredit + " Subject Type: " + this.rawTypename + " Subject Score: " + this.rawScore + " Subject Level: " + this.rawLevel); } }
using PopulationFitness.Models.FastMaths; using PopulationFitness.Models.Genes.BitSet; using System; namespace PopulationFitness.Models.Genes.Valley { public class TridGenes : NormalizingBitSetGenes { private class MinCalculator : IValueCalculator<double> { public double CalculateValue(long index) { double min = (0.0 - index) * (index + 4.0) * (index + 1.0); return min / 6; } } private class MaxCalculator : IValueCalculator<double> { public double CalculateValue(long index) { /* M= left [{n} over {2} right ] {( {n} ^ {2} +1)} ^ {2} + left (n- left [{n} over {2} right ] right ) {( {n} ^ {2} -1)} ^ {2} + left (n-1 right ) {n} ^ {4} */ double nOver2 = Math.Round(((double)index) / 2.0); long nSquared = index * index; return nOver2 * FastMaths.FastMaths.Pow(nSquared + 1, 2) + (index - nOver2) * FastMaths.FastMaths.Pow(nSquared - 1, 2) + (index - 1) * nSquared * nSquared; } } private static readonly ExpensiveCalculatedValues<double> CachedMinValues = new ExpensiveCalculatedValues<double>(new MinCalculator()); private static readonly ExpensiveCalculatedValues<double> CachedMaxValues = new ExpensiveCalculatedValues<double>(new MaxCalculator()); private double min; public TridGenes(Config config) : base(config, 0.0) { } /** * Calculates the interpolation values and the normalization values * @param n * @return */ protected override double CalculateNormalizationRatio(int n) { min = CachedMinValues.FindOrCalculate(n); double max = CachedMaxValues.FindOrCalculate(n); CalculateInterpolationRatio(n); return max - min; } private void CalculateInterpolationRatio(int n) { /* {- {n} ^ {2} ≤x} rsub {i} ≤+ {n} ^ {2} */ _interpolationRatio = (1.0 * n * n) / MaxLongForSizeOfGene; } protected override double CalculateFitnessFromIntegers(long[] integer_values) { /* https://www.sfu.ca/~ssurjano/trid.html f left (x right ) = sum from {i=1} to {n} {{left ({x} rsub {i} -1 right )} ^ {2} -} sum from {i=2} to {n} {{x} rsub {i} {x} rsub {i-1}} */ double fitness = 0.0 - min; if (integer_values.Length > 0) { double previousX = Interpolate(integer_values[0]); double firstSum = FastMaths.FastMaths.Pow(previousX - 1, 2); double secondSum = 0; for (int i = 1; i < integer_values.Length; i++) { double x = Interpolate(integer_values[i]); firstSum += (x - 1) * (x - 1); secondSum += x * previousX; previousX = x; } fitness += (firstSum - secondSum); } return fitness; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace OCRGet { public partial class FormHelp : Form { public RichTextBox richText { get; } public FormHelp() { InitializeComponent(); richText = richTextBox1; } private void FormHelp_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { Close(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using eTicaretProjesi.ENT; using System.Threading.Tasks; using eTicaretProjesi.ENT.ViewModel; using eTicaretProjesi.BL.AccountRepository; using eTicaretProjesi.ENT.IdentityModel; using eTicaretProjesi.BL.Settings; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; namespace eTicaretProjesi.Controllers { public class HesapController : Controller { // GET: Hesap public ActionResult Uyelik() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Uyelik(RegisterViewModel model) { if (!ModelState.IsValid) return View(model); var userManager = MemberShipTools.NewUserManager(); var checkUser = userManager.FindByName(model.KullaniciAd); if (checkUser != null) { ModelState.AddModelError(string.Empty, "Bu kullanıcı zaten kayıtlı!"); return View(model); } checkUser = userManager.FindByEmail(model.Email); if (checkUser != null) { ModelState.AddModelError(string.Empty, "Bu eposta adresi kullanılmakta"); return View(model); } // register işlemi yapılır var activationCode = Guid.NewGuid().ToString(); AppUser user = new AppUser() { Ad = model.Ad, Soyad = model.Soyad, Email = model.Email, UserName = model.KullaniciAd, ActivationCode = activationCode }; var response = userManager.Create(user, model.Sifre); if (response.Succeeded) { string siteUrl = Request.Url.Scheme + Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); if (userManager.Users.Count() == 1) { userManager.AddToRole(user.Id, "Admin"); await SiteSettings.SendMail(new MailViewModel { Kime = user.Email, Konu = "Hoşgeldin Sahip", Mesaj = "Sitemizi yöneteceğin için çok mutluyuz ^^" }); } else { userManager.AddToRole(user.Id, "Passive"); await SiteSettings.SendMail(new MailViewModel { Kime = user.Email, Konu = "Personel Yönetimi - Aktivasyon", Mesaj = $"Merhaba {user.Ad} {user.Soyad} <br/>Hesabınızı aktifleştirmek için <a href='{siteUrl}/Hesap/Activation?code={activationCode}'>Aktivasyon Kodu : {activationCode}</a>" }); } return RedirectToAction("Login", "Hesap"); } else { ModelState.AddModelError(string.Empty, "Kayıt İşleminde bir hata oluştu"); return View(model); } } public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model) { if (!ModelState.IsValid) return View(model); var userManager = MemberShipTools.NewUserManager(); var user = await userManager.FindAsync(model.KullaniciAd, model.Sifre); if (user == null) { ModelState.AddModelError(string.Empty, "Böyle bir kullanıcı bulunamadı"); return View(model); } var authManager = HttpContext.GetOwinContext().Authentication; var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); authManager.SignIn(new AuthenticationProperties { IsPersistent = true }, userIdentity); return RedirectToAction("Index", "Home"); } [Authorize] public ActionResult Logout() { var authManager = HttpContext.GetOwinContext().Authentication; authManager.SignOut(); return RedirectToAction("Login", "Hesap"); } public async Task<ActionResult> Activation(string code) { var userStore = MemberShipTools.NewUserStore(); var userManager = new UserManager<AppUser>(userStore); var sonuc = userStore.Context.Set<AppUser>().FirstOrDefault(x => x.ActivationCode == code); if (sonuc == null) { ViewBag.sonuc = "Aktivasyon işlemi başarısız"; return View(); } sonuc.EmailConfirmed = true; await userStore.UpdateAsync(sonuc); await userStore.Context.SaveChangesAsync(); userManager.RemoveFromRole(sonuc.Id, "Passive"); userManager.AddToRole(sonuc.Id, "User"); ViewBag.sonuc = $"Merhaba {sonuc.Ad} {sonuc.Soyad} <br/> Aktivasyon işleminiz başarılı"; await SiteSettings.SendMail(new MailViewModel() { Kime = sonuc.Email, Mesaj = ViewBag.sonuc.ToString(), Konu = "Aktivasyon", Bcc = "cvtaydn53@gmail.com" }); return View(); } public ActionResult RecoverPassword() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RecoverPassword(string email) { var userStore = MemberShipTools.NewUserStore(); var userManager = new UserManager<AppUser>(userStore); var sonuc = userStore.Context.Set<AppUser>().FirstOrDefault(x => x.Email == email); if (sonuc == null) { ViewBag.sonuc = "E mail adresiniz sisteme kayıtlı değil"; return View(); } var randomPass = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6); await userStore.SetPasswordHashAsync(sonuc, userManager.PasswordHasher.HashPassword(randomPass)); await userStore.UpdateAsync(sonuc); await userStore.Context.SaveChangesAsync(); await SiteSettings.SendMail(new MailViewModel() { Kime = sonuc.Email, Konu = "Şifreniz Değişti", Mesaj = $"Merhaba {sonuc.Ad} {sonuc.Soyad} <br/>Yeni Şifreniz : <b>{randomPass}</b>" }); ViewBag.sonuc = "Email adresinize yeni şifreniz gönderilmiştir"; return View(); } [Authorize] public ActionResult Profil() { var userManager = MemberShipTools.NewUserManager(); var user = userManager.FindById(HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId()); var model = new ProfilePasswordViewModel() { ProfileModel = new ProfileViewModel { Id = user.Id, Email = user.Email, Ad = user.Ad, Soyad = user.Soyad, KullaniciAd = user.UserName } }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Profil(ProfilePasswordViewModel model) { if (!ModelState.IsValid) return View(model); try { var userStore = MemberShipTools.NewUserStore(); var userManager = new UserManager<AppUser>(userStore); var user = userManager.FindById(model.ProfileModel.Id); user.Ad = model.ProfileModel.Ad; user.Soyad = model.ProfileModel.Soyad; if (user.Email != model.ProfileModel.Email) { user.Email = model.ProfileModel.Email; if (HttpContext.User.IsInRole("Admin")) { userManager.RemoveFromRole(user.Id, "Admin"); } else if (HttpContext.User.IsInRole("User")) { userManager.RemoveFromRole(user.Id, "User"); } userManager.AddToRole(user.Id, "Passive"); user.ActivationCode = Guid.NewGuid().ToString().Replace("-", ""); string siteUrl = Request.Url.Scheme + Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); await SiteSettings.SendMail(new MailViewModel { Kime = user.Email, Konu = "Personel Yönetimi - Aktivasyon", Mesaj = $"Merhaba {user.Ad} {user.Soyad} <br/>Email adresinizi <b>değiştirdiğiniz</b> için hesabınızı tekrar aktif etmelisiniz. <a href='{siteUrl}/Hesap/Activation?code={user.ActivationCode}'>Aktivasyon Kodu</a>" }); } await userStore.UpdateAsync(user); await userStore.Context.SaveChangesAsync(); var model1 = new ProfilePasswordViewModel() { ProfileModel = new ProfileViewModel { Id = user.Id, Email = user.Email, Ad = user.Ad, Soyad = user.Soyad, KullaniciAd = user.UserName } }; ViewBag.sonuc = "Bilgileriniz güncelleşmiştir"; return View(model1); } catch (Exception ex) { ViewBag.sonuc = ex.Message; return View(model); } } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> UpdatePassword(ProfilePasswordViewModel model) { if (model.PasswordModel.YeniSifre != model.PasswordModel.SifreTekrar) { ModelState.AddModelError(string.Empty, "Şifreler uyuşmuyor"); return View("Profil", model); } try { var userStore = MemberShipTools.NewUserStore(); var userManager = new UserManager<AppUser>(userStore); var user = userManager.FindById(model.ProfileModel.Id); user = userManager.Find(user.UserName, model.PasswordModel.EskiSifre); if (user == null) { ModelState.AddModelError(string.Empty, "Mevcut şifreniz yanlış girilmiştir"); return View("Profil", model); } await userStore.SetPasswordHashAsync(user, userManager.PasswordHasher.HashPassword(model.PasswordModel.YeniSifre)); await userStore.UpdateAsync(user); await userStore.Context.SaveChangesAsync(); HttpContext.GetOwinContext().Authentication.SignOut(); return RedirectToAction("Profil"); } catch (Exception ex) { ViewBag.sonuc = "Güncelleşme işleminde bir hata oluştu. " + ex.Message; return View("Profil", model); } } } }
namespace AzureAI.CallCenterTalksAnalysis.FunctionApps.Utils { internal static class FunctionNamesRepository { public const string FileAnalysisOrchestratorFunc = "func-file-analysis-orchestrator"; public const string TextFileAnalyzerFunc = "func-text-file-analyzer"; public const string AudioVideoFileAnalyzerFunc = "func-audio-video-file-analyzer"; public const string AnalysisResultAggregatorFunc = "func-analysis-result-aggregator"; } }
 using Anywhere2Go.DataAccess.Object; using ClaimDi.DataAccess; using ClaimDi.DataAccess.Entity; using log4net; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClaimDi.Business.Master { public class MappingCarTaskBikeLogic { private static readonly ILog logger = LogManager.GetLogger(typeof(MappingCarTaskBikeLogic)); private MyContext _context = null; private string _language = string.Empty; public MappingCarTaskBikeLogic(string language = "th") { _context = new MyContext(); _language = language; } public MappingCarTaskBikeLogic(MyContext context) { _context = context; } public MappingCarTaskBike GetMappingCarTaskBike(Guid accId, string taskId) { var req = new Repository<MappingCarTaskBike>(_context); var dataCarTaskBike = req.GetQuery().Where(t => t.AccId == accId && t.TaskId == taskId).FirstOrDefault(); return dataCarTaskBike; } public List<MappingCarTaskBike> GetMappingCarTaskBikes(Guid accId) { var req = new Repository<MappingCarTaskBike>(_context); var dataCarTaskBikes = req.GetQuery().Where(t => t.AccId == accId && t.CarInfo.IsActive.Value).OrderBy(o => o.CreateDate).ToList(); return dataCarTaskBikes; } public bool IsDuplicateMappingCarTaskBike(Guid accId, string taskId) { bool response = false; var req = new Repository<MappingCarTaskBike>(_context); var qrCodeTaskLog = req.GetQuery().Where(t => t.AccId == accId && t.TaskId == taskId && t.CarInfo.IsActive.Value).Count(); if (qrCodeTaskLog > 0) { response = true; } return response; } public BaseResult<bool> SaveMappingCarTaskBike(MappingCarTaskBike obj) { BaseResult<bool> res = new BaseResult<bool>(); try { var req = new Repository<MappingCarTaskBike>(_context); obj.CreateDate = DateTime.Now; obj.CreateBy = "system"; req.Add(obj); req.SaveChanges(); res.Result = true; } catch (Exception ex) { res.Message = ex.Message; logger.Error(string.Format("Method = {0}", "SaveMappingCarTaskBike"), ex); } return res; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //********************************************************************** // // 文件名称(File Name):LoadNodeListRequest.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-04-21 14:36:27 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-04-21 14:36:27 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Model.request { public class LoadNodeListRequest:PageRequestBase { private int _nodeid = -1; private int _noderunstatus = -1; private int _listencommandqueuestatus=-1; private int _createby = -1; private string _nodecreatetimerange="1900-01-01/2099-12-30"; private int _alarmtype = -1; /// <summary> /// 节点编号 /// </summary> public int NodeId { get{return _nodeid;} set{_nodeid=value;} } /// <summary> /// 节点运行状态 /// </summary> public int NodeRunStatus { get{return _noderunstatus;} set{_noderunstatus=value;} } /// <summary> /// 监听命令队列状态 /// </summary> public int ListenCommandQueueStatus { get{return _listencommandqueuestatus;} set{_listencommandqueuestatus=value;} } /// <summary> /// 节点创建时间范围 /// </summary> public string NodeCreateTimeRange{ get{return _nodecreatetimerange;} set{_nodecreatetimerange=value;} } /// <summary> /// 创建人 /// </summary> public int CreateBy { get { return _createby; } set { _createby = value; } } /// <summary> /// 报警类型 /// </summary> public int AlarmType { get { return _alarmtype; } set { _alarmtype = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using Serialization.Mappers; namespace Serialization.Providers { public class FixedLengthProvider : ISerializationProvider { public TextMapping Mapping { get; set; } public FixedLengthProvider(TextMapping mapping) { Mapping = mapping; } public object[] BreakIntoPieces(string origin) { string remaining = origin; ArrayList objects = new ArrayList(); int i = 0; while (!string.IsNullOrEmpty(remaining) && i < Mapping.MappedClass.Mappings.Length) { int length = Mapping.MappedClass.Mappings[i++].Length; objects.Add(remaining.Substring(0, length)); remaining = remaining.Substring(length); } return objects.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TRPO_labe_3.Utilities { public enum FigureType { OrangeRicky, BlueRicky, Cleveland, RhodeIsland, Hero, Teewee, Smashboy } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class Animal : MonoBehaviour { NavMeshAgent m_NavMeshAgent; int m_CurrentPatrolPositionId = -1; public List<Transform> m_PatrolPositions; public Transform quad; public GameObject patrolPositionsGameObject; public List<Sprite> Anim; int numSpriteAnim; float countAnim; float timerAnim = 0.3f; Material m_Material; int children; private void Awake() { } void Start() { m_Material = quad.GetComponent<Renderer>().material; children = patrolPositionsGameObject.transform.childCount; for (int i = 0; i < children; i++) m_PatrolPositions.Add(patrolPositionsGameObject.transform.GetChild(i)); m_NavMeshAgent = this.gameObject.GetComponent<NavMeshAgent>(); m_CurrentPatrolPositionId = Random.Range(0, m_PatrolPositions.Count - 1); m_NavMeshAgent.isStopped = false; m_NavMeshAgent.SetDestination(m_PatrolPositions[m_CurrentPatrolPositionId].position); } void Update() { quad.LookAt(PlayerManager._Instance.transform.position); quad.eulerAngles = new Vector3(0, quad.transform.eulerAngles.y + 180, 0); if (!m_NavMeshAgent.hasPath && m_NavMeshAgent.pathStatus == NavMeshPathStatus.PathComplete) MoveToNextPatrolPosition(); if (Anim.Count != 0) { countAnim += Time.deltaTime; if (countAnim >= timerAnim) { numSpriteAnim++; if (numSpriteAnim >= Anim.Count) { numSpriteAnim = 0; } m_Material.mainTexture = Anim[numSpriteAnim].texture; countAnim = 0; } } } void MoveToNextPatrolPosition() { m_CurrentPatrolPositionId = Random.Range(1, m_PatrolPositions.Count - 1); if (m_CurrentPatrolPositionId >= m_PatrolPositions.Count) m_CurrentPatrolPositionId = 0; m_NavMeshAgent.SetDestination(m_PatrolPositions[m_CurrentPatrolPositionId].position); } }
using System; namespace GamePracticeArray { public static class HelperIO { public static char ReturnDirectionCharacter() { bool isCharOK = false; char inputChar; do { Console.WriteLine("Please enter command"); var input = Console.ReadLine().ToLower(); inputChar = input[0]; if (inputChar == 'w' || inputChar == 's' || inputChar == 'a' || inputChar == 'd') { isCharOK = true; } else { Console.WriteLine("Please enter W, S, A or D."); } } while (!isCharOK); return inputChar; } public static void PrintDirection() { Console.WriteLine("Press W do move UP\nPress S do move DOWN\nPress A to move LEFT\nPress D to move RIGHT\nAfter entering letter press ENTER\n"); } public static void PrintBorderEnd() { Console.WriteLine("You have reach the edge of table, move on some other side."); } } }
using System.IO; using SFA.DAS.CommitmentsV2.Api.Types.Requests; namespace SFA.DAS.ProviderCommitments.Web.Models.Apprentice { public class DownloadViewModel { public string Name { get; set; } public string ContentType => "application/octet-stream"; public GetApprenticeshipsRequest Request { get; set; } public Stream Content { get; set; } } }
using EasyWebApp.API.Commons; using EasyWebApp.API.Extensions; using EasyWebApp.API.Services.CustomerDbConnStrManagerSrv; using EasyWebApp.Data.DbContext; using EasyWebApp.Data.DbContextProvider; using EasyWebApp.Data.Entities.SystemEntities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EasyWebApp.API.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class TableColumnSchemaController : ControllerBase { private readonly ICustomerDbConnStrManagerSrv _customerDbConnStrManagerSrv; private readonly IDbContextProvider _provider; public TableColumnSchemaController(ICustomerDbConnStrManagerSrv customerDbConnStrManagerSrv, IDbContextProvider dbContextProvider) { this._customerDbConnStrManagerSrv = customerDbConnStrManagerSrv; this._provider = dbContextProvider; } private async Task<CustomerDbContext> GetDbContext(string dbGuid) { var userGuid = User.GetId(); var dbConnInfo = await _customerDbConnStrManagerSrv.GetCustomerDbInfoByGuid(dbGuid, userGuid); return _provider.GetApplicationDbContext(dbConnInfo.BuildConnStr().ToString(), dbConnInfo.DbType); } [HttpGet("GetAllTableColumnConfig")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task<ActionResult<IEnumerable<SystemTableColumnConfig>>> GetAllTableConfig(string dbGuid) { var context = await GetDbContext(dbGuid); var results = await context.SystemTableColumnConfigs.ToListAsync(); return Ok(results); } [HttpGet("GetTableColumnConfigById")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task<ActionResult<SystemTableColumnConfig>> GetTableColumnConfigById(string dbGuid, int configId) { var context = await GetDbContext(dbGuid); var result = await context.SystemTableColumnConfigs.FirstOrDefaultAsync(t => t.Id == configId); if (result == null) { return CheckData<SystemTableColumnConfig>.ItemNotFound(configId); } return Ok(result); } [HttpGet("GetColumnConfigByTableId")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task<ActionResult<IEnumerable<SystemTableColumnConfig>>> GetTableColumnConfigByTableId(string dbGuid, int tableId) { var context = await GetDbContext(dbGuid); var results = await context.SystemTableColumnConfigs.Where(t => t.TableId == tableId).ToListAsync(); if (results == null) { return CheckData<SystemTableColumnConfig>.ItemNotFound(tableId); } return Ok(results); } [HttpPut("UpdateTableColumnConfig")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task<ActionResult<SystemTableColumnConfig>> UpdateTableColumnConfig(string dbGuid, SystemTableColumnConfig updatedConfig) { var context = await GetDbContext(dbGuid); var results = await context.SystemTableColumnConfigs.FirstOrDefaultAsync(t => t.Id == updatedConfig.Id); if (results == null) { return CheckData<SystemTableColumnConfig>.ItemNotFound(updatedConfig.Id); } results.ExplicitName = updatedConfig.ExplicitName; results.ExplicitDataType = updatedConfig.ExplicitDataType; results.DisplayComponent = updatedConfig.DisplayComponent; results.IsHidden = updatedConfig.IsHidden; results.ModifiedDate = DateTime.UtcNow; await context.SaveChangesAsync(); return results; } } }
using DAL; using BL; using MVVM_Core; namespace Main.ViewModels { public class ResultViewModel : BasePageViewModel { private readonly DeclarationService declarationService; public string Message { get; set; } public ResultViewModel(PageService pageservice, DeclarationService declarationService) : base(pageservice) { this.declarationService = declarationService; init(); } async void init() { bool edit = declarationService.IsEdit; bool res = await declarationService.ApplyDeclaration(); if (declarationService.IsPadied) { Message = "Оплата прошла успешно!"; } else if (edit) { Message = "Заявление успешно редактировано!"; } else { Message = "Заявление успешно оформлено!"; } if(!res) { Message = "Произошла ошибка!"; } pageservice.ClearHistoryByPool(PoolIndex); declarationService.Clear(); } protected override void Next(object param) { pageservice.ChangePage<Pages.SearchAutoPage>(PoolIndex, DisappearAndToSlideAnim.ToRight); } public override int PoolIndex => Rules.Pages.MainPool; } }
using System; using System.Collections.Generic; using Android.Runtime; namespace RU.Tinkoff.Core.Nfc.Util { // Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.core.nfc.util']/class[@name='PdolUtils']" [global::Android.Runtime.Register ("ru/tinkoff/core/nfc/util/PdolUtils", DoNotGenerateAcw=true)] public partial class PdolUtils : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.core.nfc.util']/class[@name='PdolUtils.RecvTag']" [global::Android.Runtime.Register ("ru/tinkoff/core/nfc/util/PdolUtils$RecvTag", DoNotGenerateAcw=true)] public partial class RecvTag : global::Java.Lang.Object { internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("ru/tinkoff/core/nfc/util/PdolUtils$RecvTag", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (RecvTag); } } protected RecvTag (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_arrayBI; // Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.core.nfc.util']/class[@name='PdolUtils.RecvTag']/constructor[@name='PdolUtils.RecvTag' and count(parameter)=2 and parameter[1][@type='byte[]'] and parameter[2][@type='int']]" [Register (".ctor", "([BI)V", "")] public unsafe RecvTag (byte[] p0, int p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewArray (p0); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); if (((object) this).GetType () != typeof (RecvTag)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "([BI)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "([BI)V", __args); return; } if (id_ctor_arrayBI == IntPtr.Zero) id_ctor_arrayBI = JNIEnv.GetMethodID (class_ref, "<init>", "([BI)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_arrayBI, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_arrayBI, __args); } finally { if (p0 != null) { JNIEnv.CopyArray (native_p0, p0); JNIEnv.DeleteLocalRef (native_p0); } } } static IntPtr id_ctor_arrayBIarrayB; // Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.core.nfc.util']/class[@name='PdolUtils.RecvTag']/constructor[@name='PdolUtils.RecvTag' and count(parameter)=3 and parameter[1][@type='byte[]'] and parameter[2][@type='int'] and parameter[3][@type='byte[]']]" [Register (".ctor", "([BI[B)V", "")] public unsafe RecvTag (byte[] p0, int p1, byte[] p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native_p0 = JNIEnv.NewArray (p0); IntPtr native_p2 = JNIEnv.NewArray (p2); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); __args [2] = new JValue (native_p2); if (((object) this).GetType () != typeof (RecvTag)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "([BI[B)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "([BI[B)V", __args); return; } if (id_ctor_arrayBIarrayB == IntPtr.Zero) id_ctor_arrayBIarrayB = JNIEnv.GetMethodID (class_ref, "<init>", "([BI[B)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_arrayBIarrayB, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_arrayBIarrayB, __args); } finally { if (p0 != null) { JNIEnv.CopyArray (native_p0, p0); JNIEnv.DeleteLocalRef (native_p0); } if (p2 != null) { JNIEnv.CopyArray (native_p2, p2); JNIEnv.DeleteLocalRef (native_p2); } } } } internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("ru/tinkoff/core/nfc/util/PdolUtils", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (PdolUtils); } } protected PdolUtils (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.core.nfc.util']/class[@name='PdolUtils']/constructor[@name='PdolUtils' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe PdolUtils () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { if (((object) this).GetType () != typeof (PdolUtils)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor); } finally { } } static IntPtr id_parsePDoL_arrayB; // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.nfc.util']/class[@name='PdolUtils']/method[@name='parsePDoL' and count(parameter)=1 and parameter[1][@type='byte[]']]" [Register ("parsePDoL", "([B)[B", "")] public static unsafe byte[] ParsePDoL (byte[] p0) { if (id_parsePDoL_arrayB == IntPtr.Zero) id_parsePDoL_arrayB = JNIEnv.GetStaticMethodID (class_ref, "parsePDoL", "([B)[B"); IntPtr native_p0 = JNIEnv.NewArray (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); byte[] __ret = (byte[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_parsePDoL_arrayB, __args), JniHandleOwnership.TransferLocalRef, typeof (byte)); return __ret; } finally { if (p0 != null) { JNIEnv.CopyArray (native_p0, p0); JNIEnv.DeleteLocalRef (native_p0); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; using AngleSharp.Parser.Html; namespace RegeditS { class InBlank { private List<Sprava> sprava = new List<Sprava>(); public Agent[] start(string[] okpo) { return inBlank(okpo); } private Agent[] inBlank(string[] okpo) { // Создаём экземпляр класса Agent[] agent = new Agent[okpo.Length]; // Создаём экземпляр класса Connect conn = new Connect(); // Создаём экземпляр класса var parser = new HtmlParser(); // Создаём экземпляр класса HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); for (int x = 0; x < agent.Length; x++) { // получаем страницу реестра string html = conn.connRestr(okpo[x]); // закидуем в парсер var document = parser.Parse(html); doc.LoadHtml(html); // парсим var date = doc.DocumentNode.SelectNodes("//td[contains(@class, 'RegDate tr')]"); var type = doc.DocumentNode.SelectNodes("//td[contains(@class, 'CSType tr')]"); var number = doc.DocumentNode.SelectNodes("//td[contains(@class, 'CaseNumber tr')]"); var href = doc.DocumentNode.SelectNodes("//a[@class='doc_text2']"); //Создаем обект в массиве agent[x] = new Agent(); // Вносим ОКПО agent[x].OKPO = okpo[x]; //Инецелизируем бланк с заданой длиной. agent[x].Ublank(href.Count); //заполняем бланк for (int i =0; i< href.Count; i++) { //Создаем обект в массиве agent[x].Blank[i] = new Blank(); string s = date[i].InnerText; s = s.Replace(" ", ""); s = s.Replace("\r", ""); s = s.Replace("\n", ""); agent[x].Blank[i].Data = s; s = type[i].InnerText; s = s.Replace(" ", ""); s = s.Replace("\r", ""); s = s.Replace("\n", ""); agent[x].Blank[i].Type = s; s = number[i].InnerText; s = s.Replace(" ", ""); s = s.Replace("\r", ""); s = s.Replace("\n", ""); agent[x].Blank[i].Number = s; agent[x].Blank[i].Href = href[i].Attributes["href"].Value; // Поиск судембых дел. ParsSprav pars = new ParsSprav(); if(agent[x].Blank[i].Type == "Господарське") // Добавляем дела в лист (если оно "Господарське") sprava.Add(pars.parsGospodar(agent[x].Blank[i].Href)); // agent[x].Blank[i].Href = href[i].GetAttribute("href"); } // Добавляем в массив полученый результат agent[x].Sprava = sprava.ToArray<Sprava>(); } return agent; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.Storage; using GUI.Models; using System.Collections.ObjectModel; namespace GUI.Views { public sealed partial class SettingsPage : Page { private ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; public ObservableCollection<string> HomePageList => App.HomePageList; public SettingsPage() { this.InitializeComponent(); } private void settingIrpBrokerLocationTextBox_Changed(object sender, RoutedEventArgs e) { var location = settingIrpBrokerLocationTextBox.Text.ToLower(); if (IsValidLocationFormat(location)) { localSettings.Values["IrpBrokerLocation"] = location; settingIrpBrokerLocationTextBox.BorderBrush = new SolidColorBrush(Windows.UI.Colors.Green); } else { settingIrpBrokerLocationTextBox.BorderBrush = new SolidColorBrush(Windows.UI.Colors.Red); } } private bool IsValidLocationFormat(string location) { try { var uri = new Uri(location); if (uri.Scheme != "tcp") return false; if (uri.Port < 0) return false; } catch(Exception) { return false; } return true; } private void settingBrokerPollDelay_Changed(object sender, RoutedEventArgs e) { try { var val = Convert.ToDouble(settingBrokerPollDelay.Text.ToString()); localSettings.Values[IrpDumper.IrpDumperPollDelayKey] = val; } catch { // fallback to default localSettings.Values[IrpDumper.IrpDumperPollDelayKey] = IrpDumper.IrpDumperDefaultProbeValue; } } private void settingHomePage_Changed(object sender, RoutedEventArgs e) { localSettings.Values["HomePage"] = settingHomePage.SelectedIndex; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foundry.SourceControl { public interface IChange { ChangeType Type { get; } ISourceFile File { get; } ISourceFile OldFile { get; } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace ZavenDotNetInterview.Abstract.Logic { public interface ILogic<TEntity> where TEntity : class { TEntity Get(Guid id); IEnumerable<TEntity> GetAll(); Guid Add(TEntity entity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.FVS { public class AndonPrdtLine { public int NodeID { get; set; } public string NodeName { get; set; } public int T134LeafID { get; set; } public string T134NodeName { get; set; } public int UDFOrdinal { get; set; } public int EventTypeLeaf { get; set; } public string EventTypeCode { get; set; } public string EventTypeName { get; set; } public int Status { get; set; } public AndonPrdtLine Clone() { AndonPrdtLine rlt = MemberwiseClone() as AndonPrdtLine; return rlt; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PortableDeviceApiLib; using PortableDeviceTypesLib; using _tagpropertykey = PortableDeviceApiLib._tagpropertykey; using IPortableDeviceKeyCollection = PortableDeviceApiLib.IPortableDeviceKeyCollection; using IPortableDeviceValues = PortableDeviceApiLib.IPortableDeviceValues; namespace USBMonitorInForms { public class MTPDevice { private bool isConnected; private readonly PortableDevice device; public MTPDevice(string deviceId) { device = new PortableDevice(); this.DeviceId = deviceId; this.Connect(); } ~MTPDevice() { this.Disconnect(); } public string DeviceId { get; set; } public string FriendlyName { get { if (!this.isConnected) { throw new InvalidOperationException("Not connected to device."); } IPortableDeviceContent content; IPortableDeviceProperties properties; this.device.Content(out content); content.Properties(out properties); IPortableDeviceValues propertyValues; properties.GetValues("DEVICE", null, out propertyValues); var property = new _tagpropertykey(); property.fmtid = new Guid(0x26D4979A, 0xE643, 0x4626, 0x9E, 0x2B, 0x73, 0x6D, 0xC0, 0xC9, 0x2F, 0xDC); property.pid = 12; string propertyValue; propertyValues.GetStringValue(ref property, out propertyValue); return propertyValue; } } public void Connect() { if (this.isConnected) { return; } var clientInfo = (IPortableDeviceValues)new PortableDeviceValues(); this.device.Open(this.DeviceId, clientInfo); this.isConnected = true; } public void Disconnect() { if (!this.isConnected) { return; } try { this.device.Close(); } catch (Exception) {} this.isConnected = false; } } }
using UnityEngine; public class Player : MonoBehaviour { private GameManager _manager; private void Awake() { _manager = GameManager.Instance; } private void OnTriggerEnter(Collider other) { if (other.gameObject.tag.Equals("Astronaut")) { _manager.FoundCrewmate(); Destroy(other.gameObject); } } private void OnCollisionEnter(Collision other) { if (other.gameObject.tag.Equals("Alien")) { _manager.playerIsDead = true; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; namespace Test { [Route("api")] [ApiController] public class MedicalDataController : ControllerBase { private IMedicalDataRepository medicalDataRepository; public MedicalDataController(IMedicalDataRepository _medicalDataRepository) { medicalDataRepository = _medicalDataRepository; } [HttpGet("data")] public IActionResult GetAllData() { try { List<MedicalData> allData = medicalDataRepository.GetAllData(); return Ok(allData); } catch (Exception ex) { Errors errors = ErrorsHelper.GetErrors(ex); return StatusCode(StatusCodes.Status500InternalServerError, errors); } } [HttpPost("data")] public IActionResult AddData(MedicalData medicalData) { try { if (medicalDataRepository == null) { return BadRequest("Data is null."); } if (!ModelState.IsValid) { Errors errors = ErrorsHelper.GetErrors(ModelState); return BadRequest(errors); } MedicalData addedData = medicalDataRepository.AddData(medicalData); return StatusCode(StatusCodes.Status201Created, addedData); } catch (Exception ex) { Errors errors = ErrorsHelper.GetErrors(ex); return StatusCode(StatusCodes.Status500InternalServerError, errors); } } [HttpPost("data/calculate")] public IActionResult Calculate(DataToCalculate dataToCalculate) { try { float result = medicalDataRepository.Calculate(dataToCalculate.platelets, dataToCalculate.albumin, dataToCalculate.action.ToCharArray()[0]); return Ok(result); } catch (Exception ex) { Errors errors = ErrorsHelper.GetErrors(ex); return StatusCode(StatusCodes.Status500InternalServerError, errors); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Xamarin.Forms; namespace MicroSync { public enum Modes { EditMode, PlayMode } public class Container : AbsoluteLayout { //private static int NUM_GRIDLINES = 3; TapGestureRecognizer SingleTapRecognizer = new TapGestureRecognizer(); public Modes Mode = Modes.EditMode; public Container() { SingleTapRecognizer.Tapped += (s, e) => OnTap(s, SingleTapRecognizer); this.GestureRecognizers.Add(SingleTapRecognizer); } private void OnTap(object s, TapGestureRecognizer e) { Debug.WriteLine("CLICKED: " + s.GetType().Name); if(s.GetType().Name != "InternalFAB") { ClearFABS(); } } public void ClearFABS() { foreach (View v in this.Children) { if (v.GetType().Name == "FABContainer") { this.Children.Remove(v); break; } } } } }
using UnityEngine; public class BrushManager : MonoBehaviour { public Material drawMat; void Start() { drawMat.color = Color.black; drawMat.SetFloat("_BrushSize", 100f); } public void SetColor(string color) { switch(color) { case "red" : drawMat.color = Color.red; break; case "blue" : drawMat.color = Color.blue; break; case "green" : drawMat.color = Color.green; break; case "white" : drawMat.color = Color.white;// rubber as white color break; case "black" : drawMat.color = Color.black; break; case "cyan" : drawMat.color = Color.cyan; break; case "magenta" : drawMat.color = new Color(1, 0.41f, 0.70f); break; case "gray" : drawMat.color = Color.gray; break; case "yellow" : drawMat.color = Color.yellow; break; case "brown": drawMat.color = new Color(0.56f, 0.39f, 0); break; case "orange": drawMat.color = new Color(1, 0.65f, 0); break; case "violet": drawMat.color = new Color(0.61f, 0, 0.74f); break; } } public void SetBrushSize(float size) { drawMat.SetFloat("_BrushSize", size*1000); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PlayerController : MonoBehaviour { public int startingmaxhealth; private int level; private int xp; private int xptolevel; private int health; private int maxhealth; public Slider xpslider; public Slider hpslider; public Text leveltext; public Text healthtext; public static int HEALTHADDPERLEVEL = 10; // Use this for initialization void Start () { level = 1; xp = 0; xptolevel = 20; xpslider.maxValue = xptolevel; maxhealth = startingmaxhealth; health = maxhealth; hpslider.maxValue = maxhealth; } void Update () { SetTexts (); xpslider.value = xp; hpslider.value = health; } void SetTexts () { leveltext.text = "XP"; healthtext.text = "HP"; } public void AddXP(int addxp) { xp += addxp; if (xp >= xptolevel) { int carryoverxp = xp - xptolevel; xp = 0; LevelUp (); AddXP (carryoverxp); } } public void LevelUp() { level += 1; this.maxhealth += HEALTHADDPERLEVEL; this.health += maxhealth; } public void LoseHP(int losehp) { this.health -= losehp; } }
namespace BootcampTwitterKata { public interface IEventsLoader { void Load(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace UFO.Commander { [Serializable()] public class Config { private const string FILENAME = "commander_config.xml"; private static Config instance; public static Config Get() { return instance; } public static Config Load() { if(!File.Exists(FILENAME)) { instance = new Config(); } else { using(StreamReader inStream = File.OpenText(FILENAME)) { XmlSerializer serializer = new XmlSerializer(typeof(Config)); instance = (Config)serializer.Deserialize(inStream); } } return instance; } public static void Save() { if(instance != null) { using(StreamWriter outStream = File.CreateText(FILENAME)) { XmlSerializer serializer = new XmlSerializer(typeof(Config)); serializer.Serialize(outStream, instance); } } } public Config() { MediaRootPath = @"C:\"; UseWebServices = false; WebServiceBase = "http://localhost:56566"; DatabaseServer = "localhost"; DatabaseName = "ufo"; DatabaseUser = "root"; RequireCredentials = true; SmtpServer = ""; SmtpUser = ""; SmtpPassword = ""; EmailSenderAddress = ""; MailBodyTemplatePath = "Templates\\OnProgramChangedMail_en.txt"; MailBodyItemTemplatePath = "Templates\\OnProgramChangedMailItem_en.txt"; MailSubjectTemplatePath = "Templates\\OnProgramChangedMailSubject_en.txt"; } public string MediaRootPath { get; set; } public bool UseWebServices { get; set; } public string WebServiceBase { get; set; } public string DatabaseServer { get; set; } public string DatabaseName { get; set; } public string DatabaseUser { get; set; } public bool RequireCredentials { get; set; } public string SmtpServer { get; set; } public int SmtpPort { get; set; } public string SmtpUser { get; set; } public string SmtpPassword { get; set; } public string EmailSenderAddress { get; set; } public string MailBodyTemplatePath { get; set; } public string MailBodyItemTemplatePath { get; set; } public string MailSubjectTemplatePath { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities.Concrete; using FluentValidation; namespace Business.ValidationRules.FluentValidation { public class RentalValidator:AbstractValidator<Rental> { public RentalValidator() { RuleFor(p => p.CarId).NotEmpty(); RuleFor(p => p.CustomerId).NotEmpty(); RuleFor(p => p.RentDate).GreaterThan(1900); RuleFor(p => p.RentDate).NotEmpty(); RuleFor(p => p.ReturnDate).GreaterThan(1900); } } }
using System; using System.Collections.Generic; namespace StateCorrelations { public struct TypeContract : IEqualityComparer<TypeContract> { public static TypeContract From<T>() where T : class { return new TypeContract(typeof(T)); } public static TypeContract From(object e) { return new TypeContract(e.GetType()); } private readonly string _typeFullName; private TypeContract(Type o) { _typeFullName = o.FullName; } public static implicit operator string(TypeContract contract) { return contract._typeFullName; } #region equality comparison public override bool Equals(object other) { if(!(other is TypeContract)) return false; return Equals(this, (TypeContract)other); } public int GetHashCode(TypeContract a) { return _typeFullName.GetHashCode(); } public bool Equals(TypeContract a, TypeContract b) { return a._typeFullName.Equals(b._typeFullName); } public override int GetHashCode() { return GetHashCode(this); } #endregion } public class Folded<TSagaData> { public long? OffsetStart; public long? OffsetEnd; public long? ExceptionAtOffset; public TSagaData SagaData; } public class Event { public long Offset; public string What; public DateTimeOffset When; public IEvent Content; public Guid OriginatedFromStateBlobId; } public class BlobRecord { public long Id; public Guid BlobStateId; public Guid TransactionId; public string ConsumerName; public long OffsetStart; public long OffsetEnd; public long? ExceptionAtOffset; public DateTimeOffset RecordedAt; public object BlobState; public bool Replaying; } public class PreparedTransaction { public readonly IReadOnlyCollection<BlobRecord> UncommittedBlobs; public readonly IReadOnlyCollection<Event> UncommittedEvents; public readonly Guid TransactionId; public readonly long OffsetStart; public readonly long OffsetEnd; public readonly string ConsumerName; public readonly bool InProgress; public readonly DateTimeOffset RecordedAt; } public static partial class Create { public static Foldable<TSagaId, TSagaData> Foldable<TSagaId, TSagaData>( TSagaId sagaId, Folded<TSagaData> sagaData, IEnumerable<Event> events) => new Foldable<TSagaId, TSagaData>(sagaId, sagaData, events); public static DictionaryPair<TKey, TLeftValue, TRightValue> DictionaryPair<TKey, TLeftValue, TRightValue>( IReadOnlyDictionary<TKey, TLeftValue> left, IReadOnlyDictionary<TKey, TRightValue> right) => new DictionaryPair<TKey, TLeftValue, TRightValue>(left, right); } public struct DictionaryPair<TKey, TLeftValue, TRightValue> { public DictionaryPair(IReadOnlyDictionary<TKey, TLeftValue> left, IReadOnlyDictionary<TKey, TRightValue> right) { Left = left; Right = right; } public IReadOnlyDictionary<TKey, TLeftValue> Left { get; } public IReadOnlyDictionary<TKey, TRightValue> Right { get; } } public struct Foldable<TSagaId, TSagaData> { public Foldable(TSagaId sagaId, Folded<TSagaData> sagaData, IEnumerable<Event> events) { SagaId = sagaId; SagaData = sagaData; Events = events; } public TSagaId SagaId { get; } public Folded<TSagaData> SagaData { get; } public IEnumerable<Event> Events { get; } } public interface IEvent {} public delegate TState Transition<TState>(IEvent @event, TState state); }
using System; using CC.Mobile.Services; using Groceries.Domain; namespace Groceries.Services { public interface IServiceFactory: IBasicServiceFactory<AppConfiguration> { AppPreferencesService Preferences{get;} IUsersService Users{get;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Castle.Core.Logging; using ITPE3200_1_20H_nor_way.DAL; using ITPE3200_1_20H_nor_way.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace ITPE3200_1_20H_nor_way.Controllers { [Route("[controller]/[action]")] public class OrderTicketController : Controller { private readonly IOrderTicketRepository _db; private ILogger<OrderTicketController> _log; public OrderTicketController(IOrderTicketRepository db, ILogger<OrderTicketController> log) { _db = db; _log = log; } public async Task<List<StationVM>> GetStations() { return await _db.getStations(); } public async Task<List<TripVM>> FindTrip(OrderTicketVM orderTicketVM) { Console.WriteLine(orderTicketVM.selectedDeparture); Console.WriteLine(orderTicketVM.selectedAarrival); return await _db.FindTrip(orderTicketVM); } public async Task<TripVM> GetAtrip(int id) { return await _db.getAtrip(id); } public async Task<OrderTicketVM> GetPrice(OrderTicketVM orderTicketVM) { return await _db.getPrice(orderTicketVM); } public async Task<ActionResult> Save(OrderTicketVM orderTicketVM) { bool returnOK = await _db.settInn(orderTicketVM); if(!returnOK) { _log.LogInformation("FEILMELDING HER!"); return BadRequest("FEILMELDNG HER!"); } return Ok("OPERASJON VELLYKKET HER!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace XESmartTarget.Core.Responses { public class OutputColumn { public enum ColType { Column, Tag, Field } private string _name; public string Name { get { return _name; } set { _name = value; if (Regex.IsMatch(value, @"\s+AS\s+", RegexOptions.IgnoreCase)) { Calculated = true; } } } public virtual bool Calculated { get; set; } = false; public bool Hidden { get; set; } = false; public string Expression { get; set; } public string Alias { get; set; } public ColType ColumnType { get; set; } = ColType.Column; public OutputColumn() { Hidden = false; } public OutputColumn(string name) : this() { Name = name; Alias = name; } public override string ToString() { return Name; } // Allow implicit conversion from string // This is particularly useful when reading // the configuration from a .json file, in order // to keep it as simple as possible public static implicit operator OutputColumn(string name) { OutputColumn result = null; result = new OutputColumn(name); return result; } } }
using System; using DelftTools.Functions.Conversion; using DelftTools.Functions.Generic; using NUnit.Framework; namespace DelftTools.Functions.Tests.Conversion { [TestFixture] public class ConvertedVariableTest { [Test] public void IndependVariable() { IVariable<int> x = new Variable<int>("x") { Values = { 10 } }; IVariable s = new ConvertedVariable<string, string, int>(x, x, Convert.ToInt32, Convert.ToString); Assert.AreEqual("10", s.Values[0]); s.Values[0] = "20"; Assert.AreEqual(20, x.Values[0]); x.Values.Add(3); Assert.AreEqual(2, s.Values.Count); //convert it back to int does not because the converted variable loses type :( //IVariable intVariable = new ConvertedVariable<int, string>(s, (IVariable<string>) s, Convert.ToString, Convert.ToInt32); } [Test,Ignore("Work in progress")] public void DependendVariable() { IVariable<int> x = new Variable<int>("x"); IVariable<int> y= new Variable<int>("y"); y.Arguments.Add(x); IVariable<int> convertedY = new ConvertedVariable<int, string, int>(y, x, Convert.ToInt32, Convert.ToString); convertedY["20"] = 20; Assert.AreEqual(20, y[20]); } [Test] public void ConvertTwice() { //source==>strings==>ints IVariable<int> source = new Variable<int>(); IVariable<string> strings = new ConvertedVariable<string, string, int>(source, source, Convert.ToInt32, Convert.ToString); IVariable<int> ints = new ConvertedVariable<int, int, string>(strings, strings, Convert.ToString, Convert.ToInt32); ints.Values.Add(1); //assert all variables are updated. Assert.AreEqual(1,source.Values[0]); Assert.AreEqual("1", strings.Values[0]); Assert.AreEqual(1, ints.Values[0]); //this also works when adding to source source.Values.Add(2); Assert.AreEqual(2, source.Values[1]); Assert.AreEqual("2", strings.Values[1]); Assert.AreEqual(2, ints.Values[1]); } } }
using UnityEngine; namespace AudioVisualizer { [RequireComponent(typeof(AudioSource))] public class SpectrumDataProvider : MonoBehaviour { [SerializeField] private int m_SampleSize = 512; public int SampleSize => m_SampleSize; public float[] SpectrumData => m_SpectrumData; private void Awake() { m_SpectrumData = new float[m_SampleSize]; } private void Update() { _GetSpectrumDataFromAudioSource(); } private void _GetSpectrumDataFromAudioSource() { AudioSource.GetSpectrumData(m_SpectrumData, 0, FFTWindow.BlackmanHarris); } private float[] m_SpectrumData; private AudioSource m_AudioSource; private AudioSource AudioSource { get { if (m_AudioSource == null) m_AudioSource = GetComponent<AudioSource>(); return m_AudioSource; } } } }
using FirstFollowParser; using System; using System.Collections.Generic; using System.Text; namespace LL1Parser { class InputLexer { public List<String> elements; public InputLexer() { // TODO Auto-generated constructor stub } public InputLexer(String fileName, GrammarParser grammer) { try { System.IO.StreamReader reader = new System.IO.StreamReader(fileName); String text = ""; String var = ""; while ((text = reader.ReadLine()) != null) { var = ""; int i = 0; List<String> output = new List<String>(); while (i < text.Length) { var = ""; while (true) { if (i >= text.Length) break; var += text[i]; i++; if (grammer.terminals.Contains(var)) { break; } } if (!string.IsNullOrEmpty(var)) { output.Add(var); } } elements = output; } } catch (Exception e) { Console.WriteLine(e); } } } }
using System; using System.Linq; using System.Collections.Generic; using System.Runtime.Serialization; using Aquamonix.Mobile.Lib.Extensions; namespace Aquamonix.Mobile.Lib.Domain { [DataContract] public class DeviceSetting : IDomainObjectWithId, ICloneable<DeviceSetting>, IMergeable<DeviceSetting> { [DataMember(Name = PropertyNames.Id)] public string Id { get; set; } [DataMember(Name = PropertyNames.Name)] public string Name { get; set; } [DataMember(Name = PropertyNames.Editable)] public bool? Editable { get; set; } [DataMember(Name = PropertyNames.Updatable)] public bool? Updatable { get; set; } [DataMember(Name = PropertyNames.Value)] public string Value { get; set;} [DataMember(Name = PropertyNames.Values)] public ItemsDictionary<DeviceSettingValue> Values { get; set; } public DeviceSetting Clone() { var clone = new DeviceSetting() { Id = this.Id, Name = this.Name, Editable = this.Editable, Updatable = this.Updatable, Value = this.Value }; if (this.Values != null) clone.Values = this.Values.Clone(); return clone; } public void MergeFromParent(DeviceSetting parent, bool removeIfMissingFromParent, bool parentIsMetadata) { if (parent != null) { this.Id = MergeExtensions.MergeProperty(this.Id, parent.Id, removeIfMissingFromParent, parentIsMetadata); this.Name = MergeExtensions.MergeProperty(this.Name, parent.Name, removeIfMissingFromParent, parentIsMetadata); this.Editable = MergeExtensions.MergeProperty(this.Editable, parent.Editable, removeIfMissingFromParent, parentIsMetadata); this.Updatable = MergeExtensions.MergeProperty(this.Updatable, parent.Updatable, removeIfMissingFromParent, parentIsMetadata); this.Value = MergeExtensions.MergeProperty(this.Value, parent.Value, removeIfMissingFromParent, parentIsMetadata); this.Values = ItemsDictionary<DeviceSettingValue>.MergePropertyLists(this.Values, parent.Values, removeIfMissingFromParent, parentIsMetadata); } } public string GetValue(out DeviceSettingValue settingValue) { settingValue = null; var properValue = this.Values?.Values?.FirstOrDefault(); if (properValue != null) { settingValue = properValue; return properValue.Value; } return this.Value; } public string GetValue() { DeviceSettingValue value; return this.GetValue(out value); } public void ReadyChildIds() { } } [DataContract] public class DeviceSettingValue : ICloneable<DeviceSettingValue>, IMergeable<DeviceSettingValue> { [DataMember(Name = PropertyNames.Name)] public string Name { get; set; } [DataMember(Name = PropertyNames.Value)] public string Value { get; set; } [DataMember(Name = PropertyNames.Type)] public string Type { get; set; } [DataMember(Name = PropertyNames.DisplayType)] public string DisplayType { get; set; } [DataMember(Name = PropertyNames.Units)] public string Units { get; set; } [DataMember(Name = PropertyNames.DisplayPrecision)] public string DisplayPrecision { get; set; } [DataMember(Name = PropertyNames.EditPrecision)] public string EditPrecision { get; set; } [DataMember(Name = PropertyNames.Title)] public string Title { get; set; } [DataMember(Name = PropertyNames.SubText)] public string[] SubText { get; set; } [DataMember(Name = PropertyNames.Validation)] public MinMax Validation { get; set; } [DataMember(Name = PropertyNames.Dictionary)] public SettingValueDictionary Dictionary { get; set; } [DataMember(Name = PropertyNames.Enum)] public ItemsDictionary<DeviceSettingValue> Enum { get; set; } public DeviceSettingValue Clone() { var clone = new DeviceSettingValue() { Name = this.Name, DisplayType = this.DisplayType, DisplayPrecision = this.DisplayPrecision, EditPrecision = this.EditPrecision, Title = this.Title, Type = this.Type, Units = this.Units, Value = this.Value, SubText = this.SubText }; if (this.Validation != null) clone.Validation = this.Validation.Clone(); if (this.Dictionary != null) clone.Dictionary = this.Dictionary.Clone(); if (this.Enum != null) clone.Enum = this.Enum.Clone(); return clone; } public void MergeFromParent(DeviceSettingValue parent, bool removeIfMissingFromParent, bool parentIsMetadata) { if (parent != null) { this.Name = MergeExtensions.MergeProperty(this.Name, parent.Name, removeIfMissingFromParent, parentIsMetadata); this.Value = MergeExtensions.MergeProperty(this.Value, parent.Value, removeIfMissingFromParent, parentIsMetadata); this.Type = MergeExtensions.MergeProperty(this.Type, parent.Type, removeIfMissingFromParent, parentIsMetadata); this.DisplayType = MergeExtensions.MergeProperty(this.DisplayType, parent.DisplayType, removeIfMissingFromParent, parentIsMetadata); this.DisplayPrecision = MergeExtensions.MergeProperty(this.DisplayPrecision, parent.DisplayPrecision, removeIfMissingFromParent, parentIsMetadata); this.EditPrecision = MergeExtensions.MergeProperty(this.EditPrecision, parent.EditPrecision, removeIfMissingFromParent, parentIsMetadata); this.Units = MergeExtensions.MergeProperty(this.Units, parent.Units, removeIfMissingFromParent, parentIsMetadata); this.Title = MergeExtensions.MergeProperty(this.Title, parent.Title, removeIfMissingFromParent, parentIsMetadata); this.SubText = MergeExtensions.MergeProperty(this.SubText, parent.SubText, removeIfMissingFromParent, parentIsMetadata); //TODO: should these properties be merged? if (this.Validation == null && parent.Validation != null) this.Validation = parent.Validation.Clone(); if (this.Dictionary == null && parent.Dictionary != null) this.Dictionary = parent.Dictionary.Clone(); this.Enum = ItemsDictionary<DeviceSettingValue>.MergePropertyLists(this.Enum, parent.Enum, removeIfMissingFromParent, parentIsMetadata); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using UnityEngine; // //public class ProceduralFairingBase : PartModule //{ // [KSPField] public float outlineWidth=0.05f; // [KSPField] public int outlineSlices=12; // [KSPField] public Vector4 outlineColor=new Vector4(0, 0, 0.2f, 1); // [KSPField] public float verticalStep=0.2f; // [KSPField] public float baseSize=1.25f; // [KSPField(isPersistant=true)] public float extraRadius=0.2f; // [KSPField] public int circleSegments=24; // // [KSPField] public float sideThickness=0.05f; // // [KSPField] public string extraRadiusKey="r"; // // float updateDelay=0; // // // LineRenderer line=null; // // List<LineRenderer> outline=new List<LineRenderer>(); // // // List<ConfigurableJoint> joints=new List<ConfigurableJoint>(); // // // public void OnMouseOver() // { // if (HighLogic.LoadedSceneIsEditor) // { // if (part.isConnected && Input.GetKey(extraRadiusKey)) // { // float old=extraRadius; // extraRadius+=(Input.GetAxis("Mouse X")+Input.GetAxis("Mouse Y"))*0.1f; // extraRadius=Mathf.Max(extraRadius, -1); // extraRadius=Mathf.Min(extraRadius, 100); // if (extraRadius!=old) updateDelay=0; // } // } // } // // // public override string GetInfo() // { // string s="Attach side fairings and they'll be shaped for your attached payload.\n"+ // "Remember to add a decoupler if you need one."; // // if (!string.IsNullOrEmpty(extraRadiusKey)) // s+="\nMouse over and hold '"+extraRadiusKey+"' to adjust extra radius."; // // return s; // } // // // public override void OnStart(StartState state) // { // if (state==StartState.None) return; // // if ((state & StartState.Editor)!=0) // { // // line=makeLineRenderer("payload outline", Color.red, outlineWidth); // if (line) line.transform.Rotate(0, 90, 0); // // destroyOutline(); // for (int i=0; i<outlineSlices; ++i) // { // var r=makeLineRenderer("fairing outline", outlineColor, outlineWidth); // outline.Add(r); // r.transform.Rotate(0, i*360f/outlineSlices, 0); // } // // updateDelay=0; // } // } // // // public void OnPartPack() // { // while (joints.Count>0) // { // int i=joints.Count-1; // var joint=joints[i]; joints.RemoveAt(i); // UnityEngine.Object.Destroy(joint); // } // } // // // public void OnPartUnpack() // { // if (!HighLogic.LoadedSceneIsEditor) // { // // strut side fairings together // var attached=part.findAttachNodes("connect"); // for (int i=0; i<attached.Length; ++i) // { // var p=attached[i].attachedPart; // if (p==null || p.Rigidbody==null) continue; // // // var sf=p.GetComponent<ProceduralFairingSide>(); // // if (sf==null) continue; // // var pp=attached[i>0 ? i-1 : attached.Length-1].attachedPart; // if (pp==null) continue; // // var rb=pp.Rigidbody; // if (rb==null) continue; // // var joint=p.gameObject.AddComponent<ConfigurableJoint>(); // joint.xMotion=ConfigurableJointMotion.Locked; // joint.yMotion=ConfigurableJointMotion.Locked; // joint.zMotion=ConfigurableJointMotion.Locked; // joint.angularXMotion=ConfigurableJointMotion.Locked; // joint.angularYMotion=ConfigurableJointMotion.Locked; // joint.angularZMotion=ConfigurableJointMotion.Locked; // joint.projectionDistance=0.1f; // joint.projectionAngle=5; // joint.breakForce =p.breakingForce ; // joint.breakTorque=p.breakingTorque; // joint.connectedBody=rb; // // joints.Add(joint); // } // } // } // // // LineRenderer makeLineRenderer(string name, Color color, float wd) // { // var o=new GameObject(name); // o.transform.parent=part.transform; // o.transform.localPosition=Vector3.zero; // o.transform.localRotation=Quaternion.identity; // var r=o.AddComponent<LineRenderer>(); // r.useWorldSpace=false; // r.material=new Material(Shader.Find("Particles/Additive")); // r.SetColors(color, color); // r.SetWidth(wd, wd); // r.SetVertexCount(0); // return r; // } // // // void destroyOutline() // { // foreach (var r in outline) UnityEngine.Object.Destroy(r.gameObject); // outline.Clear(); // } // // // public void OnDestroy() // { // if (line) { UnityEngine.Object.Destroy(line.gameObject); line=null; } // destroyOutline(); // } // // // public void Update() // { // if (HighLogic.LoadedSceneIsEditor) // { // updateDelay-=Time.deltaTime; // if (updateDelay<=0) { recalcShape(); updateDelay=0.2f; } // } // } // // // static public Vector3[] buildFairingShape(float baseRad, float maxRad, // float cylStart, float cylEnd, float noseHeightRatio, // Vector4 baseConeShape, Vector4 noseConeShape, // int baseConeSegments, int noseConeSegments, // Vector4 vertMapping, float mappingScaleY) // { // float baseConeRad=maxRad-baseRad; // float tip=maxRad*noseHeightRatio; // // var baseSlope=new BezierSlope(baseConeShape); // var noseSlope=new BezierSlope(noseConeShape); // // float baseV0=vertMapping.x/mappingScaleY; // float baseV1=vertMapping.y/mappingScaleY; // float noseV0=vertMapping.z/mappingScaleY; // float noseV1=vertMapping.w/mappingScaleY; // // var shape=new Vector3[1+(cylStart==0?0:baseConeSegments)+1+noseConeSegments]; // int vi=0; // // if (cylStart!=0) // { // for (int i=0; i<=baseConeSegments; ++i, ++vi) // { // float t=(float)i/baseConeSegments; // var p=baseSlope.interp(t); // shape[vi]=new Vector3(p.x*baseConeRad+baseRad, p.y*cylStart, // Mathf.Lerp(baseV0, baseV1, t)); // } // } // else // shape[vi++]=new Vector3(baseRad, 0, baseV1); // // for (int i=0; i<=noseConeSegments; ++i, ++vi) // { // float t=(float)i/noseConeSegments; // var p=noseSlope.interp(1-t); // shape[vi]=new Vector3(p.x*maxRad, (1-p.y)*tip+cylEnd, // Mathf.Lerp(noseV0, noseV1, t)); // } // // return shape; // } // // // static public Vector3[] buildInlineFairingShape(float baseRad, float maxRad, float topRad, // float cylStart, float cylEnd, float top, // Vector4 baseConeShape, // int baseConeSegments, // Vector4 vertMapping, float mappingScaleY) // { // float baseConeRad=maxRad-baseRad; // float topConeRad=maxRad- topRad; // // var baseSlope=new BezierSlope(baseConeShape); // // float baseV0=vertMapping.x/mappingScaleY; // float baseV1=vertMapping.y/mappingScaleY; // float noseV0=vertMapping.z/mappingScaleY; // // var shape=new Vector3[2+(cylStart==0?0:baseConeSegments+1)+(cylEnd==top?0:baseConeSegments+1)]; // int vi=0; // // if (cylStart!=0) // { // for (int i=0; i<=baseConeSegments; ++i, ++vi) // { // float t=(float)i/baseConeSegments; // var p=baseSlope.interp(t); // shape[vi]=new Vector3(p.x*baseConeRad+baseRad, p.y*cylStart, // Mathf.Lerp(baseV0, baseV1, t)); // } // } // // shape[vi++]=new Vector3(maxRad, cylStart, baseV1); // shape[vi++]=new Vector3(maxRad, cylEnd, noseV0); // // if (cylEnd!=top) // { // for (int i=0; i<=baseConeSegments; ++i, ++vi) // { // float t=(float)i/baseConeSegments; // var p=baseSlope.interp(1-t); // shape[vi]=new Vector3(p.x*topConeRad+topRad, Mathf.Lerp(top, cylEnd, p.y), // Mathf.Lerp(baseV1, baseV0, t)); // } // } // // return shape; // } // // // void recalcShape() // { // // scan payload and build its profile // var scan=new PayloadScan(part, verticalStep, extraRadius); // // AttachNode node=part.findAttachNode("top"); // if (node!=null && node.attachedPart!=null) // { // scan.ofs=node.position.y; // scan.addPart(node.attachedPart, part); // } // // for (int i=0; i<scan.payload.Count; ++i) // { // var cp=scan.payload[i]; // // // add connected payload parts // scan.addPart(cp.parent, cp); // foreach (var p in cp.children) scan.addPart(p, cp); // // // scan part colliders // foreach (var coll in cp.FindModelComponents<Collider>()) // { // if (coll.tag!="Untagged") continue; // skip ladders etc. // scan.addPayload(coll); // } // } // // // check for reversed base for inline fairings // float topY=0; // ProceduralFairingBase topBase=null; // if (scan.targets.Count>0) // { // topBase=scan.targets[0].GetComponent<ProceduralFairingBase>(); // topY=scan.w2l.MultiplyPoint3x4(topBase.part.transform.position).y; // if (topY<scan.ofs) topY=scan.ofs; // } // // if (scan.profile.Count<=0) // { // // no payload // if (line) line.SetVertexCount(0); // foreach (var lr in outline) lr.SetVertexCount(0); // return; // } // // // fill profile outline (for debugging) // if (line) // { // line.SetVertexCount(scan.profile.Count*2+2); // // float prevRad=0; // int hi=0; // foreach (var r in scan.profile) // { // line.SetPosition(hi*2 , new Vector3(prevRad, hi*verticalStep+scan.ofs, 0)); // line.SetPosition(hi*2+1, new Vector3( r, hi*verticalStep+scan.ofs, 0)); // hi++; prevRad=r; // } // // line.SetPosition(hi*2 , new Vector3(prevRad, hi*verticalStep+scan.ofs, 0)); // line.SetPosition(hi*2+1, new Vector3( 0, hi*verticalStep+scan.ofs, 0)); // } // // // check attached side parts and get params // var attached=part.findAttachNodes("connect"); // int numSideParts=attached.Length; // // var sideNode=attached.FirstOrDefault(n => n.attachedPart // && n.attachedPart.GetComponent<ProceduralFairingSide>()); // // float noseHeightRatio=2; // Vector4 baseConeShape=new Vector4(0.5f, 0, 1, 0.5f); // Vector4 noseConeShape=new Vector4(0.5f, 0, 1, 0.5f); // int baseConeSegments=1; // int noseConeSegments=1; // Vector2 mappingScale=new Vector2(1024, 1024); // Vector2 stripMapping=new Vector2(992, 1024); // Vector4 horMapping=new Vector4(0, 480, 512, 992); // Vector4 vertMapping=new Vector4(0, 160, 704, 1024); // // if (sideNode!=null) // { // var sf=sideNode.attachedPart.GetComponent<ProceduralFairingSide>(); // noseHeightRatio =sf.noseHeightRatio ; // baseConeShape =sf.baseConeShape ; // noseConeShape =sf.noseConeShape ; // baseConeSegments=sf.baseConeSegments; // noseConeSegments=sf.noseConeSegments; // mappingScale =sf.mappingScale ; // stripMapping =sf.stripMapping ; // horMapping =sf.horMapping ; // vertMapping =sf.vertMapping ; // } // // // compute fairing shape // float baseRad=baseSize*0.5f; // // float cylStart=0; // float maxRad=scan.profile.Max(); // // float topRad=0; // if (topBase!=null) // { // topRad=topBase.baseSize*0.5f; // maxRad=Mathf.Max(maxRad, topRad); // } // // if (maxRad>baseRad) // { // // try to fit base cone as high as possible // cylStart=scan.ofs; // for (int i=1; i<scan.profile.Count; ++i) // { // float y=i*verticalStep+scan.ofs; // float r0=baseRad; // float k=(maxRad-r0)/y; // // bool ok=true; // float r=r0+k*scan.ofs; // for (int j=0; j<i; ++j, r+=k*verticalStep) // if (scan.profile[j]>r) { ok=false; break; } // // if (!ok) break; // cylStart=y; // } // } // else // maxRad=baseRad; // no base cone, just cylinder and nose // // float cylEnd=scan.profile.Count*verticalStep+scan.ofs; // // if (topBase!=null) // { // cylEnd=topY; // // if (maxRad>topRad) // { // // try to fit top cone as low as possible // for (int i=scan.profile.Count-1; i>=0; --i) // { // float y=i*verticalStep+scan.ofs; // float r0=topRad; // float k=(maxRad-r0)/(y-topY); // // bool ok=true; // float r=maxRad+k*verticalStep; // for (int j=i; j<scan.profile.Count; ++j, r+=k*verticalStep) // if (scan.profile[j]>r) { ok=false; break; } // // if (!ok) break; // // cylEnd=y; // } // } // } // else // { // // try to fit nose cone as low as possible // for (int i=scan.profile.Count-1; i>=0; --i) // { // float s=verticalStep/noseHeightRatio; // // bool ok=true; // float r=maxRad-s; // for (int j=i; j<scan.profile.Count; ++j, r-=s) // if (scan.profile[j]>r) { ok=false; break; } // // if (!ok) break; // // float y=i*verticalStep+scan.ofs; // cylEnd=y; // } // } // // if (cylStart>cylEnd) cylStart=cylEnd; // // // build fairing shape line // Vector3[] shape; // // if (topBase!=null) // shape=buildInlineFairingShape(baseRad, maxRad, topRad, cylStart, cylEnd, topY, // baseConeShape, baseConeSegments, // vertMapping, mappingScale.y); // else // shape=buildFairingShape(baseRad, maxRad, cylStart, cylEnd, noseHeightRatio, // baseConeShape, noseConeShape, baseConeSegments, noseConeSegments, // vertMapping, mappingScale.y); // // if (sideNode==null) // { // // no side parts - fill fairing outlines // foreach (var lr in outline) // { // lr.SetVertexCount(shape.Length); // for (int i=0; i<shape.Length; ++i) // lr.SetPosition(i, new Vector3(shape[i].x, shape[i].y)); // } // } // else // { // foreach (var lr in outline) // lr.SetVertexCount(0); // } // // // rebuild side parts // int numSegs=circleSegments/numSideParts; // if (numSegs<2) numSegs=2; // // foreach (var sn in attached) // { // var sp=sn.attachedPart; // if (!sp) continue; // var sf=sp.GetComponent<ProceduralFairingSide>(); // if (!sf) continue; // // var mf=sp.FindModelComponent<MeshFilter>("model"); // if (!mf) { Debug.LogError("[ProceduralFairingBase] no model in side fairing", sp); continue; } // // var nodePos=sn.position; // // mf.transform.position=part.transform.position; // mf.transform.rotation=part.transform.rotation; // float ra=Mathf.Atan2(-nodePos.z, nodePos.x)*Mathf.Rad2Deg; // mf.transform.Rotate(0, ra, 0); // // sf.meshPos=mf.transform.localPosition; // sf.meshRot=mf.transform.localRotation; // sf.numSegs=numSegs; // sf.numSideParts=numSideParts; // sf.baseRad=baseRad; // sf.maxRad=maxRad; // sf.cylStart=cylStart; // sf.cylEnd=cylEnd; // sf.topRad=topRad; // sf.inlineHeight=topY; // sf.sideThickness=sideThickness; // sf.rebuildMesh(); // } // } //} // // ////ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ// // // //public class ProceduralFairingSide : PartModule //{ // [KSPField] public float ejectionDv=15; // [KSPField] public float ejectionTorque=0.2f; // [KSPField] public float ejectionLowDv=1; // [KSPField] public float ejectionLowTorque=0.01f; // // [KSPField] public string ejectionPowerKey="f"; // [KSPField(isPersistant=true)] public float ejectionPower=1; // // [KSPField] public string ejectSoundUrl="Squad/Sounds/sound_decoupler_fire"; // public FXGroup ejectFx; // // [KSPField] public float noseHeightRatio=2; // [KSPField] public Vector4 baseConeShape=new Vector4(0.5f, 0, 1, 0.5f); // [KSPField] public Vector4 noseConeShape=new Vector4(0.5f, 0, 1, 0.5f); // [KSPField] public int baseConeSegments=5; // [KSPField] public int noseConeSegments=7; // // [KSPField] public Vector2 mappingScale=new Vector2(1024, 1024); // [KSPField] public Vector2 stripMapping=new Vector2(992, 1024); // [KSPField] public Vector4 horMapping=new Vector4(0, 480, 512, 992); // [KSPField] public Vector4 vertMapping=new Vector4(0, 160, 704, 1024); // // [KSPField] public float density=0.2f; // [KSPField] public float specificBreakingForce =2000; // [KSPField] public float specificBreakingTorque=2000; // // [KSPField(isPersistant=true)] public int numSegs=12; // [KSPField(isPersistant=true)] public int numSideParts=2; // [KSPField(isPersistant=true)] public float baseRad=1.25f; // [KSPField(isPersistant=true)] public float maxRad=1.50f; // [KSPField(isPersistant=true)] public float cylStart=0.5f; // [KSPField(isPersistant=true)] public float cylEnd =2.5f; // [KSPField(isPersistant=true)] public float topRad=0; // [KSPField(isPersistant=true)] public float inlineHeight=0; // [KSPField(isPersistant=true)] public float sideThickness=0.05f; // [KSPField(isPersistant=true)] public Vector3 meshPos=Vector3.zero; // [KSPField(isPersistant=true)] public Quaternion meshRot=Quaternion.identity; // // // public override string GetInfo() // { // string s="Attach to Keramzit's fairing base to reshape."; // // if (!string.IsNullOrEmpty(ejectionPowerKey)) // s+="\nMouse over and press '"+ejectionPowerKey+"' to change ejection force."; // // return s; // } // // // public override void OnStart(StartState state) // { // if (state==StartState.None) return; // // ejectFx.audio=part.gameObject.AddComponent<AudioSource>(); // ejectFx.audio.volume=GameSettings.SHIP_VOLUME; // ejectFx.audio.rolloffMode=AudioRolloffMode.Logarithmic; // ejectFx.audio.panLevel=1; // ejectFx.audio.maxDistance=100; // ejectFx.audio.loop=false; // ejectFx.audio.playOnAwake=false; // // if (GameDatabase.Instance.ExistsAudioClip(ejectSoundUrl)) // ejectFx.audio.clip=GameDatabase.Instance.GetAudioClip(ejectSoundUrl); // else // Debug.LogError("[ProceduralFairingSide] can't find sound: "+ejectSoundUrl, this); // // if (state!=StartState.Editor) rebuildMesh(); // } // // // public void rebuildMesh() // { // var mf=part.FindModelComponent<MeshFilter>("model"); // if (!mf) { Debug.LogError("[ProceduralFairingSide] no model in side fairing", part); return; } // // Mesh m=mf.mesh; // if (!m) { Debug.LogError("[ProceduralFairingSide] no mesh in side fairing", part); return; } // // mf.transform.localPosition=meshPos; // mf.transform.localRotation=meshRot; // // // build fairing shape line // float tip=maxRad*noseHeightRatio; // // Vector3[] shape; // if (inlineHeight<=0) // shape=ProceduralFairingBase.buildFairingShape( // baseRad, maxRad, cylStart, cylEnd, noseHeightRatio, // baseConeShape, noseConeShape, baseConeSegments, noseConeSegments, // vertMapping, mappingScale.y); // else // shape=ProceduralFairingBase.buildInlineFairingShape( // baseRad, maxRad, topRad, cylStart, cylEnd, inlineHeight, // baseConeShape, baseConeSegments, // vertMapping, mappingScale.y); // // // set up params // var dirs=new Vector3[numSegs+1]; // for (int i=0; i<=numSegs; ++i) // { // float a=Mathf.PI*2*(i-numSegs*0.5f)/(numSideParts*numSegs); // dirs[i]=new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a)); // } // // float segOMappingScale=(horMapping.y-horMapping.x)/(mappingScale.x*numSegs); // float segIMappingScale=(horMapping.w-horMapping.z)/(mappingScale.x*numSegs); // float segOMappingOfs=horMapping.x/mappingScale.x; // float segIMappingOfs=horMapping.z/mappingScale.x; // // if (numSideParts>2) // { // segOMappingOfs+=segOMappingScale*numSegs*(0.5f-1f/numSideParts); // segOMappingScale*=2f/numSideParts; // segIMappingOfs+=segIMappingScale*numSegs*(0.5f-1f/numSideParts); // segIMappingScale*=2f/numSideParts; // } // // float stripU0=stripMapping.x/mappingScale.x; // float stripU1=stripMapping.y/mappingScale.x; // // float ringSegLen=baseRad*Mathf.PI*2/(numSegs*numSideParts); // float topRingSegLen=topRad*Mathf.PI*2/(numSegs*numSideParts); // // float collWidth=maxRad*Mathf.PI*2/(numSideParts*3); // // int numMainVerts=(numSegs+1)*(shape.Length-1)+1; // int numMainFaces=numSegs*((shape.Length-2)*2+1); // // int numSideVerts=shape.Length*2; // int numSideFaces=(shape.Length-1)*2; // // int numRingVerts=(numSegs+1)*2; // int numRingFaces=numSegs*2; // // if (inlineHeight>0) // { // numMainVerts=(numSegs+1)*shape.Length; // numMainFaces=numSegs*(shape.Length-1)*2; // } // // int totalVerts=numMainVerts*2+numSideVerts*2+numRingVerts; // int totalFaces=numMainFaces*2+numSideFaces*2+numRingFaces; // // if (inlineHeight>0) // { // totalVerts+=numRingVerts; // totalFaces+=numRingFaces; // } // // var p=shape[shape.Length-1]; // float topY=p.y, topV=p.z; // // float collCenter=(cylStart+cylEnd)/2, collHeight=cylEnd-cylStart; // if (collHeight<=0) collHeight=Mathf.Min(topY-cylEnd, cylStart)/2; // // // compute area // double area=0; // for (int i=1; i<shape.Length; ++i) // area+=(shape[i-1].x+shape[i].x)*(shape[i].y-shape[i-1].y)*Mathf.PI/numSideParts; // // // set params based on volume // float volume=(float)(area*sideThickness); // part.mass=volume*density; // part.breakingForce =part.mass*specificBreakingForce; // part.breakingTorque=part.mass*specificBreakingTorque; // // var offset=new Vector3(maxRad*0.7f, topY*0.5f, 0); // part.CoMOffset=part.transform.InverseTransformPoint(mf.transform.TransformPoint(offset)); // // // remove old colliders // foreach (var c in part.FindModelComponents<Collider>()) // UnityEngine.Object.Destroy(c.gameObject); // // // add new colliders // for (int i=-1; i<=1; ++i) // { // var obj=new GameObject("collider"); // obj.transform.parent=mf.transform; // obj.transform.localPosition=Vector3.zero; // obj.transform.localRotation=Quaternion.AngleAxis(90f*i/numSideParts, Vector3.up); // var coll=obj.AddComponent<BoxCollider>(); // coll.center=new Vector3(maxRad+sideThickness*0.5f, collCenter, 0); // coll.size=new Vector3(sideThickness, collHeight, collWidth); // } // // { // // nose collider // float r=maxRad*0.2f; // var obj=new GameObject("nose_collider"); // obj.transform.parent=mf.transform; // obj.transform.localPosition=new Vector3(r, cylEnd+tip-r*1.2f, 0); // obj.transform.localRotation=Quaternion.identity; // // if (inlineHeight>0) // { // r=sideThickness*0.5f; // obj.transform.localPosition=new Vector3(maxRad+r, collCenter, 0); // } // // var coll=obj.AddComponent<SphereCollider>(); // coll.center=Vector3.zero; // coll.radius=r; // } // // // build mesh // m.Clear(); // // var verts=new Vector3[totalVerts]; // var uv=new Vector2[totalVerts]; // var norm=new Vector3[totalVerts]; // var tang=new Vector4[totalVerts]; // // if (inlineHeight<=0) // { // // tip vertex // verts[numMainVerts -1].Set(0, topY+sideThickness, 0); // outside // verts[numMainVerts*2-1].Set(0, topY, 0); // inside // uv[numMainVerts -1].Set(segOMappingScale*0.5f*numSegs+segOMappingOfs, topV); // uv[numMainVerts*2-1].Set(segIMappingScale*0.5f*numSegs+segIMappingOfs, topV); // norm[numMainVerts -1]= Vector3.up; // norm[numMainVerts*2-1]=-Vector3.up; // // tang[numMainVerts -1]= Vector3.forward; // // tang[numMainVerts*2-1]=-Vector3.forward; // tang[numMainVerts -1]=Vector3.zero; // tang[numMainVerts*2-1]=Vector3.zero; // } // // // main vertices // float noseV0=vertMapping.z/mappingScale.y; // float noseV1=vertMapping.w/mappingScale.y; // float noseVScale=1f/(noseV1-noseV0); // float oCenter=(horMapping.x+horMapping.y)/(mappingScale.x*2); // float iCenter=(horMapping.z+horMapping.w)/(mappingScale.x*2); // // int vi=0; // for (int i=0; i<shape.Length-(inlineHeight<=0?1:0); ++i) // { // p=shape[i]; // // Vector2 n; // if (i==0) n=shape[1]-shape[0]; // else if (i==shape.Length-1) n=shape[i]-shape[i-1]; // else n=shape[i+1]-shape[i-1]; // n.Set(n.y, -n.x); // n.Normalize(); // // for (int j=0; j<=numSegs; ++j, ++vi) // { // var d=dirs[j]; // var dp=d*p.x+Vector3.up*p.y; // var dn=d*n.x+Vector3.up*n.y; // if (i==0 || i==shape.Length-1) verts[vi]=dp+d*sideThickness; // else verts[vi]=dp+dn*sideThickness; // verts[vi+numMainVerts]=dp; // // float v=(p.z-noseV0)*noseVScale; // float uo=j*segOMappingScale+segOMappingOfs; // float ui=(numSegs-j)*segIMappingScale+segIMappingOfs; // if (v>0 && v<1) // { // float us=1-v; // uo=(uo-oCenter)*us+oCenter; // ui=(ui-iCenter)*us+iCenter; // } // // uv[vi].Set(uo, p.z); // uv[vi+numMainVerts].Set(ui, p.z); // // norm[vi]=dn; // norm[vi+numMainVerts]=-dn; // tang[vi].Set(-d.z, 0, d.x, 0); // tang[vi+numMainVerts].Set(d.z, 0, -d.x, 0); // } // } // // // side strip vertices // float stripScale=Mathf.Abs(stripMapping.y-stripMapping.x)/(sideThickness*mappingScale.y); // // vi=numMainVerts*2; // float o=0; // for (int i=0; i<shape.Length; ++i, vi+=2) // { // int si=i*(numSegs+1); // // var d=dirs[0]; // verts[vi]=verts[si]; // uv[vi].Set(stripU0, o); // norm[vi].Set(d.z, 0, -d.x); // // verts[vi+1]=verts[si+numMainVerts]; // uv[vi+1].Set(stripU1, o); // norm[vi+1]=norm[vi]; // tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized; // // if (i+1<shape.Length) o+=((Vector2)shape[i+1]-(Vector2)shape[i]).magnitude*stripScale; // } // // vi+=numSideVerts-2; // for (int i=shape.Length-1; i>=0; --i, vi-=2) // { // int si=i*(numSegs+1)+numSegs; // if (i==shape.Length-1 && inlineHeight<=0) si=numMainVerts-1; // // var d=dirs[numSegs]; // verts[vi]=verts[si]; // uv[vi].Set(stripU0, o); // norm[vi].Set(-d.z, 0, d.x); // // verts[vi+1]=verts[si+numMainVerts]; // uv[vi+1].Set(stripU1, o); // norm[vi+1]=norm[vi]; // tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized; // // if (i>0) o+=((Vector2)shape[i]-(Vector2)shape[i-1]).magnitude*stripScale; // } // // // ring vertices // vi=numMainVerts*2+numSideVerts*2; // o=0; // for (int j=numSegs; j>=0; --j, vi+=2, o+=ringSegLen*stripScale) // { // verts[vi]=verts[j]; // uv[vi].Set(stripU0, o); // norm[vi]=-Vector3.up; // // verts[vi+1]=verts[j+numMainVerts]; // uv[vi+1].Set(stripU1, o); // norm[vi+1]=-Vector3.up; // tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized; // } // // if (inlineHeight>0) // { // // top ring vertices // o=0; // int si=(shape.Length-1)*(numSegs+1); // for (int j=0; j<=numSegs; ++j, vi+=2, o+=topRingSegLen*stripScale) // { // verts[vi]=verts[si+j]; // uv[vi].Set(stripU0, o); // norm[vi]=Vector3.up; // // verts[vi+1]=verts[si+j+numMainVerts]; // uv[vi+1].Set(stripU1, o); // norm[vi+1]=Vector3.up; // tang[vi]=tang[vi+1]=(verts[vi+1]-verts[vi]).normalized; // } // } // // // set vertex data to mesh // for (int i=0; i<totalVerts; ++i) tang[i].w=1; // m.vertices=verts; // m.uv=uv; // m.normals=norm; // m.tangents=tang; // // m.uv2=null; // m.colors32=null; // // var tri=new int[totalFaces*3]; // // // main faces // vi=0; // int ti1=0, ti2=numMainFaces*3; // for (int i=0; i<shape.Length-(inlineHeight<=0?2:1); ++i, ++vi) // { // p=shape[i]; // for (int j=0; j<numSegs; ++j, ++vi) // { // tri[ti1++]=vi; // tri[ti1++]=vi+1+numSegs+1; // tri[ti1++]=vi+1; // // tri[ti1++]=vi; // tri[ti1++]=vi +numSegs+1; // tri[ti1++]=vi+1+numSegs+1; // // tri[ti2++]=numMainVerts+vi; // tri[ti2++]=numMainVerts+vi+1; // tri[ti2++]=numMainVerts+vi+1+numSegs+1; // // tri[ti2++]=numMainVerts+vi; // tri[ti2++]=numMainVerts+vi+1+numSegs+1; // tri[ti2++]=numMainVerts+vi +numSegs+1; // } // } // // if (inlineHeight<=0) // { // // main tip faces // for (int j=0; j<numSegs; ++j, ++vi) // { // tri[ti1++]=vi; // tri[ti1++]=numMainVerts-1; // tri[ti1++]=vi+1; // // tri[ti2++]=numMainVerts+vi; // tri[ti2++]=numMainVerts+vi+1; // tri[ti2++]=numMainVerts+numMainVerts-1; // } // } // // // side strip faces // vi=numMainVerts*2; // ti1=numMainFaces*2*3; // ti2=ti1+numSideFaces*3; // for (int i=0; i<shape.Length-1; ++i, vi+=2) // { // tri[ti1++]=vi; // tri[ti1++]=vi+1; // tri[ti1++]=vi+3; // // tri[ti1++]=vi; // tri[ti1++]=vi+3; // tri[ti1++]=vi+2; // // tri[ti2++]=numSideVerts+vi; // tri[ti2++]=numSideVerts+vi+3; // tri[ti2++]=numSideVerts+vi+1; // // tri[ti2++]=numSideVerts+vi; // tri[ti2++]=numSideVerts+vi+2; // tri[ti2++]=numSideVerts+vi+3; // } // // // ring faces // vi=numMainVerts*2+numSideVerts*2; // ti1=(numMainFaces+numSideFaces)*2*3; // for (int j=0; j<numSegs; ++j, vi+=2) // { // tri[ti1++]=vi; // tri[ti1++]=vi+1; // tri[ti1++]=vi+3; // // tri[ti1++]=vi; // tri[ti1++]=vi+3; // tri[ti1++]=vi+2; // } // // if (inlineHeight>0) // { // // top ring faces // vi+=2; // for (int j=0; j<numSegs; ++j, vi+=2) // { // tri[ti1++]=vi; // tri[ti1++]=vi+1; // tri[ti1++]=vi+3; // // tri[ti1++]=vi; // tri[ti1++]=vi+3; // tri[ti1++]=vi+2; // } // } // // m.triangles=tri; // // if (!HighLogic.LoadedSceneIsEditor) m.Optimize(); // // part.SendEvent("FairingShapeChanged"); // } // // // [KSPEvent(name = "Jettison", active=true, guiActive=true, guiActiveUnfocused=false, guiName="Jettison")] // public void Jettison() // { // if (part.parent) // { // foreach (var p in part.parent.children) // { // var joint=p.GetComponent<ConfigurableJoint>(); // if (joint!=null && (joint.rigidbody==part.Rigidbody || joint.connectedBody==part.Rigidbody)) // Destroy(joint); // } // // part.decouple(0); // // var tr=part.FindModelTransform("nose_collider"); // if (tr) // { // part.Rigidbody.AddForce(tr.right*Mathf.Lerp(ejectionLowDv, ejectionDv, ejectionPower), // ForceMode.VelocityChange); // part.Rigidbody.AddTorque(-tr.forward*Mathf.Lerp(ejectionLowTorque, ejectionTorque, ejectionPower), // ForceMode.VelocityChange); // } // else // Debug.LogError("[ProceduralFairingSide] no 'nose_collider' in side fairing", part); // // ejectFx.audio.Play(); // } // } // // // public override void OnActive() // { // Jettison(); // } // // // [KSPAction("Jettison", actionGroup=KSPActionGroup.None)] // public void ActionJettison(KSPActionParam param) // { // Jettison(); // } // // // float osdMessageTime=0; // string osdMessageText=null; // // // public void OnMouseOver() // { // if (HighLogic.LoadedSceneIsEditor) // { // if (Input.GetKeyDown(ejectionPowerKey)) // { // if (ejectionPower<0.25f) ejectionPower=0.5f; // else if (ejectionPower<0.75f) ejectionPower=1; // else ejectionPower=0; // // foreach (var p in part.symmetryCounterparts) // p.GetComponent<ProceduralFairingSide>().ejectionPower=ejectionPower; // // osdMessageTime=Time.time+0.5f; // osdMessageText="Fairing ejection force: "; // // if (ejectionPower<0.25f) osdMessageText+="low"; // else if (ejectionPower<0.75f) osdMessageText+="medium"; // else osdMessageText+="high"; // } // } // } // // // public void OnGUI() // { // if (!HighLogic.LoadedSceneIsEditor) return; // // if (Time.time<osdMessageTime) // { // GUI.skin=HighLogic.Skin; // GUIStyle style=new GUIStyle("Label"); // style.alignment=TextAnchor.MiddleCenter; // style.fontSize=20; // style.normal.textColor=Color.black; // GUI.Label(new Rect(2, 2+(Screen.height/9), Screen.width, 50), osdMessageText, style); // style.normal.textColor=Color.yellow; // GUI.Label(new Rect(0, Screen.height/9, Screen.width, 50), osdMessageText, style); // } // } //} // //struct BezierSlope //{ // Vector2 p1, p2; // // public BezierSlope(Vector4 v) // { // p1=new Vector2(v.x, v.y); // p2=new Vector2(v.z, v.w); // } // // public Vector2 interp(float t) // { // Vector2 a=Vector2.Lerp(Vector2.zero, p1, t); // Vector2 b=Vector2.Lerp(p1, p2, t); // Vector2 c=Vector2.Lerp(p2, Vector2.one, t); // // Vector2 d=Vector2.Lerp(a, b, t); // Vector2 e=Vector2.Lerp(b, c, t); // // return Vector2.Lerp(d, e, t); // } //} // // // //struct PayloadScan //{ // public List<float> profile; // public List<Part> payload; // public HashSet<Part> hash; // // public List<Part> targets; // // public Matrix4x4 w2l; // // public float ofs, verticalStep, extraRadius; // // // public PayloadScan(Part p, float vs, float er) // { // profile=new List<float>(); // payload=new List<Part>(); // targets=new List<Part>(); // hash=new HashSet<Part>(); // hash.Add(p); // w2l=p.transform.worldToLocalMatrix; // ofs=0; // verticalStep=vs; // extraRadius=er; // } // // // public void addPart(Part p, Part prevPart) // { // if (p==null || hash.Contains(p)) return; // hash.Add(p); // // // check for another fairing base // if (p.GetComponent<ProceduralFairingBase>()!=null) // { // AttachNode node=p.findAttachNode("top"); // if (node!=null && node.attachedPart==prevPart) // { // // reversed base - potential inline fairing target // targets.Add(p); // return; // } // } // // payload.Add(p); // } // // // public void addPayloadEdge(Vector3 v0, Vector3 v1) // { // float r0=Mathf.Sqrt(v0.x*v0.x+v0.z*v0.z)+extraRadius; // float r1=Mathf.Sqrt(v1.x*v1.x+v1.z*v1.z)+extraRadius; // // float y0=(v0.y-ofs)/verticalStep; // float y1=(v1.y-ofs)/verticalStep; // // if (y0>y1) // { // float tmp; // tmp=y0; y0=y1; y1=tmp; // tmp=r0; r0=r1; r1=tmp; // } // // int h0=Mathf.FloorToInt(y0); // int h1=Mathf.FloorToInt(y1); // if (h1<0) return; // if (h1>=profile.Count) profile.AddRange(Enumerable.Repeat(0f, h1-profile.Count+1)); // // if (h0>=0) profile[h0]=Mathf.Max(profile[h0], r0); // profile[h1]=Mathf.Max(profile[h1], r1); // // if (h0!=h1) // { // float k=(r1-r0)/(y1-y0); // float b=r0+k*(h0+1-y0); // float maxR=Mathf.Max(r0, r1); // // for (int h=Math.Max(h0, 0); h<h1; ++h) // { // float r=Mathf.Min(k*(h-h0)+b, maxR); // profile[h ]=Mathf.Max(profile[h ], r); // profile[h+1]=Mathf.Max(profile[h+1], r); // } // } // } // // // public void addPayload(Bounds box, Matrix4x4 boxTm) // { // Matrix4x4 m=w2l*boxTm; // // Vector3 p0=box.min, p1=box.max; // var verts=new Vector3[8]; // for (int i=0; i<8; ++i) // verts[i]=m.MultiplyPoint3x4(new Vector3( // (i&1)!=0 ? p1.x : p0.x, // (i&2)!=0 ? p1.y : p0.y, // (i&4)!=0 ? p1.z : p0.z)); // // addPayloadEdge(verts[0], verts[1]); // addPayloadEdge(verts[2], verts[3]); // addPayloadEdge(verts[4], verts[5]); // addPayloadEdge(verts[6], verts[7]); // // addPayloadEdge(verts[0], verts[2]); // addPayloadEdge(verts[1], verts[3]); // addPayloadEdge(verts[4], verts[6]); // addPayloadEdge(verts[5], verts[7]); // // addPayloadEdge(verts[0], verts[4]); // addPayloadEdge(verts[1], verts[5]); // addPayloadEdge(verts[2], verts[6]); // addPayloadEdge(verts[3], verts[7]); // } // // // public void addPayload(Collider c) // { // var mc=c as MeshCollider; // var bc=c as BoxCollider; // if (mc) // { // // addPayload(mc.sharedMesh.bounds, // // c.GetComponent<Transform>().localToWorldMatrix); // var m=w2l*mc.transform.localToWorldMatrix; // var verts=mc.sharedMesh.vertices; // var faces=mc.sharedMesh.triangles; // for (int i=0; i<faces.Length; i+=3) // { // var v0=m.MultiplyPoint3x4(verts[faces[i ]]); // var v1=m.MultiplyPoint3x4(verts[faces[i+1]]); // var v2=m.MultiplyPoint3x4(verts[faces[i+2]]); // addPayloadEdge(v0, v1); // addPayloadEdge(v1, v2); // addPayloadEdge(v2, v0); // } // } // else if (bc) // addPayload(new Bounds(bc.center, bc.size), // bc.transform.localToWorldMatrix); // else // { // // Debug.Log("generic collider "+c); // addPayload(c.bounds, Matrix4x4.identity); // } // } //} // // ////ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ// //
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; namespace Formatter { public class ReceiptFormat1:BaseReceiptFormatter { /// <summary> /// Конструктор, сразу в нем формируем тело чека /// </summary> /// <param name="receipt"></param> /// <param name="width"></param> public ReceiptFormat1(Receipt receipt, int width, int posNumber, bool SlipInsideReceipt) : base(receipt, width, posNumber,"",SlipInsideReceipt) { } public ReceiptFormat1(Receipt receipt, int width, int posNumber, string formatReceiptName, bool SlipInsideReceipt) : base(receipt, width, posNumber, formatReceiptName, SlipInsideReceipt) { } public override string Init(Receipt receipt, int width, int posNumber, string formatReceiptName, bool SlipInsideReceipt) { string result = ""; try { MakeHeader(); } catch (Exception e) { result = e.Message; } try { MakeBody(); } catch (Exception e) { result = e.Message; } try { MakeFooter(); } catch (Exception e) { result = e.Message; } try { MakeSlip(); } catch (Exception e) { result = e.Message; } return result; } public override void MakeBodySection(ReceiptSpecRecord record) { setMeasureName(record); string nameGood = record.Name; if (record.Name.Length > 15) nameGood = record.Name.Substring(0, 15); else nameGood = record.Name.PadRight(15); //Проверка на весовой товар if (Math.Round(record.Quantity,3)-Math.Round(record.Quantity,0)!=0) Add2Strings(record.NumPos.ToString() + "." + nameGood + "", record.Price.ToString("#0.00") + "x" + record.Quantity.ToString("#0.000") + measureName + "=" + (Math.Round(record.PosSumWODisc,2)).ToString("#0.00")); else Add2Strings(record.NumPos.ToString() + "." + nameGood + "", record.Price.ToString("#0.00") + "x" + record.Quantity.ToString("#0") + measureName+ "шт=" + record.PosSumWODisc.ToString("#0.00")); } } }
using System.Collections.Generic; using System.IO; using System.Web.Routing; using Nop.Core; using Nop.Core.Plugins; using Nop.Services.Cms; using Nop.Services.Configuration; using Nop.Services.Localization; using Nop.Services.Media; namespace Nop.Plugin.Widgets.TypeProducts { /// <summary> /// PLugin /// </summary> public class TypeProductsPlugin : BasePlugin, IWidgetPlugin { private readonly IPictureService _pictureService; private readonly ISettingService _settingService; private readonly IWebHelper _webHelper; public TypeProductsPlugin(IPictureService pictureService, ISettingService settingService, IWebHelper webHelper) { this._pictureService = pictureService; this._settingService = settingService; this._webHelper = webHelper; } /// <summary> /// Gets widget zones where this widget should be rendered /// </summary> /// <returns>Widget zones</returns> public IList<string> GetWidgetZones() { return new List<string> { "home_page_top" }; } /// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "TypeProducts"; routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Widgets.TypeProducts.Controllers" }, { "area", null } }; } /// <summary> /// Gets a route for displaying widget /// </summary> /// <param name="widgetZone">Widget zone where it's displayed</param> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetDisplayWidgetRoute(string widgetZone, out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "PublicInfo"; controllerName = "TypeProducts"; routeValues = new RouteValueDictionary { {"Namespaces", "Nop.Plugin.Widgets.TypeProducts.Controllers"}, {"area", null}, {"widgetZone", widgetZone} }; } /// <summary> /// Install plugin /// </summary> public override void Install() { //pictures var sampleImagesPath = _webHelper.MapPath("~/Plugins/Widgets.TypeProducts/Content/nivoslider/sample-images/"); //settings var settings = new TypeProductsSettings { NumberOfBestsellersOnHomepage = 4, NumberOfHomePageProductOnHomepage = 4, NumberOfNewProductOnHomepage = 4, ShowBestSellerProduct=true, ShowHomePageProduct=true, ShowNewProduct=true }; _settingService.SaveSetting(settings); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture1", "Picture 1"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture2", "Picture 2"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture3", "Picture 3"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture4", "Picture 4"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture5", "Picture 5"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture", "Picture"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture.Hint", "Upload picture."); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Text", "Comment"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Text.Hint", "Enter comment for picture. Leave empty if you don't want to display any text."); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Link", "URL"); this.AddOrUpdatePluginLocaleResource("Plugins.Widgets.TypeProducts.Link.Hint", "Enter URL. Leave empty if you don't want this picture to be clickable."); base.Install(); } /// <summary> /// Uninstall plugin /// </summary> public override void Uninstall() { //settings _settingService.DeleteSetting<TypeProductsSettings>(); //locales this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture1"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture2"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture3"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture4"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture5"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Picture.Hint"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Text"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Text.Hint"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Link"); this.DeletePluginLocaleResource("Plugins.Widgets.TypeProducts.Link.Hint"); base.Uninstall(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.Configuration; namespace IdomOffice.Core.Config { public class ConfigInfo { private static string filepath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "\\ConfigFile1.json"; //public static List<ObjectInfo> list { get; set; } = new List<ObjectInfo>(); static ConfigInfo() { //SetFilePath(); bool dataexists = false; dataexists = DataExists(); if (!dataexists) { AddJson("MongoUrl", "mongodb://ivan:ivan+2017@94.23.164.152:27017/IDOM_BackOffice_Test", "System.String"); AddJson("MongoDB", "IDOM_BackOffice_Test", "System.String"); AddJson("Season", "2018", "System.Int"); AddJson("Date", "12.05.2018", "System.DateTime"); } } protected static void SetFilePath() { filepath = ConfigurationManager.AppSettings["ConfigFilePath"].ToString(); filepath= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filepath); } protected static void AddJson(string Key, string Value, string KeyType) { ObjectInfo data = new ObjectInfo(); data.Key = Key; data.Value = Value; data.KeyType = KeyType; SaveJsonToFile(data); } protected static void SaveJsonToFile(ObjectInfo info) { string content = File.ReadAllText(filepath); if (content.Length > 0) { var list = JsonConvert.DeserializeObject<List<ObjectInfo>>(content); list.Add(info); var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented); using (StreamWriter writer = new StreamWriter(filepath)) { writer.Write(convertedJson); } } else { using (StreamWriter writer = new StreamWriter(filepath)) { var list = new List<ObjectInfo>(); list.Add(info); var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented); writer.Write(convertedJson); } } } protected static bool DataExists() { bool exists = false; string content = File.ReadAllText(filepath); if(content.Length>0) { exists = true; } return exists; } protected static List<ObjectInfo> LoadJson() { List<ObjectInfo> items = new List<ObjectInfo>(); using (StreamReader r = new StreamReader(filepath)) { string json = r.ReadToEnd(); items = JsonConvert.DeserializeObject<List<ObjectInfo>>(json); } return items; } public string GetKeyType(string key) { var item = LoadJson().Find(m => m.Key == key); string itemtype = item.KeyType; return itemtype; } /* private static string GetStringValue(string value) { string data = value; return data; } private static int GetIntValue(string value) { int data = 0; data = int.Parse(value); return data; } private static DateTime GetDateValue(string value) { DateTime datevalue = DateTime.Now; datevalue = DateTime.Parse(value); return datevalue; } public static object DetermineData(Type t,string value) { string name = t.Name; object returndata = new object(); if(name=="String") { returndata = GetStringValue(value); } else if(name=="Int") { returndata = GetIntValue(value); } else if(name=="DateTime") { returndata = GetDateValue(value); } return returndata; } */ } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Text; using GameProject.UI; namespace GameProject { public class MainMenu { Texture2D background; Rectangle backgroundRec; private SpriteFont bangers; private Game game; private int gameHeight; private int gameWidth; private List<UIElement> UiElements = new List<UIElement>(); public MainMenu(Game game, SpriteFont bangers) { this.game = game; this.bangers = bangers; gameHeight = game.GraphicsDevice.Viewport.Height; gameWidth = game.GraphicsDevice.Viewport.Width; background = new Texture2D(game.GraphicsDevice, gameWidth, gameHeight); FillBackground(); backgroundRec = new Rectangle(new Point(0, 0), new Point(gameWidth, gameHeight)); CreateUIElements(); } public void Update(GameTime gameTime) { foreach (Button b in UiElements) { b.Update(gameTime); } } public void Draw(SpriteBatch spriteBatch, GameTime gameTime) { Vector2 stringSize = bangers.MeasureString("Main Menu"); spriteBatch.Draw(background, backgroundRec, Color.White); spriteBatch.DrawString(bangers, "Main Menu", new Vector2(gameWidth / 2, gameHeight / 2 - 200) - stringSize / 2, Color.White); foreach (Button b in UiElements) { b.Draw(gameTime, spriteBatch); } } private void CreateUIElements() { Vector2 stringSize; string buttonText; //Settings button buttonText = "Settings"; stringSize = bangers.MeasureString(buttonText); Action settingsAction = () => { InputManager.CurrentGameState = GameState.SettingsMenu; InputManager.PreviousGameState = GameState.MainMenu; }; Button settingsButton = new Button(settingsAction, bangers, buttonText, new Vector2(gameWidth / 2, gameHeight / 2) - stringSize / 2); UiElements.Add(settingsButton); //Back to Play button buttonText = "Play"; stringSize = bangers.MeasureString(buttonText); Action playAction = () => { InputManager.CurrentGameState = GameState.Game; InputManager.PreviousGameState = GameState.MainMenu; Time.TimeScale = 1; InputManager.IsPlaying = true; }; Button playButton = new Button(playAction, bangers, buttonText, new Vector2(gameWidth / 2, gameHeight / 2 - 50) - stringSize / 2); UiElements.Add(playButton); //Quit game Button buttonText = "Quit"; stringSize = bangers.MeasureString(buttonText); Action quitButtonAction = () => { game.Exit(); }; Button quitButton = new Button(quitButtonAction, bangers, buttonText, new Vector2(gameWidth / 2, gameHeight / 2 + 50) - stringSize / 2); UiElements.Add(quitButton); } private void FillBackground() { Color[] data = new Color[gameWidth * gameHeight]; for (int i = 0; i < data.Length; i++) data[i] = Color.YellowGreen; background.SetData(data); } } }
using System.Collections.Generic; using SuperMario.Entities; using SuperMario.Entities.BackgroundElements; using SuperMario.Entities.Blocks; using SuperMario.Entities.Enemies; using SuperMario.Entities.Items; using SuperMario.Entities.Mario; using SuperMario.Entities.Mario.CentralizedLifeSystem; using SuperMario.Entities.Mario.MarioCondition; using SuperMario.ScoreSystem; using static SuperMario.Entities.Mario.MarioStateEnum; namespace SuperMario.Collision { public class MarioCollisionHandler : ICollisionHandler { MarioEntity mario; int levelWidth = 3600; ISet<Direction> restrictedMovementDirections; public MarioCollisionHandler(MarioEntity mario) { this.mario = mario; restrictedMovementDirections = new HashSet<Direction>(); } PowerUpType GetMarioPowerType() { if (mario.CurrentConditionIsSmallCondtion()) return PowerUpType.RedMushroom; else return PowerUpType.Flower; } void EntityPastLevelBoundsRestrictDirection() { if (mario.BoundingBox.Left <= 0) restrictedMovementDirections.Add(Direction.Left); else if (mario.BoundingBox.Right >= levelWidth) restrictedMovementDirections.Add(Direction.Right); } public ISet<Direction> Collide(Entity entity, RectangleCollisions rectangleCollisions) { restrictedMovementDirections.Clear(); if (mario.CurrentMarioCondition is DeadMario) return restrictedMovementDirections; if (entity is BrickBlock brickBlock) HandleBrickBlock(brickBlock, rectangleCollisions); else if (entity is GravelBlock || entity is HitBlock || entity is ShinyBlock) HandleUnbreakableBlock(entity, rectangleCollisions); else if (entity is InvisibleBlock invisibleBlock) HandleInvisibleBlock(invisibleBlock, rectangleCollisions); else if (entity is QuestionBlock questionBlock) HandleQuestionBlock(questionBlock, rectangleCollisions); else if (entity is Goomba goomba) HandleGoomba(goomba, rectangleCollisions); else if (entity is KoopaTroopa koopaTroopa) HandleKoopa(koopaTroopa, rectangleCollisions); else if (entity is Coin coin) { coin.Obtain(); mario.DrawScorePopUp(ScoreKeeper.Instance.IncrementScore()); } else if (entity is Flower flower) HandleFlower(flower); else if (entity is Pipe) HandlePipe(entity, rectangleCollisions); else if (entity is RedMushroom redMushroom) { redMushroom.Obtain(); ScoreKeeper.Instance.IncrementScoreGetPowerUp(); mario.SetMarioConditionState(PlayerCondition.Super); } else if (entity is GreenMushroom greenMushroom) { greenMushroom.Obtain(); ScoreKeeper.Instance.IncrementScoreGetPowerUp(); CentralizedLives.Instance.GainOneLife(); } else if (entity is Star star) { star.Obtain(); ScoreKeeper.Instance.IncrementScoreGetPowerUp(); mario.SetMarioState(MarioCommands.Star); } else if (entity is ExitPipe exitPipe) { if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, exitPipe); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); if (mario.CurrentState is MarioState.MovingRight) mario.WarpBack(); } else if (entity is Flagpole flagpole) { flagpole.EndGame(); mario.StartEndGameSequence(); } else if (entity is MarioEntity marioEntity && !marioEntity.Equals(mario)) HandleMario(marioEntity, rectangleCollisions); EntityPastLevelBoundsRestrictDirection(); return restrictedMovementDirections; } void HandleBrickBlock(BrickBlock brickBlock, RectangleCollisions rectangleCollisions) { ScoreKeeper.Instance.ChainReset(); if (rectangleCollisions.Collisions.Contains(RectangleCollision.TopBottom)) { if (mario.CurrentConditionIsSmallCondtion()) brickBlock.Jiggle(); else brickBlock.Hit(GetMarioPowerType()); } else if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, brickBlock); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } void HandleUnbreakableBlock(Entity block, RectangleCollisions rectangleCollisions) { ScoreKeeper.Instance.ChainReset(); if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, block); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } void HandleInvisibleBlock(InvisibleBlock invisibleBlock, RectangleCollisions rectangleCollisions) { ScoreKeeper.Instance.ChainReset(); if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, invisibleBlock); if (rectangleCollisions.Collisions.Contains(RectangleCollision.TopBottom)) invisibleBlock.Hit(GetMarioPowerType()); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } void HandleQuestionBlock(QuestionBlock questionBlock, RectangleCollisions rectangleCollisions) { ScoreKeeper.Instance.ChainReset(); if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, questionBlock); if (rectangleCollisions.Collisions.Contains(RectangleCollision.TopBottom)) { if (!questionBlock.IsHit()) mario.DrawScorePopUp(ScoreKeeper.Instance.IncrementScore()); questionBlock.Hit(GetMarioPowerType()); } restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } void HandleGoomba(Goomba goomba, RectangleCollisions rectangleCollisions) { if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) { if (!goomba.IsHit()) { mario.EnemyHitMarioBounce(); goomba.Hit(); mario.DrawScorePopUp(ScoreKeeper.Instance.IncrementScore()); ScoreKeeper.Instance.ChainIncrement(); } } if (mario.CurrentConditionIsStarCondition()) { if (!goomba.IsHit()) { goomba.Hit(); mario.DrawScorePopUp(ScoreKeeper.Instance.IncrementScore()); ScoreKeeper.Instance.ChainIncrement(); } } if ((rectangleCollisions.Collisions.Contains(RectangleCollision.LeftRight) || rectangleCollisions.Collisions.Contains(RectangleCollision.RightLeft) || rectangleCollisions.Collisions.Contains(RectangleCollision.TopBottom)) && !goomba.IsHit()) mario.SetMarioState(MarioCommands.Hit); if (!goomba.IsHit()) restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } void HandleKoopa(KoopaTroopa koopaTroopa, RectangleCollisions rectangleCollisions) { if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) { mario.EnemyHitMarioBounce(); koopaTroopa.Hit(); mario.DrawScorePopUp(ScoreKeeper.Instance.IncrementScore()); ScoreKeeper.Instance.ChainIncrement(); } if (mario.CurrentConditionIsStarCondition()) { koopaTroopa.Hit(); mario.DrawScorePopUp(ScoreKeeper.Instance.IncrementScore()); ScoreKeeper.Instance.ChainIncrement(); } if (rectangleCollisions.Collisions.Contains(RectangleCollision.RightLeft) && koopaTroopa.IsShellState() && !koopaTroopa.IsShellHit()) koopaTroopa.ShellHit(Direction.Left); else if (rectangleCollisions.Collisions.Contains(RectangleCollision.LeftRight) && koopaTroopa.IsShellState() && !koopaTroopa.IsShellHit()) koopaTroopa.ShellHit(Direction.Right); else if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop) && koopaTroopa.IsShellState() && !koopaTroopa.IsShellHit()) koopaTroopa.ShellHit(Direction.Idle); else if ((rectangleCollisions.Collisions.Contains(RectangleCollision.LeftRight) || rectangleCollisions.Collisions.Contains(RectangleCollision.RightLeft) || rectangleCollisions.Collisions.Contains(RectangleCollision.TopBottom)) && (koopaTroopa.IsShellHit() || !koopaTroopa.IsShellState())) mario.SetMarioState(MarioCommands.Hit); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } void HandleFlower(Flower flower) { flower.Obtain(); ScoreKeeper.Instance.IncrementScoreGetPowerUp(); mario.SetMarioConditionState(PlayerCondition.Fire); } void HandlePipe(Entity pipe, RectangleCollisions rectangleCollisions) { ScoreKeeper.Instance.ChainReset(); if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, pipe); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); if (mario.CurrentState is MarioState.CrouchingLeft || mario.CurrentState is MarioState.CrouchingRight) mario.Warp(); } void HandleMario(MarioEntity otherMario, RectangleCollisions rectangleCollisions) { if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) CollisionHelper.SetEntityLocationToTopOfEntity(mario, otherMario); restrictedMovementDirections.UnionWith(BlockHelper.GetRectangleRestrictedMovement(rectangleCollisions)); } } }
using UnityEngine; public class SkyRockSpawn : MonoBehaviour { public float spawnRate; private float time = 0.0f; public GameObject skyRock; public float height; public float xBound; public float zBound; private void Update() { time += Time.deltaTime; if (spawnRate < time) { time = 0.0f; float xPos = Random.Range(-xBound, xBound); float zPos = Random.Range(-zBound, zBound); Vector3 spawnPoint = new Vector3( xPos, height, zPos ); Instantiate(skyRock, spawnPoint, new Quaternion()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Lab_6 { public partial class Face_clock : Form { public Color BackGroundColor { get; set; } public Color HourHandColor { get; set; } public Color MinuteHandColor { get; set; } public Color SecondHandColor { get; set; } Timer t = new Timer(); int WIDTH = 300, HEIGHT = 300, secHAND = 140, minHAND = 110, hrHAND = 80; // in center int cy, cx; Bitmap bmp; Graphics cg; public Face_clock() { } public Face_clock(Color BackGroundColor, Color HourHandColor, Color MinuteHandColor, Color SecondHandColor) { InitializeComponent(); this.BackGroundColor = BackGroundColor; this.HourHandColor = HourHandColor; this.MinuteHandColor = MinuteHandColor; this.SecondHandColor = SecondHandColor; // create a new bitmap bmp = new Bitmap(WIDTH + 1, HEIGHT + 1); // placing in center cx = WIDTH / 2; cy = HEIGHT / 2; //timer t.Interval = 1000; // i.e. tick in milisecond t.Tick += new EventHandler(this.t_Tick); t.Start(); } private void t_Tick(object sender, EventArgs e) { // create an image cg = Graphics.FromImage(bmp); //get time int ss = DateTime.Now.Second; int mm = DateTime.Now.Minute; int hh = DateTime.Now.Hour; int[] handCoord = new int[2]; //get time cg.Clear(BackGroundColor); //draw a circle cg.DrawEllipse(new Pen(Color.Black, 6f), 0, 0, WIDTH, HEIGHT); //draw clock numbers cg.DrawString("12", new Font("Ariel", 12), Brushes.Black, new PointF(140, 3)); cg.DrawString("1", new Font("Ariel", 12), Brushes.Black, new PointF(218, 22)); cg.DrawString("2", new Font("Ariel", 12), Brushes.Black, new PointF(263, 70)); cg.DrawString("3", new Font("Ariel", 12), Brushes.Black, new PointF(285, 140)); cg.DrawString("4", new Font("Ariel", 12), Brushes.Black, new PointF(263, 212)); cg.DrawString("5", new Font("Ariel", 12), Brushes.Black, new PointF(218, 259)); cg.DrawString("6", new Font("Ariel", 12), Brushes.Black, new PointF(142, 279)); cg.DrawString("7", new Font("Ariel", 12), Brushes.Black, new PointF(70, 259)); cg.DrawString("8", new Font("Ariel", 12), Brushes.Black, new PointF(22, 212)); cg.DrawString("9", new Font("Ariel", 12), Brushes.Black, new PointF(1, 140)); cg.DrawString("10", new Font("Ariel", 12), Brushes.Black, new PointF(22, 70)); cg.DrawString("11", new Font("Ariel", 12), Brushes.Black, new PointF(70, 22)); //draw seconds hand handCoord = msCoord(ss, secHAND); cg.DrawLine(new Pen(SecondHandColor, 2f), new Point(cx, cy), new Point(handCoord[0], handCoord[1])); //draw minutes hand handCoord = msCoord(mm, minHAND); cg.DrawLine(new Pen(MinuteHandColor, 3f), new Point(cx, cy), new Point(handCoord[0], handCoord[1])); //draw hours hand handCoord = hrCoord(hh % 12, mm, hrHAND); cg.DrawLine(new Pen(HourHandColor, 3f), new Point(cx, cy), new Point(handCoord[0], handCoord[1])); //load the bitmap image pictureBox1.Image = bmp; //display time in the heading this.Text = "Струна Виктор " + hh + ":" + mm + ":" + ss; cg.Dispose(); } private int[] msCoord(int val, int hlen) { int[] coord = new int[2]; val *= 6; // note: each minute and seconds make a 6 degree if (val >= 0 && val <= 100) { coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180)); coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180)); } else { coord[0] = cx - (int)(hlen * -Math.Sin(Math.PI * val / 180)); coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180)); } return coord; } //coord for hour private int[] hrCoord(int hval, int mval, int hlen) { int[] coord = new int[2]; //each hour makes 60 degree with min making 0.5 degree int val = (int)((hval * 30) + (mval * 0.5)); if (val >= 0 && val <= 180) { coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180)); coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180)); } else { coord[0] = cx - (int)(hlen * -Math.Sin(Math.PI * val / 180)); coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180)); } return coord; } } }
using System; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual { /// <summary> /// Representa el objeto response de Contratos - Observaciones /// </summary> /// <remarks> /// Creación : GMD 20150527 <br /> /// Modificación : <br /> /// </remarks> public class ContratoEstadioObservacionResponse { /// <summary> /// Codigo Contrato Estadio de Observacion /// </summary> public Guid CodigoContratoEstadioObservacion { get; set; } /// <summary> /// Codigo Contrato de Estadio /// </summary> public Guid CodigoContratoEstadio { get; set; } /// <summary> /// Descripcion /// </summary> public string Descripcion { get; set; } /// <summary> /// Fecha de Registro /// </summary> public string FechaRegistro { get; set; } /// <summary> /// Codigo de Parrafo /// </summary> public Guid? CodigoContratoParrafo { get; set; } /// <summary> /// Codigo de Archivo /// </summary> public int? CodigoArchivo { get; set; } /// <summary> /// Ruta Sharepoint /// </summary> public string RutaArchivoSharepoint { get; set; } /// <summary> /// Codigo Estadio de Retorno /// </summary> public Guid? CodigoEstadioRetorno { get; set; } /// <summary> /// Destinatario /// </summary> public Guid? Destinatario { get; set; } /// <summary> /// Destinatario /// </summary> public string NombreDestinatario { get; set; } /// <summary> /// Codigo Tipo Respuesta /// </summary> public string CodigoTipoRespuesta { get; set; } /// <summary> /// Nombre Tipo Respuesta /// </summary> public string NombreTipoRespuesta { get; set; } /// <summary> /// Respuesta /// </summary> public string Respuesta { get; set; } /// <summary> /// Fecha de Respuesta /// </summary> public string FechaRespuesta { get; set; } /// <summary> /// Observador /// </summary> public string Observador { get; set; } /// <summary> /// Nombre del Observador /// </summary> public string NombreObservador { get; set; } } }
namespace HandmadeHTTPServer.Data.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<HandmadeHTTPServer.Data.SharpStoreContext> { public Configuration() { this.AutomaticMigrationsEnabled = false; this.ContextKey = "HandmadeHTTPServer.Data.SharpStoreContext"; } protected override void Seed(HandmadeHTTPServer.Data.SharpStoreContext context) { } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; namespace Juicy.DirtCheapDaemons.Http { public interface IRequest { MountPoint MountPoint { get; } string VirtualPath { get; } string PostBody { get; set; } string this[string headerName] { get; set; } IDictionary<string, string> Headers { get; } IDictionary<string, string> QueryString { get; } IDictionary<string, string> Form { get; } } }
using System; namespace Backend_WebProject_API.Models { public class TodoItemModel { public string TitleHeader { get; set; } public string TaskDescription { get; set; } public string UUID { get; set; } } }
namespace App.Web.Swagger.Examples { public static class ExamplesConsts { public const string RequestId = "ade44b50-6c66-41a3-9d0d-d82518d8ff84"; public const int UserId = 42; public const string UserEmail = "foo@bar.baz"; public const string UserPassword = "1234"; public const string SessionToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using WingtipToys.Data; using WingtipToys.Models; namespace WingtipToys.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ApplicationDbContext _appDbContext; public HomeController(ILogger<HomeController> logger, ApplicationDbContext appDbContext) { _appDbContext = appDbContext; _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } public IActionResult About() { return View(); } public IActionResult Contact() { return View(); } public IQueryable<Category> GetCategories() { IQueryable<Category> query = ProductDatabaseInitializer.GetDefaultCategories().AsQueryable(); return query; } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [RequireComponent(typeof(Button))] public class StateButton : MonoBehaviour { [SerializeField] protected Button _button; [SerializeField] protected Sprite _inactiveSprite; [SerializeField] protected Sprite _activeSprite; [SerializeField] protected bool _active; public bool active { get => _active; set { _active = value; _button.image.sprite = _active ? _activeSprite : _inactiveSprite; } } public UnityEvent onClick => _button.onClick; private void Reset() { if (!_button) _button = GetComponent<Button>(); } private void OnValidate() { active = _active; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using SSISTeam9.Models; namespace SSISTeam9.DAO { public class EmployeeDAO { public static Employee GetUserPassword(string userName) { Employee employee = new Employee(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where userName = '" + userName + "'"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { employee = new Employee() { EmpId = (long)reader["empId"], DeptId = (long)reader["deptId"], EmpName = (string)reader["empName"], EmpRole = (string)reader["empRole"], EmpDisplayRole = (string)reader["empDisplayRole"], UserName = (string)reader["userName"], Password = (string)reader["password"], Email = (reader["email"] == DBNull.Value) ? null : (string)reader["email"], SessionId = (reader["sessionId"] == DBNull.Value) ? null : (string)reader["sessionId"] }; } return employee; } } public static string CreateSession(string userName) { string sessionId = Guid.NewGuid().ToString(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"Update Employee set sessionId = '" + sessionId + "'where userName ='" + userName + "'"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } return sessionId; } public static bool IsActiveSessionId(string sessionId) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"Select COUNT(*) from Employee where sessionId = '" + sessionId + "'"; SqlCommand cmd = new SqlCommand(q, conn); int count = (int)cmd.ExecuteScalar(); return (count == 1); } } public static void RemoveSession(string sessionId) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"Update Employee set sessionId = NULL where sessionId ='" + sessionId + "'"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } public static Employee GetUserBySessionId(string sessionId) { Employee employee = new Employee(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where sessionId = '" + sessionId + "'"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { employee = new Employee() { EmpId = (long)reader["empId"], DeptId = (long)reader["deptId"], EmpName = (string)reader["empName"], EmpRole = (string)reader["empRole"], EmpDisplayRole = (string)reader["empDisplayRole"], UserName = (string)reader["userName"], Password = (string)reader["password"], Email = (reader["email"] == DBNull.Value) ? null : (string)reader["email"], SessionId = (reader["sessionId"] == DBNull.Value) ? null : (string)reader["sessionId"] }; } return employee; } } public static Employee GetDeptHeadByDeptId(long deptId) { Employee employee = new Employee(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where empRole = 'HEAD' and deptId = @deptId"; SqlCommand cmd = new SqlCommand(q, conn); cmd.Parameters.AddWithValue("@deptId", deptId); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { employee = new Employee() { Email = (reader["email"] == DBNull.Value) ? null : (string)reader["email"], }; } return employee; } } public static Employee GetRepByDeptId(long deptId) { Employee employee = new Employee(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where empRole = 'REPRESENTATIVE' and deptId = @deptId"; SqlCommand cmd = new SqlCommand(q, conn); cmd.Parameters.AddWithValue("@deptId", deptId); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { employee = new Employee() { Email = (reader["email"] == DBNull.Value) ? null : (string)reader["email"], }; } return employee; } } public static Employee GetEmployeeById(long empId) { Employee employee = new Employee(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where empId = '" + empId + "'"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { employee = new Employee() { EmpId = (long)reader["empId"], DeptId = (long)reader["deptId"], EmpName = (string)reader["empName"], EmpRole = (string)reader["empRole"], EmpDisplayRole = (string)reader["empDisplayRole"], UserName = (string)reader["userName"], Password = (string)reader["password"], Email = (reader["email"] == DBNull.Value) ? null : (string)reader["email"], SessionId = (reader["sessionId"] == DBNull.Value) ? null : (string)reader["sessionId"] }; } return employee; } } public static List<Employee> GetEmployeeByRole(string role) { List<Employee> employees = new List<Employee>(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where empRole = '" + role + "'"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Employee employee = new Employee() { EmpId = (long)reader["empId"], DeptId = (long)reader["deptId"], EmpName = (string)reader["empName"], EmpRole = (string)reader["empRole"], EmpDisplayRole = (string)reader["empDisplayRole"], UserName = (string)reader["userName"], Password = (string)reader["password"], Email = (reader["email"] == DBNull.Value) ? null : (string)reader["email"], SessionId = (reader["sessionId"] == DBNull.Value) ? null : (string)reader["sessionId"] }; employees.Add(employee); } return employees; } } public static void UpdateEmployeeRoleById(long newRep,long currentRep) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string qq = @"Update Employee Set empRole='EMPLOYEE',empDisplayRole='EMPLOYEE' where empId =" + currentRep; SqlCommand cmd = new SqlCommand(qq, conn); cmd.ExecuteNonQuery(); string q = @"Update Employee Set empRole='REPRESENTATIVE',empDisplayRole='REPRESENTATIVE' where empId =" + newRep; SqlCommand cmd1 = new SqlCommand(q, conn); cmd1.ExecuteNonQuery(); } } public static void UpdateEmployeeHead(long newHead, long currentHead) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string qq = @"Update Employee Set empRole='EMPLOYEE' where empId =" + currentHead; SqlCommand cmd = new SqlCommand(qq, conn); cmd.ExecuteNonQuery(); string q = @"Update Employee Set empRole='HEAD' where empId =" + newHead; SqlCommand cmd1 = new SqlCommand(q, conn); cmd1.ExecuteNonQuery(); } } public static void ChangeEmployeeRoles(long deptId) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string qq = @"Update Employee Set empRole='HEAD' where empDisplayRole='HEAD' and empRole='EMPLOYEE'"; SqlCommand cmd = new SqlCommand(qq, conn); cmd.ExecuteNonQuery(); string q = @"Update Employee Set empRole='EMPLOYEE' where empDisplayRole='EMPLOYEE' and empRole='HEAD'"; SqlCommand cmd1 = new SqlCommand(q, conn); cmd1.ExecuteNonQuery(); } } public static List<Employee> GetEmployeesByIdList(List<long> empIds) { if(null == empIds || empIds.Count == 0) { return new List<Employee>(); } using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where empId IN ({0})"; var parms = empIds.Select((s, i) => "@id" + i.ToString()).ToArray(); var inclause = string.Join(",", parms); string sql = string.Format(q, inclause); Console.Write(sql); SqlCommand cmd = new SqlCommand(sql, conn); for(var i=0; i<parms.Length; i++) { cmd.Parameters.AddWithValue(parms[i], empIds[i]); } Employee employee = null; List<Employee> employees = new List<Employee>(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Department d = new Department() { DeptId = (long)reader["deptId"] }; employee = new Employee() { EmpId = (long)reader["empId"], EmpName = (string)reader["empName"], EmpRole = (string)reader["empRole"], EmpDisplayRole = (string)reader["empDisplayRole"], UserName = (string)reader["userName"], Password = (string)reader["password"], Department = d }; employees.Add(employee); } return employees; } } public static List<Employee> GetEmployeesByDepartment(long deptId) { List<Employee> employees = new List<Employee>(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Employee where deptId="+deptId; Employee employee = null; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Department d = new Department() { DeptId = (long)reader["deptId"] }; employee = new Employee() { EmpId = (long)reader["empId"], EmpName = (string)reader["empName"], EmpRole = (string)reader["empRole"], EmpDisplayRole = (string)reader["empDisplayRole"], UserName = (string)reader["userName"], Password = (string)reader["password"], Department = d }; employees.Add(employee); } } return employees; } public static List<string> GetAllEmployeeNames() { List<string> employeeNames = new List<string>(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT DISTINCT empName from Employee"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string employeeName = (string)reader["empName"]; employeeNames.Add(employeeName); } } return employeeNames; } public static string GetUserEmail (long empId) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT email from Employee where empId = '" + empId + "'"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); string email = null; if (reader.Read()) { email = (reader["email"] == DBNull.Value) ? "team9rockz@gmail.com" : (string)reader["email"]; } return email; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameLobby : MonoBehaviour { public List<GameObject> rowLables = new List<GameObject> (); public List<GameObject> typeSelectBoxes = new List<GameObject> (); public List<GameObject> factionSelectBoxes = new List<GameObject> (); public List<GameObject> teamSelectBoxes = new List<GameObject> (); public GameObject startingResources; // Use this for initialization void Start () { SetupSelectBoxes (4); // TODO: In the future when multiple maps are supported we will adjust this value } /// <summary> /// Sets up select boxes so they line up with the selected map /// </summary> /// <param name="numPlayers">Number players.</param> private void SetupSelectBoxes(int numPlayers) { for (int i = 0; i < typeSelectBoxes.Count; i++) { if (i < numPlayers) { typeSelectBoxes [i].SetActive (true); factionSelectBoxes [i].SetActive (true); teamSelectBoxes [i].SetActive (true); rowLables [i].SetActive (true); } else { typeSelectBoxes [i].SetActive (false); factionSelectBoxes [i].SetActive (false); teamSelectBoxes [i].SetActive (false); rowLables [i].SetActive (false); } } } /// <summary> /// Starts a new game passing in the required setup information /// </summary> public void StartGame() { string compressedData = ""; for (int i = 0; i < typeSelectBoxes.Count; i++) { if (typeSelectBoxes [i].activeSelf) { compressedData += typeSelectBoxes [i].GetComponent<UnityEngine.UI.Dropdown> ().value + ","; compressedData += factionSelectBoxes [i].GetComponent<UnityEngine.UI.Dropdown> ().value + ","; compressedData += teamSelectBoxes [i].GetComponent<UnityEngine.UI.Dropdown> ().value + ";"; } } compressedData += startingResources.GetComponent<UnityEngine.UI.Dropdown> ().value; PlayerPrefs.SetString ("LastLevelSetup", compressedData); PlayerPrefs.Save (); PlayerPrefs.SetString ("NewLevelData", compressedData); SceneManager.LoadScene ("DesolationFields"); } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.App.Asset.Refunds.Domain.Enums { /// <summary> /// 提现转账 状态 /// </summary> [ClassProperty(Name = "提现转账状态")] public enum RefundStatus { /// <summary> /// 待处理 /// </summary> [Display(Name = "待处理")] [LabelCssClass(BadgeColorCalss.Primary)] Pending = 1, /// <summary> /// 等待审核 /// </summary> [Display(Name = "初审成功")] [LabelCssClass(BadgeColorCalss.Success)] FirstCheckSuccess = 2, ///// <summary> /////管理员审核成功 /////提现的两种操作 ///// </summary> //[Display(Name = "管理员审核成功")] //[LabelCssClass(BadgeColorCalss.Success)] //AdminCheckSuccess = 3, /// <summary> /// 失败 /// </summary> [Display(Name = "失败")] [LabelCssClass(BadgeColorCalss.Danger)] Failured = 5, /// <summary> /// 付款成功 /// </summary> [Display(Name = "付款成功")] [LabelCssClass(BadgeColorCalss.Success)] Success = 6 } }
 public enum InitOrder { Default, Maze, MazeCellManager, PathToGoalManager, PhotonConfiguration, PhotonMovement, PhotonCollision, PhotonAnimation, CameraConfiguration, CameraController, DirectionalLight, Arrow }
#region MIT License /* * Copyright (c) 2009 University of Jyväskylä, Department of Mathematical * Information Technology. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion /* * Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen. */ using Keys = Silk.NET.Input.Key; namespace Jypeli { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member /// <summary> /// Näppäimistön näppäin. /// </summary> public enum Key { None = Keys.Unknown, Back = Keys.Backspace, Tab = Keys.Tab, Enter = Keys.Enter, Pause = Keys.Pause, CapsLock = Keys.CapsLock, Escape = Keys.Escape, Space = Keys.Space, PageUp = Keys.PageUp, PageDown = Keys.PageDown, End = Keys.End, Home = Keys.Home, Left = Keys.Left, Up = Keys.Up, Right = Keys.Right, Down = Keys.Down, PrintScreen = Keys.PrintScreen, Insert = Keys.Insert, Delete = Keys.Delete, D0 = Keys.Number0, D1 = Keys.Number1, D2 = Keys.Number2, D3 = Keys.Number3, D4 = Keys.Number4, D5 = Keys.Number5, D6 = Keys.Number6, D7 = Keys.Number7, D8 = Keys.Number8, D9 = Keys.Number9, A = Keys.A, B = Keys.B, C = Keys.C, D = Keys.D, E = Keys.E, F = Keys.F, G = Keys.G, H = Keys.H, I = Keys.I, J = Keys.J, K = Keys.K, L = Keys.L, M = Keys.M, N = Keys.N, O = Keys.O, P = Keys.P, Q = Keys.Q, R = Keys.R, S = Keys.S, T = Keys.T, U = Keys.U, V = Keys.V, W = Keys.W, X = Keys.X, Y = Keys.Y, Z = Keys.Z, Å = Keys.LeftBracket, Ä = Keys.Apostrophe, Ö = Keys.Semicolon, NumPad0 = Keys.Keypad0, NumPad1 = Keys.Keypad1, NumPad2 = Keys.Keypad2, NumPad3 = Keys.Keypad3, NumPad4 = Keys.Keypad4, NumPad5 = Keys.Keypad5, NumPad6 = Keys.Keypad6, NumPad7 = Keys.Keypad7, NumPad8 = Keys.Keypad8, NumPad9 = Keys.Keypad9, Multiply = Keys.KeypadMultiply, Add = Keys.KeypadAdd, //Separator = Keys.Separator, TODO: Mikä tää on? Subtract = Keys.KeypadSubtract, Decimal = Keys.KeypadDecimal, Divide = Keys.KeypadDivide, F1 = Keys.F1, F2 = Keys.F2, F3 = Keys.F3, F4 = Keys.F4, F5 = Keys.F5, F6 = Keys.F6, F7 = Keys.F7, F8 = Keys.F8, F9 = Keys.F9, F10 = Keys.F10, F11 = Keys.F11, F12 = Keys.F12, F13 = Keys.F13, F14 = Keys.F14, F15 = Keys.F15, F16 = Keys.F16, F17 = Keys.F17, F18 = Keys.F18, F19 = Keys.F19, F20 = Keys.F20, F21 = Keys.F21, F22 = Keys.F22, F23 = Keys.F23, F24 = Keys.F24, NumLock = Keys.NumLock, Scroll = Keys.ScrollLock, LeftShift = Keys.ShiftLeft, RightShift = Keys.ShiftRight, LeftControl = Keys.ControlLeft, RightControl = Keys.ControlRight, LeftAlt = Keys.AltLeft, RightAlt = Keys.AltRight, //Ouml = Keys.OemTilde, //Auml = Keys.OemQuotes, //TODO: Entä nää? LessOrGreater = Keys.World2, Period = Keys.Period, Comma = Keys.Comma, } }
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace CustomXamarinControls { public class CurrencyEntry : Entry { public bool ShouldReactToTextChange { get; set; } public double Decimal; protected override void OnPropertyChanged(string propertyName = null) { if (nameof(this.Text).Equals(propertyName)) { if (double.TryParse(this.Text, out Decimal)) { if ((Decimal % 1) == 0) { this.Text = $"{Decimal:C0}"; } else { this.Text = $"{Decimal:C}"; } } } base.OnPropertyChanged(propertyName); } } }
using System; using System.Collections; using System.Collections.Generic; namespace Cwiczenia { internal class Llista<T> : IEnumerable<T>, IEnumerable { private T[] array = new T[100]; private int lenght = 0; public void Add(T args) { array[lenght++] = args; } public void Remove(T args) { bool found = false; int index = 0; foreach (T item in array) { if (!found && item.Equals(args)) { found = true; } if (found && index + 1 < lenght) { array[index] = array[index + 1]; } index++; } lenght--; } public int Count() { return lenght; } public void AddRange(T[] args) { foreach (T item in args) { Add(item); } } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < lenght; i++) { yield return array[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
namespace ArrayManipulator { using System; using System.Linq; public class StartUp { public static void Main() { var numbers = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); var input = Console.ReadLine(); while (input != "print") { var commandLine = input .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); var command = commandLine[0]; switch (command) { case "add": { var index = int.Parse(commandLine[1]); var number = int.Parse(commandLine[2]); numbers.Insert(index, number); } break; case "addMany": { var index = int.Parse(commandLine[1]); var numsList = commandLine.Skip(2).Take(commandLine.Length).Select(int.Parse).ToList(); numbers.InsertRange(index, numsList); } break; case "contains": { var number = int.Parse(commandLine[1]); Console.WriteLine(numbers.IndexOf(number)); } break; case "remove": { var index = int.Parse(commandLine[1]); numbers.RemoveAt(index); } break; case "shift": { var possition = int.Parse(commandLine[1]); for (int i = 0; i < possition; i++) { var number = numbers[0]; numbers.RemoveAt(0); numbers.Add(number); } } break; case "sumPairs": { for (int i = 0; i < numbers.Count - 1; i++) { numbers[i] += numbers[i + 1]; numbers.RemoveAt(i + 1); } } break; } input = Console.ReadLine(); } Console.WriteLine($"[{string.Join(", ", numbers)}]"); } } }
using System; using System.IO; using System.Net; using System.Threading.Tasks; using Android.Content; using Explayer.Droid.Services; using Explayer.Services; using System.IO.Compression; using Java.Util.Zip; using Xamarin.Forms; [assembly: Dependency(typeof(HandleStaticFilesService))] namespace Explayer.Droid.Services { public class HandleStaticFilesService : AbstractHandleStaticFilesService { private static Context _context; public static void Init(Context context) { _context = context; } public override string DirectoryPath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), "static"); protected override Task LoadHtmlFromResource() { var tcs = new TaskCompletionSource<object>(); Task.Factory.StartNew(() => { //delete old folder if exists if (Directory.Exists(DirectoryPath)) { Directory.Delete(DirectoryPath, true); } //load all files in Assets to an HTML folder try { SyncAssets("static", Environment.GetFolderPath( Environment.SpecialFolder.Personal) + "/"); } catch (Exception e) { tcs.SetException(e); return; } tcs.SetResult(null); }); return tcs.Task; } /*protected override async Task<string> DownloadZipFile(string zipName) { string zipName = "stimuli-v1.0.0.zip"; var zipUrl = "https://static.isearchlab.org/explayer/apps/" + zipName; using (var client = new WebClient()) { var zipPath = Path.Combine(DirectoryPath, zipName); await client.DownloadFileTaskAsync(zipUrl, zipPath); System.IO.Compression. } }*/ private static void SyncAssets(string assetFolder, string targetDir) { if (_context == null) throw new NullReferenceException("Class has not been initialized"); var slash = (assetFolder == "" ? "" : "/"); var assets = _context.Assets.List(assetFolder); foreach (var asset in assets) { var subAssets = _context.Assets.List(assetFolder + slash + asset); // if it has a length, it's a folder if (subAssets.Length > 0) { SyncAssets(assetFolder + slash + asset, targetDir); } else { // it's a file using (var source = _context.Assets.Open(assetFolder + slash + asset)) { if (!Directory.Exists(targetDir + assetFolder)) { Directory.CreateDirectory(targetDir + assetFolder); } using (var dest = File.Create(targetDir + assetFolder + slash + asset)) { Console.WriteLine("Copying '" + assetFolder + slash + asset + "' to '" + targetDir + assetFolder + slash + asset + "'"); source.CopyTo(dest); } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Hacer un programa que pida por pantalla la fecha de nacimiento de una persona (día, mes y año) y calcule el número de días vividos por esa persona hasta la fecha actual (tomar la fecha del sistema con DateTime.Now). Nota: Utilizar estructuras selectivas. Tener en cuenta los años bisiestos. namespace Ejercicio_07 { class Ejercicio_07 { static void Main(string[] args) { Console.Title = "Ejercicio 07"; Console.Write("Ingrese dia de nacimiento: "); int.TryParse(Console.ReadLine(), out int dia); Console.Write("Ingrese mes de nacimiento: "); int.TryParse(Console.ReadLine(), out int mes); Console.Write("Ingrese anio de nacimiento: "); int.TryParse(Console.ReadLine(), out int anio); DateTime nacimiento = new DateTime(anio, mes, dia); DateTime now = DateTime.Now; Console.WriteLine("Tu nacimiento es el dia {0}",nacimiento); Console.WriteLine("La fecha de hoy es {0}",now); int diasVividos = 0; for (; nacimiento < now; nacimiento = nacimiento.AddDays(1.0))//adddays agrega de a un dia { diasVividos++; } Console.WriteLine("Viviste: {0} dias", diasVividos); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CPClient.Service.Model { public class ClienteEnderecoModel { [Key] public int Id { get; set; } public string Logradouro { get; set; } public string Numero { get; set; } public string Complemento { get; set; } public string Bairro { get; set; } public string CidadeUf { get; set; } public int CEP { get; set; } public int EnderecoTipoId { get; set; } public bool Ativo { get; set; } } }
using System.Collections.Generic; using System.Linq; using DFC.ServiceTaxonomy.GraphSync.Interfaces; using DFC.ServiceTaxonomy.GraphSync.JsonConverters; using Newtonsoft.Json; namespace DFC.ServiceTaxonomy.GraphSync.Models { [JsonConverter(typeof(SubgraphConverter))] public class Subgraph : ISubgraph { //todo: immutable, with non-nullable sourcenode? public INode? SourceNode { get; set; } public HashSet<INode> Nodes { get; } public HashSet<IRelationship> Relationships { get; } private IRelationship[]? _outgoingRelationships; private IRelationship[]? _incomingRelationships; public Subgraph() { SourceNode = null; Nodes = new HashSet<INode>(); Relationships = new HashSet<IRelationship>(); } public Subgraph(IEnumerable<INode> nodes, IEnumerable<IRelationship> relationships, INode? sourceNode = null) { Nodes = new HashSet<INode>(nodes); Relationships = new HashSet<IRelationship>(relationships); SourceNode = sourceNode; } public void Add(ISubgraph subgraph) { Nodes.UnionWith(subgraph.Nodes); Relationships.UnionWith(subgraph.Relationships); // options: // use SourceNode from new Subgraph // keep original SourceNode // validate both same (& throw if not) // set to null if different SourceNode = subgraph.SourceNode; } public IEnumerable<IRelationship> OutgoingRelationships { get { if (_outgoingRelationships != null) return _outgoingRelationships; //todo: null SourceNode return _outgoingRelationships = Relationships .Where(r => r.StartNodeId == SourceNode!.Id) .ToArray(); } } public IEnumerable<IRelationship> IncomingRelationships { get { if (_incomingRelationships != null) return _incomingRelationships; //todo: null SourceNode return _incomingRelationships = Relationships .Where(r => r.EndNodeId == SourceNode!.Id) .ToArray(); } } } }
namespace SFA.DAS.ProviderCommitments.Web.Models.Cohort { public class FileUploadValidateErrorRequest { public long ProviderId { get; set; } public string CachedErrorGuid { get; set; } } }
using gView.Framework.Carto; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.system; namespace gView.Framework.Symbology { public interface ISymbol : IPersistable, IClone, IClone2, ILegendItem { void Draw(IDisplay display, IGeometry geometry); string Name { get; } SymbolSmoothing SymbolSmothingMode { set; } bool SupportsGeometryType(GeometryType type); bool RequireClone(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Dapper; using DapperExtensions; using ReactMusicStore.Core.Domain.Entities; using ReactMusicStore.Core.Domain.Interfaces.Repository.ReadOnly; namespace ReactMusicStore.Core.Data.Repository.Dapper { public class OrderDapperRepository : Common.Repository , IOrderReadOnlyRepository { public Order Get(int id) { using (var cn = MusicStoreConnection) { var order = cn.Query<Order> ("SELECT * " + " FROM Order O" + " WHERE C.OrderId = @OrderId", new {CartId = id}) .FirstOrDefault(); return order; } } public IEnumerable<Order> All() { using (var cn = MusicStoreConnection) { var orders = cn.Query<Order>("SELECT * FROM Order C").ToList(); return orders; } } public IEnumerable<Order> Find(Expression<Func<Order, bool>> predicate) { using (var cn = MusicStoreConnection) { var orders = cn.GetList<Order>(predicate); return orders; } } } }
using System; using Hayaa.BaseModel; using Hayaa.CacheKeyStatic; using Hayaa.Common; using Hayaa.UserAuth.Service.Core.DataAccess; namespace Hayaa.UserAuth.Service.Core { public class UserAuthoServer : IUserAuthoService { public FunctionOpenResult<string> CompanyUserLogin(string loginKey, string pwd, string sessionKey) { FunctionOpenResult<string> result = new FunctionOpenResult<string>() { ActionResult=true }; //获取会话数据 UserSession userSession = UserSessionDal.Get(sessionKey); int sessionId = (userSession==null)?0:userSession.SessionId; //先检查失败次数 LoginAudit loginAudit =(sessionId>0)? LoginAuditDal.Get(sessionId): LoginAuditDal.Add(new LoginAudit()); if ((loginAudit != null) && (loginAudit.FailTotal >= 3)) { result.ActionResult = false; result.ErrorMsg = "密码错误太多"; result.ErrorCode = ErrorCode.PwdAttack; return result; } //验证口令 UserSession loginSession= CompanyLoginDal.Get(loginKey, pwd); if (loginSession == null) loginSession = new UserSession(); loginSession.SessionKey = sessionKey; if (loginSession.UserId > 0) { loginSession.Status = 1; loginSession.SessionId=UserSessionDal.Add(loginSession); userSession = loginSession; //添加会话缓存 RedisComponent.SaveCache<UserSession>(String.Format(UserAuthorityCacheKey.AuthorityCacheKey, sessionKey), loginSession); result.Data = loginSession.SessionKey; } else { loginAudit.FailTotal++; result.ActionResult = false; result.ErrorMsg = "验证未通过"; result.ErrorCode = ErrorCode.LoginFail; } if (userSession == null) { loginSession.Status = 1; UserSessionDal.Add(loginSession); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CEMAPI.Models; using Rotativa.Options; using System.Web.Hosting; using System.Text.RegularExpressions; using System.IO; using CEMAPI.BAL; using Newtonsoft.Json.Linq; using System.Web.Configuration; using CEMAPI.DAL; using System.Net.Http; using System.Net.Mail; using System.Reflection; using DMSUploadDownload; using System.Globalization; namespace CEMAPI.Controllers { public class GeneratePDFController : Controller { TETechuvaDBContext context = new TETechuvaDBContext(); CollectionManangementController collMgmtCtrl = new CollectionManangementController(); NotificationHistoryBAL Notif_Hist_BAL = new NotificationHistoryBAL(); InvoiceBAL invBAL = new InvoiceBAL(); RecordExceptions exc = new RecordExceptions(); CEMEmailControllerBal cememail = new CEMEmailControllerBal(); public const string emailBodyValue = "<p>FYI, Hereby i am attaching a file please find the attachment.</p>"; public GeneratePDFController() { context.Configuration.ProxyCreationEnabled = true; } // GET: GeneratePDF public ActionResult Index() { return View(); } public string DailyInvoicePDF(string id) { string result = string.Empty; int tempInvId = Convert.ToInt32(id); int authUser = 0; var re = Request; var headers = re.Headers; authUser = Convert.ToInt32(headers.GetValues("authUser").First()); var actionResult = new Rotativa.ActionAsPdf("DailyInvoicePDFView", new { id = id }) //some route values) { FileName = "Test.pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10,Top=2 }, // PageWidth = 185, // PageHeight = 245 }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); string base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); try { var soaDtoObj = (from invo in context.TEInvoices join ofr in context.TEOffers on invo.ContextID equals ofr.OfferID join prjct in context.TEProjects on ofr.ProjectID equals prjct.ProjectID join compny in context.TECompanies on prjct.CompanyID equals compny.Uniqueid join unit in context.TEUnits on ofr.UnitID equals unit.UnitID where invo.InVoiceID == tempInvId select new { prjct.ProjectCode, prjct.ProjectColor, prjct.ProjectName, prjct.Logo, compny.CompanyCode, compny.Name, compny.CIN, compny.PAN, compny.Address, unit.UnitNumber, invo.SAPCustomerID, ofr.OfferCustomerName }).FirstOrDefault(); if (soaDtoObj != null) collMgmtCtrl.UploadDocument(base64String, "Customer-Invoice", "Customer-Invoice", soaDtoObj.ProjectName, soaDtoObj.OfferCustomerName, soaDtoObj.UnitNumber, authUser, soaDtoObj.SAPCustomerID, tempInvId, soaDtoObj.SAPCustomerID, ""); } catch (Exception ex) { } return base64String; } public ActionResult DailyInvoicePDFView(string id) { var template = context.TEEmailTemplates.Where(a => a.ModuleName.Contains("DAILY INVOICE")).FirstOrDefault(); string finalTemplate = string.Empty; if (template != null) finalTemplate = template.EmailTemplate; InvoiceBrkupDtlDTO outInvDTO = new InvoiceBrkupDtlDTO(); outInvDTO = new InvoiceDAL().GetInvoiceBreakupByInvoiceId(Convert.ToInt32(id)); string url = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; if (outInvDTO != null) { finalTemplate = finalTemplate.Replace("#CompanyName", outInvDTO.CompanyName); string AmountInWords = invBAL.NumberToWords(Convert.ToInt64(outInvDTO.TotalAmount)); finalTemplate = finalTemplate.Replace("#TotalAmntInWords", AmountInWords); finalTemplate = finalTemplate.Replace("#CompanyAddress", outInvDTO.CompanyAddress); finalTemplate = finalTemplate.Replace("#CompanyCIN", outInvDTO.CompanyCIN); finalTemplate = finalTemplate.Replace("#CompanyTAN", ""); finalTemplate = finalTemplate.Replace("#CompanyPAN", ""); finalTemplate = finalTemplate.Replace("#PF_Reg_No", outInvDTO.ServiceTagReg); finalTemplate = finalTemplate.Replace("#CustomerName", outInvDTO.CustomerName); finalTemplate = finalTemplate.Replace("#server_folder", "http://" + url + "/portfolio/"); finalTemplate = finalTemplate.Replace("#ProjectLogo", outInvDTO.ProjectLogo); finalTemplate = finalTemplate.Replace("#InvoiceId", outInvDTO.InvoiceId); finalTemplate = finalTemplate.Replace("#ServiceTaxRegNo", ""); finalTemplate = finalTemplate.Replace("#MilestoneName", outInvDTO.MilestoneName); finalTemplate = finalTemplate.Replace("#ProjectName", outInvDTO.ProjectName); if (outInvDTO.InvoiceDate != null) finalTemplate = finalTemplate.Replace("#InvoiceDate", outInvDTO.InvoiceDate.Value.ToShortDateString()); else finalTemplate = finalTemplate.Replace("#InvoiceDate", ""); if (outInvDTO.MilestoneCompletionDate != null) finalTemplate = finalTemplate.Replace("#MilestoneCompletionDate", outInvDTO.MilestoneCompletionDate.Value.ToShortDateString()); else finalTemplate = finalTemplate.Replace("#MilestoneCompletionDate", ""); finalTemplate = finalTemplate.Replace("#UnitNumber", outInvDTO.UnitNumber); if (outInvDTO.TowardsLand != null) finalTemplate = finalTemplate.Replace("#TowardsLand", outInvDTO.TowardsLand.ToString()); else finalTemplate = finalTemplate.Replace("#TowardsLand", ""); if (outInvDTO.LandServiceTax != null) finalTemplate = finalTemplate.Replace("#LandServiceTax", outInvDTO.LandServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#LandServiceTax", ""); if (outInvDTO.TotalConsideration != null) finalTemplate = finalTemplate.Replace("#TotalConsideration", outInvDTO.TotalConsideration.ToString()); else finalTemplate = finalTemplate.Replace("#TotalConsideration", ""); if (outInvDTO.LandSBC != null) finalTemplate = finalTemplate.Replace("#LandSBC", outInvDTO.LandSBC.ToString()); else finalTemplate = finalTemplate.Replace("#LandSBC", ""); if (outInvDTO.LandKKC != null) finalTemplate = finalTemplate.Replace("#LandKKC", outInvDTO.LandKKC.ToString()); else finalTemplate = finalTemplate.Replace("#LandKKC", ""); if (outInvDTO.LandVAT != null) finalTemplate = finalTemplate.Replace("#LandVAT", outInvDTO.LandVAT.ToString()); else finalTemplate = finalTemplate.Replace("#LandVAT", ""); if (outInvDTO.LandTotalTax != null) finalTemplate = finalTemplate.Replace("#LandTotalTax", outInvDTO.LandTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#LandTotalTax", ""); if (outInvDTO.LandTotalAmount != null) finalTemplate = finalTemplate.Replace("#LandTotalAmount", outInvDTO.LandTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#LandTotalAmount", ""); if (outInvDTO.TowardsConstn != null) finalTemplate = finalTemplate.Replace("#TowardsConstn", outInvDTO.TowardsConstn.ToString()); else finalTemplate = finalTemplate.Replace("#TowardsConstn", ""); if (outInvDTO.TotalServiceTax != null) finalTemplate = finalTemplate.Replace("#TotalServiceTax", outInvDTO.TotalServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#TotalServiceTax", ""); if (outInvDTO.ConstnServiceTax != null) finalTemplate = finalTemplate.Replace("#ConstnServiceTax", outInvDTO.ConstnServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnServiceTax", ""); if (outInvDTO.TowardsConstn != null) finalTemplate = finalTemplate.Replace("#TowardsConstn", outInvDTO.TowardsConstn.ToString()); else finalTemplate = finalTemplate.Replace("#TowardsConstn", ""); if (outInvDTO.ConstnVatableComponent != null) finalTemplate = finalTemplate.Replace("#ConstnVatableComponent", outInvDTO.ConstnVatableComponent.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnVatableComponent", ""); if (outInvDTO.OtherChargTotalTax != null) finalTemplate = finalTemplate.Replace("#OtherChargTotalTax", outInvDTO.OtherChargTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#OtherChargTotalTax", ""); if (outInvDTO.ConstnSBC != null) finalTemplate = finalTemplate.Replace("#ConstnSBC", outInvDTO.ConstnSBC.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnSBC", ""); if (outInvDTO.ConstnKKC != null) finalTemplate = finalTemplate.Replace("#ConstnKKC", outInvDTO.ConstnKKC.ToString()); else finalTemplate = finalTemplate.Replace("#TowardsLand", ""); if (outInvDTO.ConstnVAT != null) finalTemplate = finalTemplate.Replace("#ConstnVAT", outInvDTO.ConstnVAT.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnVAT", ""); if (outInvDTO.ConstnTotalTax != null) finalTemplate = finalTemplate.Replace("#ConstnTotalTax", outInvDTO.ConstnTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnTotalTax", ""); if (outInvDTO.ConstnTotalAmount != null) finalTemplate = finalTemplate.Replace("#ConstnTotalAmount", outInvDTO.ConstnTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnTotalAmount", ""); if (outInvDTO.ConstnNonVatableComponent != null) finalTemplate = finalTemplate.Replace("#ConstnNonVatableComponent", outInvDTO.ConstnNonVatableComponent.ToString()); else finalTemplate = finalTemplate.Replace("#ConstnNonVatableComponent", ""); if (outInvDTO.TowardsMaintn != null) finalTemplate = finalTemplate.Replace("#TowardsMaintn", outInvDTO.TowardsMaintn.ToString()); else finalTemplate = finalTemplate.Replace("#TowardsMaintn", ""); if (outInvDTO.MaintnServiceTax != null) finalTemplate = finalTemplate.Replace("#MaintnServiceTax", outInvDTO.MaintnServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#MaintnServiceTax", ""); if (outInvDTO.MaintnSBC != null) finalTemplate = finalTemplate.Replace("#MaintnSBC", outInvDTO.MaintnSBC.ToString()); else finalTemplate = finalTemplate.Replace("#MaintnSBC", ""); if (outInvDTO.MaintnKKC != null) finalTemplate = finalTemplate.Replace("#MaintnKKC", outInvDTO.MaintnKKC.ToString()); else finalTemplate = finalTemplate.Replace("#MaintnKKC", ""); if (outInvDTO.MaintnVAT != null) finalTemplate = finalTemplate.Replace("#MaintnVAT", outInvDTO.MaintnVAT.ToString()); else finalTemplate = finalTemplate.Replace("#MaintnVAT", ""); if (outInvDTO.MaintnTotalTax != null) finalTemplate = finalTemplate.Replace("#MaintnTotalTax", outInvDTO.MaintnTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#MaintnTotalTax", ""); if (outInvDTO.MaintnTotalAmount != null) finalTemplate = finalTemplate.Replace("#MaintnTotalAmount", outInvDTO.MaintnTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#MaintnTotalAmount", ""); if (outInvDTO.OtherCharges != null) finalTemplate = finalTemplate.Replace("#OtherCharges", outInvDTO.OtherCharges.ToString()); else finalTemplate = finalTemplate.Replace("#OtherCharges", ""); if (outInvDTO.OtherChargServiceTax != null) finalTemplate = finalTemplate.Replace("#OtherChargServiceTax", outInvDTO.OtherChargServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#OtherChargServiceTax", ""); if (outInvDTO.OtherChargSBC != null) finalTemplate = finalTemplate.Replace("#OtherChargSBC", outInvDTO.OtherChargSBC.ToString()); else finalTemplate = finalTemplate.Replace("#OtherChargSBC", ""); if (outInvDTO.OtherChargKKC != null) finalTemplate = finalTemplate.Replace("#OtherChargKKC", outInvDTO.OtherChargKKC.ToString()); else finalTemplate = finalTemplate.Replace("#OtherChargKKC", ""); if (outInvDTO.OtherChargVAT != null) finalTemplate = finalTemplate.Replace("#OtherChargVAT", outInvDTO.OtherChargVAT.ToString()); else finalTemplate = finalTemplate.Replace("#OtherChargVAT", ""); if (outInvDTO.OtherChargTotalAmount != null) finalTemplate = finalTemplate.Replace("#OtherChargTotalAmount", outInvDTO.OtherChargTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#OtherChargTotalAmount", ""); if (outInvDTO.Reimbursements != null) finalTemplate = finalTemplate.Replace("#Reimbursements", outInvDTO.Reimbursements.ToString()); else finalTemplate = finalTemplate.Replace("#Reimbursements", ""); if (outInvDTO.ReimbServiceTax != null) finalTemplate = finalTemplate.Replace("#ReimbServiceTax", outInvDTO.ReimbServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#ReimbServiceTax", ""); if (outInvDTO.ReimbSBC != null) finalTemplate = finalTemplate.Replace("#ReimbSBC", outInvDTO.ReimbSBC.ToString()); else finalTemplate = finalTemplate.Replace("#ReimbSBC", ""); if (outInvDTO.ReimbKKC != null) finalTemplate = finalTemplate.Replace("#ReimbKKC", outInvDTO.ReimbKKC.ToString()); else finalTemplate = finalTemplate.Replace("#ReimbKKC", ""); if (outInvDTO.ReimbVAT != null) finalTemplate = finalTemplate.Replace("#ReimbVAT", outInvDTO.ReimbVAT.ToString()); else finalTemplate = finalTemplate.Replace("#ReimbVAT", ""); if (outInvDTO.ReimbTotalTax != null) finalTemplate = finalTemplate.Replace("#ReimbTotalTax", outInvDTO.ReimbTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#ReimbTotalTax", ""); if (outInvDTO.ReimbTotalAmount != null) finalTemplate = finalTemplate.Replace("#ReimbTotalAmount", outInvDTO.ReimbTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#ReimbTotalAmount", ""); if (outInvDTO.InterestCharges != null) finalTemplate = finalTemplate.Replace("#InterestCharges", outInvDTO.InterestCharges.ToString()); else finalTemplate = finalTemplate.Replace("#InterestCharges", ""); if (outInvDTO.IntrstServiceTax != null) finalTemplate = finalTemplate.Replace("#IntrstServiceTax", outInvDTO.IntrstServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#IntrstServiceTax", ""); if (outInvDTO.IntrstSBC != null) finalTemplate = finalTemplate.Replace("#IntrstSBC", outInvDTO.IntrstSBC.ToString()); else finalTemplate = finalTemplate.Replace("#IntrstSBC", ""); if (outInvDTO.IntrstKKC != null) finalTemplate = finalTemplate.Replace("#IntrstKKC", outInvDTO.IntrstKKC.ToString()); else finalTemplate = finalTemplate.Replace("#IntrstKKC", ""); if (outInvDTO.IntrstVAT != null) finalTemplate = finalTemplate.Replace("#IntrstVAT", outInvDTO.IntrstVAT.ToString()); else finalTemplate = finalTemplate.Replace("#IntrstVAT", ""); if (outInvDTO.IntrstTotalTax != null) finalTemplate = finalTemplate.Replace("#IntrstTotalTax", outInvDTO.IntrstTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#IntrstTotalTax", ""); if (outInvDTO.IntrstTotalAmount != null) finalTemplate = finalTemplate.Replace("#IntrstTotalAmount", outInvDTO.IntrstTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#IntrstTotalAmount", ""); if (outInvDTO.CustomisationCharges != null) finalTemplate = finalTemplate.Replace("#CustomisationCharges", outInvDTO.CustomisationCharges.ToString()); else finalTemplate = finalTemplate.Replace("#CustomisationCharges", ""); if (outInvDTO.CustmServiceTax != null) finalTemplate = finalTemplate.Replace("#CustmServiceTax", outInvDTO.CustmServiceTax.ToString()); else finalTemplate = finalTemplate.Replace("#CustmServiceTax", ""); if (outInvDTO.CustmSBC != null) finalTemplate = finalTemplate.Replace("#CustmSBC", outInvDTO.CustmSBC.ToString()); else finalTemplate = finalTemplate.Replace("#CustmSBC", ""); if (outInvDTO.CustmKKC != null) finalTemplate = finalTemplate.Replace("#CustmKKC", outInvDTO.CustmKKC.ToString()); else finalTemplate = finalTemplate.Replace("#CustmKKC", ""); if (outInvDTO.CustmVAT != null) finalTemplate = finalTemplate.Replace("#CustmVAT", outInvDTO.CustmVAT.ToString()); else finalTemplate = finalTemplate.Replace("#CustmVAT", ""); if (outInvDTO.CustmTotalTax != null) finalTemplate = finalTemplate.Replace("#CustmTotalTax", outInvDTO.CustmTotalTax.ToString()); else finalTemplate = finalTemplate.Replace("#CustmTotalTax", ""); if (outInvDTO.CustmTotalAmount != null) finalTemplate = finalTemplate.Replace("#CustmTotalAmount", outInvDTO.CustmTotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#CustmTotalAmount", ""); if (outInvDTO.TotalAmount != null) finalTemplate = finalTemplate.Replace("#TotalAmount", outInvDTO.TotalAmount.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmount", ""); if (outInvDTO.BasicConsideration != null) finalTemplate = finalTemplate.Replace("#BasicConsideration", outInvDTO.BasicConsideration.ToString()); else finalTemplate = finalTemplate.Replace("#BasicConsideration", ""); if (outInvDTO.TotalSBC != null) finalTemplate = finalTemplate.Replace("#TotalSBC", outInvDTO.TotalSBC.ToString()); else finalTemplate = finalTemplate.Replace("#TotalSBC", ""); if (outInvDTO.TotalKKC != null) finalTemplate = finalTemplate.Replace("#TotalKKC", outInvDTO.TotalKKC.ToString()); else finalTemplate = finalTemplate.Replace("#TotalKKC", ""); if (outInvDTO.TotalVAT != null) finalTemplate = finalTemplate.Replace("#TotalVAT", outInvDTO.TotalVAT.ToString()); else finalTemplate = finalTemplate.Replace("#TotalVAT", ""); if (outInvDTO.TotalPayable != null) finalTemplate = finalTemplate.Replace("#TotalPayable", outInvDTO.TotalPayable.ToString()); else finalTemplate = finalTemplate.Replace("#TotalPayable", ""); if (outInvDTO.TDS != null) finalTemplate = finalTemplate.Replace("#TDS", outInvDTO.TDS.ToString()); else finalTemplate = finalTemplate.Replace("#TDS", ""); if (outInvDTO.NetPayable != null) finalTemplate = finalTemplate.Replace("#NetPayable", outInvDTO.NetPayable.ToString()); else finalTemplate = finalTemplate.Replace("#NetPayable", ""); } if (finalTemplate != null) { ViewBag.content = finalTemplate; } return View(); } public bool ReceiptPDF(int collectionId, int userId) { bool res = false; try { var actionResult = new Rotativa.ActionAsPdf("ReceiptPDFView", new { id = collectionId }) //some route values) { FileName = "RECEIPT-" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10,Top=2 }, }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); string base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); var soaDtoObj = (from collctn in context.TECollections join ofr in context.TEOffers on collctn.ContextID equals ofr.OfferID join prjct in context.TEProjects on ofr.ProjectID equals prjct.ProjectID join unit in context.TEUnits on ofr.UnitID equals unit.UnitID join twr in context.TETowerMasters on unit.TowerID equals twr.TowerID join blockPickItem in context.TEPickListItems on twr.BlockId equals blockPickItem.Uniqueid //join spec in context.TESpecificationMasters on ofr.SpecsType equals spec.SpecificationID where collctn.CollectionsID == collectionId select new { OfferId = ofr.OfferID, UnitId = unit.UnitID, ProjectName = prjct.ProjectName, ProjectColour = prjct.ProjectColor, ProjectLogo = prjct.Logo, Block = blockPickItem.Description, CustomerName = ofr.OfferCustomerName, UnitNo = unit.UnitNumber, CustomerId = ofr.SAPCustomerID, ReceiptID = collctn.ReceiptID, // Specification = spec.SpecificationName, OfferConsideration = ofr.Consideration, OfferLandCost = ofr.LandPrice, OfferConstructionCost = ofr.ConstructionPrice }).FirstOrDefault(); if (soaDtoObj != null) { //res = collMgmtCtrl.UploadDocument(base64String, "Customer-Receipt", "Customer-Receipt", soaDtoObj.ProjectName, soaDtoObj.CustomerName, soaDtoObj.UnitNo, userId, soaDtoObj.ReceiptID, soaDtoObj.OfferId, soaDtoObj.CustomerId, ""); string projectName = string.Empty; if (!string.IsNullOrEmpty(soaDtoObj.Block)) projectName = soaDtoObj.ProjectName + " " + soaDtoObj.Block; else projectName = soaDtoObj.ProjectName; res = collMgmtCtrl.UploadDocument(base64String, "Customer-Receipt", "Customer-Receipt", projectName, soaDtoObj.CustomerName, soaDtoObj.UnitNo, userId, soaDtoObj.ReceiptID, soaDtoObj.OfferId, soaDtoObj.CustomerId, ""); } } catch (Exception ex) { exc.RecordUnHandledException(ex); } return res; } public ActionResult ReceiptPDFView(int id) { RECEIPTDTO recieiptObj = (from collctn in context.TECollections join ofr in context.TEOffers on collctn.ContextID equals ofr.OfferID join prjct in context.TEProjects on collctn.ProjectID equals prjct.ProjectID join unit in context.TEUnits on collctn.UnitID equals unit.UnitID join twr in context.TETowerMasters on unit.TowerID equals twr.TowerID join blockPickItem in context.TEPickListItems on twr.BlockId equals blockPickItem.Uniqueid join compny in context.TECompanies on prjct.CompanyID equals compny.Uniqueid join compnyGSTN in context.TECompanyGSTNDetails on prjct.StateID equals compnyGSTN.StateID into tempcmp from cmp in tempcmp.Where(a=>a.CompanyID== compny.Uniqueid).DefaultIfEmpty() where (collctn.CollectionsID == id && collctn.IsDeleted == false) select new RECEIPTDTO { CustomerName = ofr.OfferCustomerName, ProjectName = prjct.ProjectName, ProjectLogo = prjct.Logo, UnitNumber = unit.UnitNumber, Block = blockPickItem.Description, SAPCustomerID = collctn.SAPCustomerID, PaymentMode = collctn.PaymentMode, OfferID= collctn.ContextID, ReceiptID = collctn.ReceiptID, DraweeBank = collctn.DraweeBank, SAPBankCode = collctn.SAPBankCode, InstrumentNumber = collctn.InstrumentNumber, InstrumentDate = collctn.InstrumentDate, Amount = collctn.Amount, ReceivedOn = collctn.ReceivedOn, ClearedOn = collctn.ClearedOn, PayeeBank = collctn.PayeeBank, PayeeName = collctn.PayeeName, CompanyName = compny.Name, CompanyLogo = compny.CompanyLogo, CompanyGSTIN = cmp.GSTNCode, CompanyAddress = compny.Address, CompanyCIN = compny.CIN, CompanyPAN = compny.PAN, }).FirstOrDefault(); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; string AmountInWords = string.Empty; if (recieiptObj != null) { if(recieiptObj.ClearedOn==null) { recieiptObj.ClearedOn = DateTime.Now; } var customerGSTN = (from appl in context.TEApplicants where appl.ContextID == recieiptObj.OfferID && appl.Type == "Main Applicant" && appl.IsDeleted == false select new { GSTIN = appl.Gstin }).FirstOrDefault(); if (customerGSTN != null) { recieiptObj.CustomerGSTIN = customerGSTN.GSTIN; } AmountInWords = invBAL.NumberToWords(Convert.ToInt64(recieiptObj.Amount)); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = " Rupees " + AmountInWords + " Only "; } string projectName = string.Empty; if (!string.IsNullOrEmpty(recieiptObj.Block)) projectName = recieiptObj.ProjectName + " " + recieiptObj.Block; else projectName = recieiptObj.ProjectName; recieiptObj.ProjectName = projectName; } ViewBag.result = recieiptObj; ViewBag.ToDayDate = DateTime.Now.Date; ViewBag.server_folder = serviceProvideurl; ViewBag.AmountInWords = AmountInWords; if (recieiptObj != null) { return View(); } else { return new EmptyResult(); } } // to send emails with attachments public string DetailedSOA_Attachment(string id) { string result = string.Empty; string base64String = string.Empty; try { int tempInvId = Convert.ToInt32(id); var actionResult = new Rotativa.ActionAsPdf("DetailedSOA_AttachmentView", new { id = id }) //some route values) { FileName = "Daily Invoice" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10,Top=2 }, PageWidth = 185, PageHeight = 245 }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); result = invBAL.saveDocument(base64String); return result; } catch (Exception ex) { exc.RecordUnHandledException(ex); return result; } } public ActionResult DetailedSOA_AttachmentView(string id) { var template = context.TEEmailTemplates.Where(a => a.ModuleName.Contains("DETAILED SOA TEMPLATE")).FirstOrDefault(); string finalTemplate = string.Empty; if (template != null) finalTemplate = template.EmailTemplate; JObject jsonObject = new JObject(new JProperty("orderId", id)); FugueSOADTO soaDtoObj = new FugueSOADTO(); soaDtoObj = new InvoiceBAL().GetDetailSOAByOrderId(id); int breakupcnt = 0; int notecnt = 0; int cnt = 0; int totinvecdcnt = 0; string url = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; string PayableConsiderationDetails_Table = ""; var SubItems_Table = ""; string AnnexureTaxBookDetails_Table = ""; string TotalAmountInvoicedDetails_Table = ""; string Notes_Table = ""; string TotalAmountReceivedDetails_Table = ""; var PayableTaxDetails_Table = ""; var InvoiceBrakupSummaryDetails_Table = ""; string tempRecivedTable = ""; string tempInvoiceBreakupTable = ""; string tempTotAmountInvDetails_Table = ""; if (soaDtoObj != null) { int i = 0, j = 0; for (; i < soaDtoObj.PayableConsiderationDetails.Count; i++) { PayableConsiderationDetails_Table += " <tbody><tr><td class='snTd'>" + "1 " + soaDtoObj.PayableConsiderationDetails[i].SNo + "</td><td>" + soaDtoObj.PayableConsiderationDetails[i].Name + "</td><td class='txtalignright w20 currency'>" + soaDtoObj.PayableConsiderationDetails[i].Value + "</td></tr>"; for (; j < soaDtoObj.PayableConsiderationDetails[i].SubItems.Count; j++) { SubItems_Table += " <tr><td class='snTd'>" + "" + "</td><td>" + soaDtoObj.PayableConsiderationDetails[i].SubItems[j].Name + "</td><td class='txtalignright w20 currency'>" + soaDtoObj.PayableConsiderationDetails[i].SubItems[j].Value + "</td></tr>"; } PayableConsiderationDetails_Table += SubItems_Table + "</tbody>"; j = 0; SubItems_Table = ""; } foreach (var taxdata in soaDtoObj.PayableTaxDetails) { PayableTaxDetails_Table += "<tr><td class='snTd '>" + "4 " + taxdata.SNo + "</td><td>" + taxdata.TaxName + "</td><td class='txtalignright w20 currency'>" + taxdata.Value + "</td></tr>"; } tempRecivedTable += "<tbody>"; tempRecivedTable += "<tr>"; tempRecivedTable += "<th class='snTd greyBG'</th>"; tempRecivedTable += "<th colspan = '3' class='greyBG txtalignleft'>Total Amount Received</th>"; tempRecivedTable += "<th class='txtalignright currency'>" + soaDtoObj.TotalAmountReceived + "</th>"; tempRecivedTable += "</tr>"; tempRecivedTable += "<tr>"; tempRecivedTable += "<th class='snTd'>SI</th>"; tempRecivedTable += "<th class='txtalignleft'>Receipt Number</th>"; tempRecivedTable += "<th class='txtalignleft'>Receipt Date</th>"; tempRecivedTable += "<th class='txtalignleft'>Reference No.</th>"; tempRecivedTable += "<th class='txtalignleft'>Amount</th>"; tempRecivedTable += "</tr>"; foreach (var amntdata in soaDtoObj.TotalAmountReceivedDetails) { cnt++; tempRecivedTable += " <tr><td class='snTd'>" + cnt + "</td><td>" + amntdata.ReceiptNumber + "</td><td>" + amntdata.ReceiptDate.Value.ToShortDateString() + "</td><td class='txtalignright'>" + amntdata.ReferenceNo + "</td><td class='txtalignright currency'>" + amntdata.Amount + "</td></tr>"; } TotalAmountReceivedDetails_Table += tempRecivedTable + "</tbody>"; tempInvoiceBreakupTable += "<tbody>"; tempInvoiceBreakupTable += "<tr>"; tempInvoiceBreakupTable += "<th class='snTd greyBG'></th>"; tempInvoiceBreakupTable += "<th colspan = '4' class='greyBG txtalignleft'>Invoice Break up Summary</th>"; tempInvoiceBreakupTable += "</tr>"; tempInvoiceBreakupTable += "<tr>"; tempInvoiceBreakupTable += " <th class='snTd'>SI</th>"; tempInvoiceBreakupTable += "<th class='txtalignleft'>Consideration</th>"; tempInvoiceBreakupTable += "<th class='txtalignleft'>Total Amount</th>"; tempInvoiceBreakupTable += "<th class='txtalignleft'>Invoiced Amount</th>"; tempInvoiceBreakupTable += "<th class='txtalignleft'>Balance to be Invoiced</th>"; tempInvoiceBreakupTable += "</tr>"; foreach (var breakdata in soaDtoObj.InvoiceBrakupSummaryDetails) { breakupcnt++; tempInvoiceBreakupTable += "<tr><td class='snTd'>" + breakupcnt + "</td><td>" + breakdata.Name + "</td><td class='txtalignright currency'>" + breakdata.TotalValue + "</td><td class='txtalignright currency'>" + breakdata.InvoicedValue + "</td><td class='txtalignright currency'>" + breakdata.BalanceValue + "</td></tr>"; } TotalAmountReceivedDetails_Table += tempInvoiceBreakupTable + "</tbody>"; foreach (var notedata in soaDtoObj.NoteList) { notecnt++; Notes_Table += " <tr><td class='vTop'>" + notecnt + "</td><td>" + notedata + "</td></tr>"; } tempTotAmountInvDetails_Table += "<tbody>"; tempTotAmountInvDetails_Table += "<tr>"; tempTotAmountInvDetails_Table += "<th class='snTd greyBG'>B</th>"; tempTotAmountInvDetails_Table += "<th colspan = '8' class='greyBG txtalignleft'>Total Amount Invoiced</th>"; tempTotAmountInvDetails_Table += "<th colspan = '2' class='txtalignright currency'>#TotalAmountInvoiced</th>"; tempTotAmountInvDetails_Table += "</tr>"; tempTotAmountInvDetails_Table += " <tr class='text -center'>"; tempTotAmountInvDetails_Table += " <th rowspan = '2' > SI </th >"; tempTotAmountInvDetails_Table += " <th rowspan='2'>Invoice Number</th>"; tempTotAmountInvDetails_Table += " <th rowspan = '2' > Invoice Detail</th>"; tempTotAmountInvDetails_Table += " <th rowspan = '2' > Date </th >"; tempTotAmountInvDetails_Table += " <th colspan= '4' > Amount </th >"; tempTotAmountInvDetails_Table += " <th rowspan= '2' > Other Taxes</th>"; tempTotAmountInvDetails_Table += " <th rowspan = '2' > VAT </th >"; tempTotAmountInvDetails_Table += " <th rowspan= '2' > Total Amount</th>"; tempTotAmountInvDetails_Table += " </tr>"; tempTotAmountInvDetails_Table += "<tr>"; tempTotAmountInvDetails_Table += " <td>Land</td>"; tempTotAmountInvDetails_Table += " <td>Construction</td>"; tempTotAmountInvDetails_Table += "<td>Maintenance</td>"; tempTotAmountInvDetails_Table += " <td>Others</td>"; tempTotAmountInvDetails_Table += " </tr>"; foreach (var invoiceddata in soaDtoObj.TotalAmountInvoicedDetails) { totinvecdcnt++; tempTotAmountInvDetails_Table += "<tr>"; tempTotAmountInvDetails_Table += "<td>" + totinvecdcnt + "</ td>"; tempTotAmountInvDetails_Table += "<td>" + invoiceddata.InvoiceNumber + "</td>"; tempTotAmountInvDetails_Table += "<td>" + invoiceddata.InvoiceDetail + "</td >"; if (invoiceddata.InvoiceDate.Value != null) tempTotAmountInvDetails_Table += "<td>" + invoiceddata.InvoiceDate.Value.ToShortDateString() + "</td>"; else tempTotAmountInvDetails_Table += "<td></td >"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'>" + invoiceddata.LandCost + "</td>"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'> " + invoiceddata.ConstructionCost + "</td>"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'> " + invoiceddata.MaintenanceCost + "</td>"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'>" + invoiceddata.OtherCost + "</td>"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'>" + invoiceddata.OtherTaxes + "</td>"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'>" + invoiceddata.VAT + "</td>"; tempTotAmountInvDetails_Table += "<td class='txtalignright currency'>" + invoiceddata.TotalInvoiceAmount + "</td>"; tempTotAmountInvDetails_Table += "</tr>"; } TotalAmountInvoicedDetails_Table += tempTotAmountInvDetails_Table + "</tbody>"; foreach (var annexdata in soaDtoObj.AnnexureTaxBookDetails) { AnnexureTaxBookDetails_Table += "<table class=\'w100 mt30 bordering'\" cellpadding=\'3'\">"; AnnexureTaxBookDetails_Table += "<tbody>"; AnnexureTaxBookDetails_Table += "<tr>"; AnnexureTaxBookDetails_Table += "<th colspan = \'6\' class=\'greyBG txtalignleft\'>" + annexdata.Name + "</th>"; AnnexureTaxBookDetails_Table += "</tr>"; AnnexureTaxBookDetails_Table += "<tr>"; AnnexureTaxBookDetails_Table += "<th>Time Period</th>"; AnnexureTaxBookDetails_Table += "<th>Land</th>"; AnnexureTaxBookDetails_Table += "<th>Construction</th>"; AnnexureTaxBookDetails_Table += "<th>Maintenence</th>"; AnnexureTaxBookDetails_Table += "<th>Reimbursements</th>"; AnnexureTaxBookDetails_Table += "<th>Other</th>"; AnnexureTaxBookDetails_Table += "</tr>"; AnnexureTaxBookDetails_Table += "<tr>"; for (i = 0; i < annexdata.AnnexTaxBookDetails.Count; i++) { AnnexureTaxBookDetails_Table += "<td>" + annexdata.AnnexTaxBookDetails[i].TimePeriod + "</td>"; AnnexureTaxBookDetails_Table += "<td class='txtalignright currency'>" + annexdata.AnnexTaxBookDetails[i].Land + "</td>"; AnnexureTaxBookDetails_Table += "<td class='txtalignright currency'>" + annexdata.AnnexTaxBookDetails[i].Construction + "</td>"; AnnexureTaxBookDetails_Table += "<td class='txtalignright currency'>" + annexdata.AnnexTaxBookDetails[i].Maintenance + "</td>"; AnnexureTaxBookDetails_Table += "<td class='txtalignright currency'>" + annexdata.AnnexTaxBookDetails[i].Reimbursements + "</td>"; AnnexureTaxBookDetails_Table += "<td class='txtalignright currency'>" + annexdata.AnnexTaxBookDetails[i].Other + "</td>"; } AnnexureTaxBookDetails_Table += "</tr>"; AnnexureTaxBookDetails_Table += "</tbody>"; AnnexureTaxBookDetails_Table += "</table>"; } finalTemplate = finalTemplate.Replace("#CompanyAddress", soaDtoObj.CompanyAddress); finalTemplate = finalTemplate.Replace("#CompanyCIN", soaDtoObj.CompanyCIN); finalTemplate = finalTemplate.Replace("#CompanyName", soaDtoObj.CompanyName); finalTemplate = finalTemplate.Replace("#CompanyTAN", soaDtoObj.CompanyTAN); finalTemplate = finalTemplate.Replace("#CompanyPAN", soaDtoObj.CompanyPAN); finalTemplate = finalTemplate.Replace("#server_folder", "http://" + url + "/portfolio/"); finalTemplate = finalTemplate.Replace("#ProjectLogo", soaDtoObj.ProjectLogo); finalTemplate = finalTemplate.Replace("#CustomerName", soaDtoObj.CustomerName); finalTemplate = finalTemplate.Replace("#CustomerId", soaDtoObj.CustomerId); finalTemplate = finalTemplate.Replace("#Specification", soaDtoObj.Specification); finalTemplate = finalTemplate.Replace("#ProjectColour", soaDtoObj.ProjectColour); finalTemplate = finalTemplate.Replace("#ProjectName", soaDtoObj.ProjectName); finalTemplate = finalTemplate.Replace("#Specification", soaDtoObj.Specification); finalTemplate = finalTemplate.Replace("#UnitNo", soaDtoObj.UnitNo); finalTemplate = finalTemplate.Replace("#AnnexureTaxBookDetails_Table", AnnexureTaxBookDetails_Table); finalTemplate = finalTemplate.Replace("#PayableConsiderationDetails_Table", PayableConsiderationDetails_Table); finalTemplate = finalTemplate.Replace("#TotalAmountInvoicedDetails_Table", TotalAmountInvoicedDetails_Table); finalTemplate = finalTemplate.Replace("#Notes_Table", Notes_Table); finalTemplate = finalTemplate.Replace("#TotalAmountReceivedDetails_Table", TotalAmountReceivedDetails_Table); finalTemplate = finalTemplate.Replace("#PayableTaxDetails_Table", PayableTaxDetails_Table); finalTemplate = finalTemplate.Replace("#InvoiceBrakupSummaryDetails_Table", InvoiceBrakupSummaryDetails_Table); if (soaDtoObj.Date != null) finalTemplate = finalTemplate.Replace("#Date", soaDtoObj.Date.ToShortDateString()); else finalTemplate = finalTemplate.Replace("#Date", ""); if (soaDtoObj.TotalAmountReceived != null) finalTemplate = finalTemplate.Replace("#TotalAmountReceived", soaDtoObj.TotalAmountReceived.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountReceived", ""); if (soaDtoObj.TotalAmountPayable != null) finalTemplate = finalTemplate.Replace("#TotalAmountPayable", soaDtoObj.TotalAmountPayable.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountPayable", ""); if (soaDtoObj.Interest != null) finalTemplate = finalTemplate.Replace("#InterestAndFee", soaDtoObj.Interest.ToString()); else finalTemplate = finalTemplate.Replace("#InterestAndFee", ""); if (soaDtoObj.Taxes != null) finalTemplate = finalTemplate.Replace("#Taxes", soaDtoObj.Taxes.ToString()); else finalTemplate = finalTemplate.Replace("#Taxes", ""); if (soaDtoObj.TotalAmountInvoiced != null) finalTemplate = finalTemplate.Replace("#TotalAmountInvoiced", soaDtoObj.TotalAmountInvoiced.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountInvoiced", ""); if (soaDtoObj.BalanceAmountPayable != null) finalTemplate = finalTemplate.Replace("#BalanceAmountPayable", soaDtoObj.BalanceAmountPayable.ToString()); else finalTemplate = finalTemplate.Replace("#BalanceAmountPayable", ""); if (soaDtoObj.Customization != null) finalTemplate = finalTemplate.Replace("#Customization", soaDtoObj.Customization.ToString()); else finalTemplate = finalTemplate.Replace("#Customization", ""); if (soaDtoObj.TotalAmountReceived != null) finalTemplate = finalTemplate.Replace("#TotalAmountReceived", soaDtoObj.TotalAmountReceived.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountReceived", ""); if (soaDtoObj.TotalAmountPayable != null) finalTemplate = finalTemplate.Replace("#TotalAmountPayable", soaDtoObj.TotalAmountPayable.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountPayable", ""); if (soaDtoObj.TotalAmountReceived != null) finalTemplate = finalTemplate.Replace("#TotalAmountReceived", soaDtoObj.TotalAmountReceived.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountReceived", ""); if (soaDtoObj.TotalAmountPayable != null) finalTemplate = finalTemplate.Replace("#TotalAmountPayable", soaDtoObj.TotalAmountPayable.ToString()); else finalTemplate = finalTemplate.Replace("#TotalAmountPayable", ""); } if (finalTemplate != null) { ViewBag.content = finalTemplate; } return View(); } /// <summary> /// To send Emails to the Customers with Detailed SOA and Invoice Attachments Based o Regular Job /// </summary> /// <param name="InvoiceId"></param> /// <param name="OrderId"></param> /// <returns></returns> public ActionResult SendInvoicedEmails_Attachments() { try { DateTime today = DateTime.Now.Date; DateTime nextday = DateTime.Now.AddDays(1).Date; var sendEmailsList = (from inv in context.TEInvoices where inv.InVoicedOn > today && inv.InVoicedOn < nextday && inv.InVoiceStatus == "Invoiced" select new { inv.SAPOrderID, inv.InVoiceID }).ToList(); foreach (var data in sendEmailsList) { string Invoice_pdfPath = Invoice_Attachment(data.InVoiceID, 3375,null); string SOA_pdfPath = DetailedSOA_Attachment(data.SAPOrderID); string SmtpServerObj = WebConfigurationManager.AppSettings["SmtpServer"]; string FugueEmail = WebConfigurationManager.AppSettings["Fugue"]; string SmtpPassword = WebConfigurationManager.AppSettings["SmtpPassword"]; var customerDetails = (from ofr in context.TEOffers join ld in context.TELeads on ofr.LeadID equals ld.LeadID join cont in context.TEContactEmails on ld.ContactID equals cont.TEContact where ofr.SAPOrderID == data.SAPOrderID select new { cont.Emailid, ld.CallName }).FirstOrDefault(); string base64 = string.Empty; if (customerDetails != null) { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(SmtpServerObj); mail.From = new MailAddress(FugueEmail); mail.To.Add(customerDetails.Emailid); mail.Subject = "DETAILED SOA && INVOICE "; mail.Body = "Dear " + customerDetails.CallName + ",FYI,Here by i am attaching a file please find the attachment"; string assemblyFile = string.Empty; assemblyFile = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath; int index = assemblyFile.LastIndexOf("/bin/"); string Logo = string.Empty; string logoFilePath = @"" + assemblyFile.Substring(0, index) + "/"; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("" + logoFilePath + "" + Invoice_pdfPath + ""); mail.Attachments.Add(attachment); System.Net.Mail.Attachment attachment2; attachment2 = new System.Net.Mail.Attachment("" + logoFilePath + "" + SOA_pdfPath + ""); mail.Attachments.Add(attachment2); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential(FugueEmail, SmtpPassword); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } } } catch (Exception ex) { exc.RecordUnHandledException(ex); } //SuccessInfo sinfo = new SuccessInfo(); //if (1 == 1) //{ // sinfo.errorcode = 0; // sinfo.errormessage = "Success"; // sinfo.fromrecords = 1; // sinfo.totalrecords = 0; // sinfo.pages = "1"; //} //else //{ // sinfo.errorcode = 1; // sinfo.errormessage = "Fail"; // sinfo.fromrecords = 1; // sinfo.torecords = 10; // sinfo.totalrecords = 0; // sinfo.listcount = 0; // sinfo.pages = "1"; //} return Json(JsonRequestBehavior.AllowGet); } public ActionResult SendInvoicedEmails_Attachments_Backup() { try { DateTime today = DateTime.Now.Date; DateTime nextday = DateTime.Now.AddDays(1).Date; var sendEmailsList = (from inv in context.TEInvoices where inv.InVoicedOn > today && inv.InVoicedOn < nextday && inv.InVoiceStatus == "Invoiced" select new { inv.SAPOrderID, inv.InVoiceID }).ToList(); foreach (var data in sendEmailsList) { string Invoice_pdfPath = Invoice_Attachment(data.InVoiceID, 3375,null); string SOA_pdfPath = DetailedSOA_Attachment(data.SAPOrderID); string SmtpServerObj = WebConfigurationManager.AppSettings["SmtpServer"]; string FugueEmail = WebConfigurationManager.AppSettings["Fugue"]; string SmtpPassword = WebConfigurationManager.AppSettings["SmtpPassword"]; var customerDetails = (from ofr in context.TEOffers join ld in context.TELeads on ofr.LeadID equals ld.LeadID join cont in context.TEContactEmails on ld.ContactID equals cont.TEContact where ofr.SAPOrderID == data.SAPOrderID select new { cont.Emailid, ld.CallName }).FirstOrDefault(); string base64 = string.Empty; if (customerDetails != null) { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(SmtpServerObj); mail.From = new MailAddress(FugueEmail); mail.To.Add(customerDetails.Emailid); mail.Subject = "DETAILED SOA && INVOICE "; mail.Body = "Dear " + customerDetails.CallName + ",FYI,Here by i am attaching a file please find the attachment"; string assemblyFile = string.Empty; assemblyFile = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath; int index = assemblyFile.LastIndexOf("/bin/"); string Logo = string.Empty; string logoFilePath = @"" + assemblyFile.Substring(0, index) + "/"; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("" + logoFilePath + "" + Invoice_pdfPath + ""); mail.Attachments.Add(attachment); System.Net.Mail.Attachment attachment2; attachment2 = new System.Net.Mail.Attachment("" + logoFilePath + "" + SOA_pdfPath + ""); mail.Attachments.Add(attachment2); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential(FugueEmail, SmtpPassword); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } } } catch (Exception ex) { exc.RecordUnHandledException(ex); } //SuccessInfo sinfo = new SuccessInfo(); //if (1 == 1) //{ // sinfo.errorcode = 0; // sinfo.errormessage = "Success"; // sinfo.fromrecords = 1; // sinfo.totalrecords = 0; // sinfo.pages = "1"; //} //else //{ // sinfo.errorcode = 1; // sinfo.errormessage = "Fail"; // sinfo.fromrecords = 1; // sinfo.torecords = 10; // sinfo.totalrecords = 0; // sinfo.listcount = 0; // sinfo.pages = "1"; //} return Json(JsonRequestBehavior.AllowGet); } //to clear invoice [HttpPost] public ActionResult ClearCollection(JsonVlaues json) { TECollection colln = new TECollection(); bool res = true; SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); string errMsg = string.Empty; try { context.Configuration.ProxyCreationEnabled = false; colln = context.TECollections.Where(a => a.CollectionsID == json.CollectionsID).FirstOrDefault(); if (colln == null || colln.CollectionsID == 0) { errMsg = "Receipt Details not found"; sinfo.errormessage = errMsg; sinfo.errorcode = 1; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } if (colln.Status != "Deposited") { errMsg = String.Format("Clear Receipt can be allowed only for receipts with Deposited Status"); sinfo.errormessage = errMsg; sinfo.errorcode = 1; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } colln.Status = "Cleared"; colln.IsDeleted = false; colln.LastModifiedOn = DateTime.Now; colln.LastModifiedBy_Id = json.LastModifiedBy_Id; colln.ClearedBy = json.LastModifiedBy_Id; colln.ClearedOn = DateTime.Now; colln.UnAllocatedAmount = colln.Amount; context.Entry(colln).CurrentValues.SetValues(colln); context.SaveChanges(); //#region ReceiptAllocation Logic //new InvoiceDAL().AllocateReceiptsBySAPCustomerId(colln.SAPCustomerID, "Receipt Clearance"); //#endregion //Code to update receipt status in SAP Receipts TESAPReceipt sapColn = (from receipt in context.TESAPReceipts where receipt.CustomerNumber == colln.SAPCustomerID && receipt.AccountingDocumentNumber == colln.ReceiptID select receipt).FirstOrDefault(); if (sapColn != null && sapColn.ID > 0) { sapColn.Status = "Cleared"; context.Entry(colln).CurrentValues.SetValues(sapColn); context.SaveChanges(); } #region ReceiptAllocation Logic new InvoiceDAL().AllocateReceiptsBySAPCustomerId(colln.SAPCustomerID, "Receipt Clearance"); #endregion ReceiptPDF(json.CollectionsID, json.LastModifiedBy_Id); int? result = colln.CollectionsID; res = result > 0 ? true : false; } catch (Exception ex) { res = false; } if (res) { sinfo.errorcode = 0; sinfo.errormessage = "Successfully Cleared"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Failed to Clear"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } [HttpPost] public ActionResult PostReceiptToDMS(JsonVlaues json) { bool res = false; SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); string errMsg = string.Empty; int collnId = json.CollectionsID; int lastModifiedBy = json.LastModifiedBy_Id; try { if (collnId > 0 && lastModifiedBy > 0) { res = ReceiptPDF(collnId, json.LastModifiedBy_Id); } else { errMsg = "Receipt Details not found"; sinfo.errormessage = errMsg; sinfo.errorcode = 1; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { res = false; } if (res) { sinfo.errorcode = 0; sinfo.errormessage = "Receipt Posted to DMS Successfully"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Failed to Post to DMS"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } [HttpPost] public ActionResult PostInvoiceToDMS(InvoiceJsonVlaues invoiceValues) { bool res = false; SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); string errMsg = string.Empty; string InvoiceBase64 = string.Empty; int invId = invoiceValues.PrimaryObjectID; int lastModifiedBy = invoiceValues.LastModifiedById; try { if (invId > 0 && lastModifiedBy > 0) { InvoiceBase64 = Invoice_Attachment(invId, lastModifiedBy,"ResendToDMS"); if (!string.IsNullOrEmpty(InvoiceBase64)) res = true; } else { errMsg = "Invoice Details not found"; sinfo.errormessage = errMsg; sinfo.errorcode = 1; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { res = false; } if (res) { sinfo.errorcode = 0; sinfo.errormessage = "Invoice Posted to DMS Successfully"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Failed to Post to DMS"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } /// <summary> /// To Post Invoice and Pushing the Invoice PDF to DMS /// </summary> /// <param name="json"></param> /// <returns></returns> [HttpPost] public ActionResult PostInvoice(InvoiceJsonVlaues invoiceValues) { bool res = false; SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); string invoiceAttachPath = string.Empty; string CSOAAttachPath = string.Empty; string csoaBase64 = string.Empty; string InvoiceBase64 = string.Empty; string FileName =string.Empty; try { sinfo.errorcode = 1; context.Configuration.ProxyCreationEnabled = false; sinfo = new InvoiceDAL().PostInvoice(invoiceValues.PrimaryObjectID, invoiceValues.LastModifiedById, invoiceValues.PreInvoiceDate, invoiceValues.DateFlag); if (sinfo.errorcode == 0) { res = true; InvoiceBase64 = Invoice_Attachment(invoiceValues.PrimaryObjectID, invoiceValues.LastModifiedById,"", invoiceValues.PreInvoiceDate, invoiceValues.DateFlag); invoiceAttachPath = invBAL.generatePdfPath(InvoiceBase64); var customerDetails = (from inv in context.TEInvoices join ofr in context.TEOffers on inv.ContextID equals ofr.OfferID join ld in context.TELeads on ofr.LeadID equals ld.LeadID join cont in context.TEContactEmails on ld.ContactID equals cont.TEContact where inv.InVoiceID == invoiceValues.PrimaryObjectID select new { ofr.SAPOrderID,ofr.LeadID, cont.Emailid, ld.CallName }).FirstOrDefault(); if (customerDetails != null) { if (!string.IsNullOrEmpty(customerDetails.SAPOrderID)) { csoaBase64 = CurrentSOAPDF(customerDetails.SAPOrderID); if (!string.IsNullOrEmpty(csoaBase64)) { CSOAAttachPath = invBAL.generatePdfPath(csoaBase64); } } var Body = "Dear" + customerDetails.CallName + "FYI,Hereby i am attaching a file please find the attachment"; var subject = "INVOICE"; string[] arr1 = new string[] { invoiceAttachPath, CSOAAttachPath }; var mail = new Mailing(); if (!string.IsNullOrEmpty(customerDetails.Emailid)) { cememail.OnInvoiceCreation(invoiceValues.PrimaryObjectID, invoiceValues.LastModifiedById, customerDetails.Emailid, InvoiceBase64, invoiceAttachPath, csoaBase64, CSOAAttachPath, arr1); //bool ismailsent = mail.SendEMail(customerDetails.Emailid, "", "", Body, subject, arr1); //if (ismailsent) //{ // int TemptrancsID = 0; // TemptrancsID = Notif_Hist_BAL.CustomerEmailTransactions(customerDetails.LeadID, "", customerDetails.Emailid, "", "", Body, subject, invoiceValues.LastModifiedById); // if (TemptrancsID != 0) // { // if (!string.IsNullOrEmpty(invoiceAttachPath)) // Notif_Hist_BAL.CustomerEmailTransactionWithAttachments(TemptrancsID, "pdf", InvoiceBase64, invoiceAttachPath, invoiceValues.LastModifiedById); // if (!string.IsNullOrEmpty(CSOAAttachPath)) // Notif_Hist_BAL.CustomerEmailTransactionWithAttachments(TemptrancsID, "pdf", csoaBase64, CSOAAttachPath, invoiceValues.LastModifiedById); // } //} } } } } catch (Exception ex) { res = false; } if (res) { sinfo.errorcode = 0; sinfo.errormessage = "Invoice Posted Successfully"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Failed to post Invoice"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } //sending Email Profarma Invoice To Customer with Attachment // to send emails with attachments public bool sendProfarmaInvoiceEmailAttachment(int invoiceID, int userId, string CC, string To, string type, string emailBody = emailBodyValue) { bool result = true; string base64String = string.Empty; try { int tempInvId = Convert.ToInt32(invoiceID); var actionResult = new Rotativa.ActionAsPdf("Invoice_AttachmentView", new { id = invoiceID, type=type, PostingType = "" }) //some route values) { FileName = "INVOICE" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10,Top=2 }, PageWidth = 185, PageHeight = 245 }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); string ProjectName = string.Empty; string UnitNumber = string.Empty; string Milestonename = string.Empty; var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); string attachpath = new InvoiceBAL().generatePdfPath(base64String); string customerName = string.Empty; if (string.IsNullOrEmpty(To)) { var custDtls = (from inv in context.TEInvoices join ofr in context.TEOffers on inv.ContextID equals ofr.OfferID join ld in context.TELeads on ofr.LeadID equals ld.LeadID join cnt in context.TEContactEmails on ld.ContactID equals cnt.TEContact join units in context.TEUnits on ofr.UnitID equals units.UnitID join prjs in context.TEProjects on ofr.ProjectID equals prjs.ProjectID join mile in context.TEOfferMileStones on inv.MileStoneRef equals mile.MileStoneID into tempmilesotones from milest in tempmilesotones.DefaultIfEmpty() where inv.InVoiceID == tempInvId && cnt.Emailid != null select new { ofr.OfferCustomerName, ld.CallName, cnt.Emailid, prjs.ProjectShortName, units.UnitNumber, milest.Name }).FirstOrDefault(); if (custDtls != null) { To = custDtls.Emailid; customerName = custDtls.CallName; ProjectName = custDtls.ProjectShortName; UnitNumber = custDtls.UnitNumber; Milestonename = custDtls.Name; } } else { var custDtls = (from inv in context.TEInvoices join ofr in context.TEOffers on inv.ContextID equals ofr.OfferID join ld in context.TELeads on ofr.LeadID equals ld.LeadID join units in context.TEUnits on ofr.UnitID equals units.UnitID join prjs in context.TEProjects on ofr.ProjectID equals prjs.ProjectID join mile in context.TEOfferMileStones on inv.MileStoneRef equals mile.MileStoneID into tempmilesotones from milest in tempmilesotones.DefaultIfEmpty() where inv.InVoiceID == tempInvId select new { ofr.OfferCustomerName, ld.CallName, prjs.ProjectShortName, units.UnitNumber, milest.Name }).FirstOrDefault(); if (custDtls != null) { customerName = custDtls.CallName; ProjectName = custDtls.ProjectShortName; UnitNumber = custDtls.UnitNumber; Milestonename = custDtls.Name; } } // var Body = "Dear " + customerName + "FYI, Hereby i am attaching a file please find the attachment"; var Body = "Dear " + customerName + ","; string mailBody = Body.ToString() + emailBody; var subject = "PRO FORMA INVOICE - " + ProjectName + " Unit " + UnitNumber; string[] arr1 = new string[] { attachpath }; var mail = new Mailing(); mail.SendEMail_fugueCredentials(To, CC, "", mailBody, subject, arr1, "INVOICE"); } catch (Exception ex) { exc.RecordUnHandledException(ex); result = false; } return result; } public string Invoice_Attachment(int id, int userId, string postingType,DateTime? preDate = null, bool? dateFlag = null) { string base64String = string.Empty; TEDMSDocument dmsDoc = new TEDMSDocument(); ResultDocumentDetails res = new ResultDocumentDetails(); try { int tempInvId = Convert.ToInt32(id); var custDtls = (from inv in context.TEInvoices join ofr in context.TEOffers on inv.ContextID equals ofr.OfferID into o from tmpofr in o.DefaultIfEmpty() join prjct in context.TEProjects on tmpofr.ProjectID equals prjct.ProjectID join unit in context.TEUnits on tmpofr.UnitID equals unit.UnitID join twr in context.TETowerMasters on unit.TowerID equals twr.TowerID join blockPickItem in context.TEPickListItems on twr.BlockId equals blockPickItem.Uniqueid where inv.InVoiceID == tempInvId select new { prjct.ProjectName, unit.UnitNumber, Block = blockPickItem.Description, tmpofr.OfferCustomerName, inv.SAPCustomerID, inv.LastModifiedBy_Id, inv.ContextID, tmpofr.IsPostGSTOrder }).FirstOrDefault(); DateTime gstAppliedDate = new DateTime(2017, 07, 01); TEInvoice invObj = context.TEInvoices.Where(a => a.InVoiceID == id && a.IsDeleted == false).FirstOrDefault(); if (invObj == null) { return ""; } else if (invObj.InVoicedOn < gstAppliedDate) { var actionResult = new Rotativa.ActionAsPdf("InvoicePDFforOldCustomer", new { id = id, type = "DMSPENDINGINVOICE", PostingType = postingType }) //some route values) { FileName = "INVOICE" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10, Top = 2 }, }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); } else { bool postGstOrder = custDtls.IsPostGSTOrder; if (postGstOrder) { var actionResult = new Rotativa.ActionAsPdf("Invoice_AttachmentViewForGST", new { id = id, type = "DMSPENDINGINVOICE", PostingType = postingType, PREdate = preDate, FlagDate = dateFlag }) //some route values) { FileName = "INVOICE" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10, Top = 2 }, }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); } else { var actionResult = new Rotativa.ActionAsPdf("Invoice_AttachmentView", new { id = id, type = "DMSPENDINGINVOICE", PostingType = postingType, PREdate = preDate, FlagDate = dateFlag }) //some route values) { FileName = "INVOICE" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10, Top = 2 }, }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); } } if (custDtls != null) { //collMgmtCtrl.UploadDocument(base64String, "Customer-Invoice", "Customer-Invoice", custDtls.ProjectName, custDtls.OfferCustomerName, custDtls.UnitNumber, userId, id.ToString(), custDtls.ContextID, custDtls.SAPCustomerID, ""); string projectName = string.Empty; if (!string.IsNullOrEmpty(custDtls.Block)) projectName = custDtls.ProjectName + " " + custDtls.Block; else projectName = custDtls.ProjectName; collMgmtCtrl.UploadDocument(base64String, "Customer-Invoice", "Customer-Invoice", projectName, custDtls.OfferCustomerName, custDtls.UnitNumber, userId, id.ToString(), custDtls.ContextID, custDtls.SAPCustomerID, ""); } return base64String; } catch (Exception ex) { exc.RecordUnHandledException(ex); return base64String; } } //generate new Invoice pdf (with CGST and TST TAX Calculations) public ActionResult Invoice_AttachmentView(string id, string type, string PostingType, DateTime? PREdate = null, bool? FlagDate = null) { string invoicetitle = string.Empty; InvoiceBrkupDTO outInvDTO = new InvoiceBrkupDTO(); if (PostingType == "ResendToDMS") { invoicetitle = "INVOICE"; outInvDTO = new InvoiceDAL().GetInvoicePerformaToResendDMSByInvoiceId(Convert.ToInt32(id)); ViewBag.ToDayDate = outInvDTO.InvoicedOn; } else { if (type == "DMSPENDINGINVOICE") { invoicetitle = "INVOICE"; outInvDTO = new InvoiceDAL().GetInvoicePerformaByInvoiceId(Convert.ToInt32(id)); ViewBag.ToDayDate = outInvDTO.InvoicedOn; } else { invoicetitle = "PRO FORMA INVOICE"; ViewBag.ToDayDate = DateTime.Now.Date; } if (type == "PENDINGINVOICE") { outInvDTO = new InvoiceDAL().GetInvoicePerformaByInvoiceId(Convert.ToInt32(id)); ViewBag.ToDayDate = DateTime.Now.Date; } else if (type == "MILESTONEINVOICE") { outInvDTO = new InvoiceDAL().GetInvoicePerformaByMilestoneId(Convert.ToInt32(id)); ViewBag.ToDayDate = DateTime.Now.Date; } else if (type == "SPLITMILESTONEINVOICE") { outInvDTO = new InvoiceDAL().GetInvoicePerformaBySplittedMilestoneId(Convert.ToInt32(id)); ViewBag.ToDayDate = DateTime.Now.Date; } } var CSGSTTaxAmnt = outInvDTO.invBrkupDtl.Sum(a => a.CSGSTTaxAmnt); var SGSTTaxAmnt = outInvDTO.invBrkupDtl.Sum(a => a.SGSTTaxAmnt); var invTotalAmount = outInvDTO.invBrkupDtl.Sum(a => a.TotalAmount); var totConsiderationAmnt = outInvDTO.invBrkupDtl.Sum(a => a.ConsiderationAmnt); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; string AmountInWords = string.Empty; if (outInvDTO != null) { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(invTotalAmount)); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords ="Rupees "+ AmountInWords + " Only "; } } int ProjectID = outInvDTO.ProjectID; var DigitalSign = (from t1 in context.TEOrgRules join t2 in context.UserProfiles on t1.UserID equals t2.UserId into t2F from t2Final in t2F.DefaultIfEmpty() join t3 in context.webpages_Roles on t1.RoleID equals t3.RoleId into t3F from t3Final in t3F.DefaultIfEmpty() where (t1.ProjectID == ProjectID && t3Final.RoleName.Equals("AVP-Finance") && t1.IsDeleted == false && t2Final.IsDeleted == false) select t2Final.CallName).FirstOrDefault(); ViewBag.result = outInvDTO; ViewBag.totCSGSTTaxAmnt = CSGSTTaxAmnt; ViewBag.totSGSTTaxAmnt = SGSTTaxAmnt; ViewBag.invTotalAmount = invTotalAmount; ViewBag.totConsiderationAmnt = totConsiderationAmnt; ViewBag.server_folder = serviceProvideurl; ViewBag.InvoiceType = outInvDTO; ViewBag.AmountInWords = AmountInWords; ViewBag.Title = invoicetitle; ViewBag.DigitalSign = DigitalSign; if(Convert.ToBoolean(FlagDate)) { ViewBag.ToDayDate = PREdate; } if (outInvDTO != null) { return View(); } else { return new EmptyResult(); } } //generate new Invoice pdf (with CGST and TST TAX Calculations) Mahipal 17-Apr-2018 public ActionResult Invoice_AttachmentViewForGST(string id, string type, string PostingType, DateTime? PREdate = null, bool? FlagDate = null) { string invoicetitle = string.Empty; InvoiceBrkupDTO outInvDTO = new InvoiceBrkupDTO(); if (PostingType == "ResendToDMS") { invoicetitle = "INVOICE"; outInvDTO = new InvoiceDAL().GetInvoicePerformaToResendDMSByInvoiceId(Convert.ToInt32(id)); ViewBag.ToDayDate = outInvDTO.InvoicedOn; } else { if (type == "DMSPENDINGINVOICE") { invoicetitle = "INVOICE"; outInvDTO = new InvoiceDAL().GetInvoicePerformaByInvoiceId(Convert.ToInt32(id)); ViewBag.ToDayDate = outInvDTO.InvoicedOn; } else { invoicetitle = "PRO FORMA INVOICE"; ViewBag.ToDayDate = DateTime.Now.Date; } if (type == "PENDINGINVOICE") { outInvDTO = new InvoiceDAL().GetInvoicePerformaByInvoiceId(Convert.ToInt32(id)); ViewBag.ToDayDate = DateTime.Now.Date; } else if (type == "MILESTONEINVOICE") { outInvDTO = new InvoiceDAL().GetInvoicePerformaByMilestoneId(Convert.ToInt32(id)); ViewBag.ToDayDate = DateTime.Now.Date; } else if (type == "SPLITMILESTONEINVOICE") { outInvDTO = new InvoiceDAL().GetInvoicePerformaBySplittedMilestoneId(Convert.ToInt32(id)); ViewBag.ToDayDate = DateTime.Now.Date; } } var CSGSTTaxAmnt = outInvDTO.invBrkupDtl.Sum(a => a.CSGSTTaxAmnt); var SGSTTaxAmnt = outInvDTO.invBrkupDtl.Sum(a => a.SGSTTaxAmnt); var invTotalAmount = outInvDTO.invBrkupDtl.Sum(a => a.TotalAmount); var totConsiderationAmnt = outInvDTO.invBrkupDtl.Sum(a => a.ConsiderationAmnt); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; string AmountInWords = string.Empty; if (outInvDTO != null) { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(invTotalAmount)); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = "Rupees " + AmountInWords + " Only "; } } int ProjectID = outInvDTO.ProjectID; var DigitalSign = (from t1 in context.TEOrgRules join t2 in context.UserProfiles on t1.UserID equals t2.UserId into t2F from t2Final in t2F.DefaultIfEmpty() join t3 in context.webpages_Roles on t1.RoleID equals t3.RoleId into t3F from t3Final in t3F.DefaultIfEmpty() where (t1.ProjectID == ProjectID && t3Final.RoleName.Equals("AVP-Finance") && t1.IsDeleted == false && t2Final.IsDeleted == false) select t2Final.CallName).FirstOrDefault(); ViewBag.result = outInvDTO; ViewBag.totCSGSTTaxAmnt = CSGSTTaxAmnt; ViewBag.totSGSTTaxAmnt = SGSTTaxAmnt; ViewBag.invTotalAmount = invTotalAmount; ViewBag.totConsiderationAmnt = totConsiderationAmnt; ViewBag.server_folder = serviceProvideurl; ViewBag.InvoiceType = outInvDTO; ViewBag.AmountInWords = AmountInWords; ViewBag.Title = invoicetitle; ViewBag.DigitalSign = DigitalSign; if (Convert.ToBoolean(FlagDate)) { ViewBag.ToDayDate = PREdate; } if (outInvDTO != null) { return View(); } else { return new EmptyResult(); } } //generate old Invoice pdf (before GST tax calculations) public ActionResult InvoicePDFforOldCustomer(string id) { string invoicetitle = string.Empty; InvoiceBrkupDtlDTO outInvDTO = new InvoiceBrkupDtlDTO(); invoicetitle = "INVOICE"; outInvDTO = new InvoiceDAL().GetInvoiceBreakupByInvoiceId(Convert.ToInt32(id)); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; string AmountInWords = string.Empty; if (outInvDTO != null) { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(outInvDTO.TotalAmount)); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = "Rupees " + AmountInWords + " Only "; } } ViewBag.result = outInvDTO; if (outInvDTO != null) { var totalConsideration = outInvDTO.TotalConsideration; var totalTax = outInvDTO.TotalTax; ViewBag.totConsideration = totalConsideration; ViewBag.totTax = totalTax; } ViewBag.server_folder = serviceProvideurl; ViewBag.InvoiceType = outInvDTO; ViewBag.AmountInWords = AmountInWords; if (outInvDTO != null) { return View(); } else { return new EmptyResult(); } } [HttpPost] public ActionResult SendEmail_ProfrmaInvoice(InvoiceJsonVlaues invoiceValues) { bool res = true; SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); //string errMsg = string.Empty; try { context.Configuration.ProxyCreationEnabled = false; res = sendProfarmaInvoiceEmailAttachment(invoiceValues.PrimaryObjectID, invoiceValues.LastModifiedById, invoiceValues.cemEmail, invoiceValues.EmailTO, invoiceValues.ProfarmaEmailType); //, invoiceValues.EmailBody if (res) { TEInvoice inv = context.TEInvoices.Where(a => a.InVoiceID == invoiceValues.PrimaryObjectID).FirstOrDefault(); if (inv != null) { inv.IsDispatched = true; context.Entry(inv).CurrentValues.SetValues(inv); context.SaveChanges(); } sinfo.errorcode = 0; sinfo.errormessage = "Email sent successfully"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Unable to send Email"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { new GenericDAL().RecordUnHandledException(ex); sinfo.errorcode = 1; sinfo.errormessage = "Fail to send Email"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } [HttpPost] public ActionResult SendEmail_CustomerSummaryInvoice(InvoiceJsonVlaues invoiceValues) { bool res = true; SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); //string errMsg = string.Empty; try { context.Configuration.ProxyCreationEnabled = false; res = sendProfarmaInvoiceEmailAttachment(invoiceValues.PrimaryObjectID, invoiceValues.LastModifiedById, invoiceValues.EmailCC, invoiceValues.EmailTO, invoiceValues.ProfarmaEmailType); if (res) { sinfo.errorcode = 0; sinfo.errormessage = "Email sent successfully"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Unable to send Email"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { new GenericDAL().RecordUnHandledException(ex); sinfo.errorcode = 1; sinfo.errormessage = "Fail to send Email"; infoDetailsObj.info = sinfo; return Json(infoDetailsObj, JsonRequestBehavior.AllowGet); } } #region Customer ALL SOA PDF DOWNLOAD CODE BASED ON SAPOrderID public string CurrentSOAPDF(string orderId) { string result = string.Empty; string base64String = string.Empty; try { CurrentSOADTO soaDtoObj = new CurrentSOADTO(); soaDtoObj = new InvoiceBAL().GetCurrentStatementOfAcccount(orderId); string Page = "0"; var ToPage = "0"; string customSwitches = string.Format("--footer-html \"{0}\" " + "--header-html \"{1}\" ", Url.Action("AFSFooter", "GeneratePDF", new { PageNumber = Page, TotalPage = ToPage }, "http"), Url.Action("AFSHeader", "GeneratePDF", new { PageNumber = Page, Cname= soaDtoObj.CustomerName, UnitNO = soaDtoObj.UnitNo, Dated = soaDtoObj.Date }, "http")); var actionResult = new Rotativa.ActionAsPdf("CurrentSOAPDFView", new { id = orderId }) { FileName = "CURRENTSOA" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageMargins = { Left = 10, Right = 10, Top = 12, Bottom = 10 }, CustomSwitches = customSwitches }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); return base64String; } catch (Exception ex) { exc.RecordUnHandledException(ex); return result; } } public ActionResult CurrentSOAPDFView(string id) { CurrentSOADTO soaDtoObj = new CurrentSOADTO(); soaDtoObj = new InvoiceBAL().GetCurrentStatementOfAcccount(id); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; string AmountInWords = ""; ViewBag.result = soaDtoObj; @ViewBag.server_folder = serviceProvideurl; if (soaDtoObj != null) { if (soaDtoObj.AmountDueNow < 0) { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(soaDtoObj.AmountDueNow * (-1))); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = " Rupees "+AmountInWords + " Only "; } } else { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(soaDtoObj.AmountDueNow)); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = " Rupees " + AmountInWords + " Only "; } } ViewBag.AmountDueNowInWords = AmountInWords; return View(); } else { return new EmptyResult(); } } public string CustomerAccountSummaryPDF(string id) { string result = string.Empty; string base64String = string.Empty; try { var actionResult = new Rotativa.ActionAsPdf("CustomerAccountSummaryPDFView", new { id = id }) //some route values) { FileName = "CUSTOMERACCOUNTSUMMARY" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10,Top=2 }, // PageWidth = 185, // PageHeight = 245 }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); return base64String; } catch (Exception ex) { exc.RecordUnHandledException(ex); return result; } } public ActionResult CustomerAccountSummaryPDFView(string id) { DetailSOADTO soaDtoObj = new DetailSOADTO(); soaDtoObj = new InvoiceBAL().GetDetailSOAByOrderId_New(id); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; ViewBag.result = soaDtoObj; ViewBag.ToDayDate = DateTime.Now.Date; @ViewBag.server_folder = serviceProvideurl; if (soaDtoObj != null) { return View(); } else { return new EmptyResult(); } } public string FinalSOAPDF(string id) { string result = string.Empty; string base64String = string.Empty; try { var actionResult = new Rotativa.ActionAsPdf("FinalSOAPDFView", new { id = id }) { FileName = "FINALSOA" + DateTime.Now.ToString("yyyymmddhhmmss") + ".pdf", PageSize = Size.A4, PageOrientation = Orientation.Portrait, PageMargins = { Left = 10, Right = 10,Top=2 }, //PageWidth = 185, // PageHeight = 245 }; string filePath = HostingEnvironment.MapPath("~/UploadDocs/"); string filename = string.Empty; filename = DateTime.Now.ToString(); filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", ""); var byteArray = actionResult.BuildPdf(ControllerContext); var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); return base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length); } catch (Exception ex) { exc.RecordUnHandledException(ex); return result; } } public ActionResult FinalSOAPDFView(string id) { //NewFinalSOADTO finalsoaDtoObj = invBAL.GetFinalSOAByOrderId_New(id); int dupUserId = 3375; CurrentSOADTO finalsoaDtoObj = invBAL.GetFinalSOAByOrderId_New(id, dupUserId); string serviceProvideurl = WebConfigurationManager.AppSettings["ServiceProviderUrl"]; ViewBag.result = finalsoaDtoObj; ViewBag.server_folder = serviceProvideurl; string AmountInWords = string.Empty; ViewBag.ToDayDate = DateTime.Now.Date; if (finalsoaDtoObj != null) { if (finalsoaDtoObj.AmountDueNow < 0) { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(finalsoaDtoObj.AmountDueNow * (-1))); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = " Rupees " + AmountInWords + " Only "; } } else { AmountInWords = invBAL.NumberToWords(Convert.ToInt64(finalsoaDtoObj.AmountDueNow)); if (!string.IsNullOrEmpty(AmountInWords)) { AmountInWords = " Rupees " + AmountInWords + " Only "; } } ViewBag.AmountDueNowInWords = AmountInWords; return View(); } else { return new EmptyResult(); } } [HttpPost] public ActionResult DownloadCustomerSOAPdf(string OrderId,int LastModifiedBy,string SOAType) { SuccessInfo sinfo = new SuccessInfo(); infoDeatails infoDetailsObj = new infoDeatails(); string base64 = string.Empty; try { context.Configuration.ProxyCreationEnabled = false; if (SOAType == "CurrentSOA") { base64 = CurrentSOAPDF(OrderId); } else if (SOAType == "CustomerAccountSummary") { base64 = CustomerAccountSummaryPDF(OrderId); } else if (SOAType == "FinalSOA") { base64 = FinalSOAPDF(OrderId); } if (!string.IsNullOrEmpty(base64)) { sinfo.errorcode = 0; sinfo.errormessage = "Customer SOA PDF Downloaded Successfully"; infoDetailsObj.info = sinfo; var result = new { result = base64,info= sinfo }; return Json(result, JsonRequestBehavior.AllowGet); } else { sinfo.errorcode = 1; sinfo.errormessage = "Unable to Download Customer SOA"; var result = new { result = base64, info = sinfo }; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { sinfo.errorcode = 1; sinfo.errormessage = "Failed to Download"; var result = new { result = base64, info = sinfo }; return Json(result, JsonRequestBehavior.AllowGet); } } # endregion public ActionResult AFSFooter(string Page, string ToPage) { ViewBag.Page = Page; ViewBag.ToPage = ToPage; return View(); } public ActionResult AFSHeader(string Page, string Cname, string UnitNO, DateTime Dated) { ViewBag.Page = Page; ViewBag.CustomerName = Cname; ViewBag.UnitNO = UnitNO; ViewBag.Dated = Dated.ToString("dd-MMM-yy"); return View(); } public class JsonVlaues { public int LastModifiedBy_Id { get; set; } public int CollectionsID { get; set; } } public class InvoiceJsonVlaues { public int LastModifiedById { get; set; } public string SAPCustomerID { get; set; } public int PrimaryObjectID { get; set; } public string EmailCC { get; set; } public string EmailTO { get; set; } public string EmailBody { get; set; } public string ProfarmaEmailType { get; set; } public Nullable<DateTime> PreInvoiceDate { get; set; } public Nullable<bool> DateFlag { get; set; } public string cemEmail { get; set; } public string emailMsgBody { get; set; } } public class infoDeatails { public SuccessInfo info { get; set; } } public class RECEIPTDTO { public int? OfferID { get; set; } public string CompanyName { get; set; } public string CompanyAddress { get; set; } public string CustomerName { get; set; } public string CustomerGSTIN { get; set; } public string CompanyLogo { get; set; } public string CompanyPAN { get; set; } public string CompanyCIN { get; set; } public string CompanyGSTIN { get; set; } public string PayeeBank { get; set; } public string PayeeName { get; set; } public string ProjectLogo { get; set; } public string ProjectName { get; set; } public DateTime Date { get; set; } public string UnitNumber { get; set; } public string SAPCustomerID { get; set; } public string PaymentMode { get; set; } public string DraweeBank { get; set; } public string ReceiptID { get; set; } public DateTime? InstrumentDate { get; set; } public DateTime? ReceivedOn { get; set; } public DateTime? ClearedOn { get; set; } public string SAPBankCode { get; set; } public decimal? Amount { get; set; } public string InstrumentNumber { get; set; } public string Block { get; set; } } } }
namespace Podemski.Musicorum.Interfaces.Entities { public interface ITrack : IEntity { IAlbum Album { get; } string Title { get; set; } string Description { get; set; } } }
/*********************************************************************** * Module: ConsumableEquipmentRepository.cs * Author: Jelena Budisa * Purpose: Definition of the Class Repository.ConsumableEquipmentRepository ***********************************************************************/ using System; using Model.Manager; using Newtonsoft.Json; using System.Collections.Generic; using System.IO; namespace Repository { public class ConsumableEquipmentRepository { private string path; public ConsumableEquipmentRepository() { string fileName = "consumableEquipment.json"; path = Path.GetFullPath(fileName); } public Model.Manager.ConsumableEquipment GetEquipment(int id) { List<ConsumableEquipment> consumableEquipment = ReadFromFile(); foreach (ConsumableEquipment e in consumableEquipment) { if (e.Id.Equals(id)) { return e; } } return null; } public List<ConsumableEquipment> GetAllEquipment() { List<ConsumableEquipment> consumableEquipment = ReadFromFile(); return consumableEquipment; } public Model.Manager.ConsumableEquipment SetEquipment(Model.Manager.ConsumableEquipment equipment) { List<ConsumableEquipment> consumableEquipment = ReadFromFile(); foreach (ConsumableEquipment e in consumableEquipment) { if (e.Id.Equals(equipment.Id)) { e.Quantity = equipment.Quantity; e.Type = equipment.Type; break; } } WriteInFile(consumableEquipment); return equipment; } public bool DeleteEquipment(int id) { List<ConsumableEquipment> consumableEquipment = ReadFromFile(); ConsumableEquipment equipmentForDelete = null; foreach (ConsumableEquipment e in consumableEquipment) { if (e.Id.Equals(id)) { equipmentForDelete = e; break; } } if (equipmentForDelete == null) { return false; } consumableEquipment.Remove(equipmentForDelete); WriteInFile(consumableEquipment); return true; } public Model.Manager.ConsumableEquipment NewEquipment(Model.Manager.ConsumableEquipment equipment) { List<ConsumableEquipment> consumableEquipment = ReadFromFile(); ConsumableEquipment searchEquipment = GetEquipment(equipment.Id); if (searchEquipment != null) { return null; } consumableEquipment.Add(equipment); WriteInFile(consumableEquipment); return equipment; } private List<ConsumableEquipment> ReadFromFile() { List<ConsumableEquipment> consumableEquipment; if (File.Exists(path)) { string json = File.ReadAllText(path); consumableEquipment = JsonConvert.DeserializeObject<List<ConsumableEquipment>>(json); } else { consumableEquipment = new List<ConsumableEquipment>(); WriteInFile(consumableEquipment); } return consumableEquipment; } private void WriteInFile(List<ConsumableEquipment> consumableEquipment) { string json = JsonConvert.SerializeObject(consumableEquipment); File.WriteAllText(path, json); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Restaurant.Models; namespace Restaurant.Repositories { public interface IMemberRepository { /* List<Member> GetMemberByMessage(Message mes); Member GetMemberBylastname();*/ IEnumerable<Member> GetAllMember(); List<Member> GetMemberBylastname(); } }
using gView.Framework.Data; using gView.Framework.FDB; using gView.Framework.Geometry; using gView.Framework.UI.Controls.Filter; using gView.Framework.UI.Dialogs; using System; using System.Collections.Generic; using System.Windows.Forms; namespace gView.Framework.UI.Controls { public partial class SpatialIndexControl : UserControl { public enum IndexType { gView = 0, GEOMETRY = 1, GEOGRAPHY = 2 } private ISpatialReference _sRef = null; private IndexType _type = IndexType.gView; public SpatialIndexControl() { InitializeComponent(); cmbIndexType.SelectedIndex = 0; } public ISpatialReference SpatialReference { set { _sRef = value; } } public IndexType Type { get { return _type; } set { cmbIndexType.SelectedIndex = (int)value; } } #region Extent public IEnvelope Extent { get { return new Envelope( (double)numLeft.Value, (double)numBottom.Value, (double)numRight.Value, (double)numTop.Value); } set { if (value == null) { return; } numLeft.Value = (decimal)value.minx; numBottom.Value = (decimal)value.miny; numRight.Value = (decimal)value.maxx; numTop.Value = (decimal)value.maxy; CalcCellSize(); } } #endregion #region Levels public int Levels { get { return (int)numLevels.Value; } set { try { numLevels.Value = value; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void numLevels_ValueChanged(object sender, EventArgs e) { CalcCellSize(); } private void CalcCellSize() { BinaryTree2 tree = new BinaryTree2(Extent, (int)numLevels.Value, 100); IEnvelope cell = tree[(long)numLevels.Value]; numCellSizeX.Value = (decimal)Math.Sqrt(cell.Width * cell.Width + cell.Height * cell.Height); } #endregion #region MSSpatial public MSSpatialIndex MSIndex { get { if (_type == IndexType.GEOMETRY) { MSSpatialIndex index = new MSSpatialIndex(); index.GeometryType = GeometryFieldType.MsGeometry; index.SpatialIndexBounds = this.Extent; index.CellsPerObject = (int)numCellsPerObject.Value; index.Level1 = (MSSpatialIndexLevelSize)cmbLevel1.SelectedIndex; index.Level2 = (MSSpatialIndexLevelSize)cmbLevel2.SelectedIndex; index.Level3 = (MSSpatialIndexLevelSize)cmbLevel3.SelectedIndex; index.Level4 = (MSSpatialIndexLevelSize)cmbLevel4.SelectedIndex; return index; } else if (_type == IndexType.GEOGRAPHY) { MSSpatialIndex index = new MSSpatialIndex(); index.GeometryType = GeometryFieldType.MsGeography; index.CellsPerObject = (int)numCellsPerObject.Value; index.Level1 = (MSSpatialIndexLevelSize)cmbLevel1.SelectedIndex; index.Level2 = (MSSpatialIndexLevelSize)cmbLevel2.SelectedIndex; index.Level3 = (MSSpatialIndexLevelSize)cmbLevel3.SelectedIndex; index.Level4 = (MSSpatialIndexLevelSize)cmbLevel4.SelectedIndex; return index; } return null; } set { // TODO } } #endregion #region Properties public ISpatialIndexDef SpatialIndexDef { get { switch (_type) { case IndexType.gView: return new gViewSpatialIndexDef( this.Extent, this.Levels); case IndexType.GEOMETRY: case IndexType.GEOGRAPHY: return MSIndex; } return null; } set { if (value is gViewSpatialIndexDef) { gViewSpatialIndexDef gvIndex = (gViewSpatialIndexDef)value; this.Extent = gvIndex.SpatialIndexBounds; this.Levels = gvIndex.Levels; cmbIndexType.SelectedIndex = 0; } else if (value is MSSpatialIndex) { MSSpatialIndex msIndex = (MSSpatialIndex)value; this.Extent = new Envelope(msIndex.SpatialIndexBounds); numCellsPerObject.Value = msIndex.CellsPerObject; cmbLevel1.SelectedIndex = (int)msIndex.Level1; cmbLevel2.SelectedIndex = (int)msIndex.Level2; cmbLevel3.SelectedIndex = (int)msIndex.Level3; cmbLevel4.SelectedIndex = (int)msIndex.Level4; if (msIndex.GeometryType == GeometryFieldType.MsGeometry) { cmbIndexType.SelectedIndex = 1; } else { cmbIndexType.SelectedIndex = 2; } } } } public bool IndexTypeIsEditable { get { return cmbIndexType.Enabled; } set { cmbIndexType.Enabled = value; } } #endregion async private void btnImport_Click(object sender, EventArgs e) { List<ExplorerDialogFilter> filters = new List<ExplorerDialogFilter>(); filters.Add(new OpenDataFilter()); ExplorerDialog dlg = new ExplorerDialog("Import Extent", filters, true); dlg.MulitSelection = true; if (dlg.ShowDialog() == DialogResult.OK) { IEnvelope bounds = null; foreach (IExplorerObject exObject in dlg.ExplorerObjects) { var instance = await exObject?.GetInstanceAsync(); if (instance == null) { continue; } IEnvelope objEnvelope = null; if (instance is IDataset) { foreach (IDatasetElement element in await ((IDataset)instance).Elements()) { if (element == null) { continue; } objEnvelope = ClassEnvelope(element.Class); } } else { objEnvelope = ClassEnvelope(instance as IClass); } if (objEnvelope != null) { if (bounds == null) { bounds = new Envelope(objEnvelope); } else { bounds.Union(objEnvelope); } } } if (bounds != null) { this.Extent = bounds; } } } async private void btnImportDef_Click(object sender, EventArgs e) { List<ExplorerDialogFilter> filters = new List<ExplorerDialogFilter>(); filters.Add(new OpenFDBFeatureclassFilter()); ExplorerDialog dlg = new ExplorerDialog("Import Spatial Index", filters, true); dlg.MulitSelection = true; if (dlg.ShowDialog() == DialogResult.OK) { IEnvelope bounds = null; int levels = 0; foreach (IExplorerObject exObject in dlg.ExplorerObjects) { var instance = await exObject?.GetInstanceAsync(); if (instance == null) { continue; } if (instance is IFeatureClass && ((IFeatureClass)instance).Dataset != null && ((IFeatureClass)instance).Dataset.Database is IImplementsBinarayTreeDef) { IFeatureClass fc = (IFeatureClass)instance; IImplementsBinarayTreeDef fdb = (IImplementsBinarayTreeDef)fc.Dataset.Database; BinaryTreeDef def = await fdb.BinaryTreeDef(fc.Name); if (def != null) { if (bounds == null) { bounds = new Envelope(def.Bounds); } else { bounds.Union(def.Bounds); } levels = Math.Max(levels, def.MaxLevel); } } } if (bounds != null) { this.Extent = bounds; this.Levels = levels; } } } private IEnvelope ClassEnvelope(IClass Class) { if (Class is IFeatureClass) { return ProjectEnvelope( ((IFeatureClass)Class).Envelope, ((IFeatureClass)Class).SpatialReference); } else if (Class is IRasterClass && ((IRasterClass)Class).Polygon != null) { return ProjectEnvelope( ((IRasterClass)Class).Polygon.Envelope, ((IRasterClass)Class).SpatialReference); } return null; } private IEnvelope ProjectEnvelope(IEnvelope env, ISpatialReference sRef) { if (sRef == null || env == null || _sRef == null) { return env; } IGeometry geom = GeometricTransformerFactory.Transform2D(env, sRef, _sRef); if (geom != null) { return geom.Envelope; } return null; } private void cmbIndexType_SelectedIndexChanged(object sender, EventArgs e) { if (cmbIndexType.SelectedIndex == 0) { panelLevels.Visible = true; panelRaster.Visible = false; } else { panelLevels.Visible = false; panelRaster.Visible = true; if (cmbLevel1.SelectedIndex == -1) { cmbLevel1.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3); } if (cmbLevel2.SelectedIndex == -1) { cmbLevel2.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3); } if (cmbLevel3.SelectedIndex == -1) { cmbLevel3.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3); } if (cmbLevel4.SelectedIndex == -1) { cmbLevel4.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3); } } gpExtent.Enabled = cmbIndexType.SelectedIndex != 2; _type = (IndexType)cmbIndexType.SelectedIndex; } } }
namespace RosPurcell.Web.Infrastructure.DependencyInjection { using System.Linq; using System.Reflection; using Ninject.Extensions.Conventions; using Ninject.Modules; using Ninject.Syntax; using Ninject.Web.Common; using RosPurcell.Web.Handlers; using RosPurcell.Web.Infrastructure.Contexts; using RosPurcell.Web.Infrastructure.Locators; using RosPurcell.Web.Infrastructure.Mapping; using RosPurcell.Web.Infrastructure.Settings; using RosPurcell.Web.Infrastructure.ViewModelBuilding; using RosPurcell.Web.Services.Email; using RosPurcell.Web.Services.Icon; using RosPurcell.Web.Services.Logging; using RosPurcell.Web.Services.Search; using RosPurcell.Web.ViewModels.NestedContent.Base; using Zone.UmbracoMapper; public class NinjectServicesModule : NinjectModule { public override void Load() { if (Kernel == null) { return; } var assembly = typeof(NinjectServicesModule).Assembly.ManifestModule.Name; Kernel.Bind(x => x .FromAssembliesMatching(assembly) .SelectAllClasses().InheritedFrom(typeof(IHandler<,,>)) .BindAllInterfaces() .Configure(y => y.InRequestScope())); Kernel.Bind(x => x .FromAssembliesMatching(assembly) .SelectAllClasses().InheritedFrom(typeof(IHandler<,>)) .BindAllInterfaces() .Configure(y => y.InRequestScope())); Kernel.Bind(x => x .FromAssembliesMatching(assembly) .SelectAllClasses().InheritedFrom(typeof(IHandler<>)) .BindAllInterfaces() .Configure(y => y.InRequestScope())); Kernel.Bind(x => x .FromAssembliesMatching(assembly) .SelectAllClasses().InheritedFrom(typeof(ICustomMapping<>)) .BindAllInterfaces() .Configure(y => y.InRequestScope())); RegisterNestedContentModules(); Kernel.Bind<IViewModelBuilder>().To<ViewModelBuilder>(); Kernel.Bind<IHandlerResolver>().To<HandlerResolver>(); Kernel.Bind<IUmbracoMapper>().To<CustomMapper>().InSingletonScope(); Kernel.Bind<ILocator>().To<Locator>().InSingletonScope(); Kernel.Bind<IIconService>().To<IconService>().InSingletonScope(); Kernel.Bind<ILoggingService>().To<LoggingService>().InSingletonScope(); Kernel.Bind<ISearchService>().To<SearchService>().InSingletonScope(); Kernel.Bind<IEmailService>().To<EmailService>() .InSingletonScope() .WithConstructorArgument("displayName", Settings.Current.Email.DisplayName) .WithConstructorArgument("emailAddress", Settings.Current.Email.EmailAddress); Kernel.Bind<IHttpContext>().To<InjectedHttpContext>(); Kernel.Bind<IPageContext>().To<PageContext>(); } private void RegisterNestedContentModules() { var types = Assembly.GetExecutingAssembly().GetTypes() .Where(x => typeof(BaseNestedContent).IsAssignableFrom(x) && x.IsClass); foreach (var type in types) { var method = GetType().GetMethod(nameof(RegisterNamedModule), BindingFlags.NonPublic | BindingFlags.Instance); var genericMethod = method.MakeGenericMethod(type); genericMethod.Invoke(this, new object[] { Kernel, type.Name }); } } // ReSharper disable once UnusedMember.Local - called using reflection // ReSharper disable once MemberCanBeMadeStatic.Local private void RegisterNamedModule<T>(IBindingRoot kernel, string name) where T : BaseNestedContent { kernel.Bind<BaseNestedContent>().To<T>().Named(name); } } }
using ShapesGraphics.ViewModels; using System.Windows; using OpenTK.Graphics.OpenGL; namespace ShapesGraphics.Views { public partial class MainWindow : Window { private MainWindowViewModel _viewModel; public MainWindow() { InitializeComponent(); _viewModel = new MainWindowViewModel(canvas); DataContext = _viewModel; GL.ClearColor(0f, 1f, 0f, 1.0f); } private void CanvasContainerSizeChanged(object sender, SizeChangedEventArgs e) { canvas.Width = e.NewSize.Height; canvas.Height = e.NewSize.Height; } } }
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual { /// <summary> /// Representa el objeto request de Variable Lista /// </summary> /// <remarks> /// Creación : GMD 20150515 <br /> /// Modificación : <br /> /// </remarks> public class VariableListaRequest : Filtro { /// <summary> /// Codigo de variable lista /// </summary> public string CodigoVariableLista { get; set; } /// <summary> /// Codigo de variable /// </summary> public string CodigoVariable { get; set; } /// <summary> /// Nombre /// </summary> public string Nombre { get; set; } /// <summary> /// Descripcion /// </summary> public string Descripcion { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TicTacToe.Src; namespace TickTackToeApplication { class Program { private static TicTacToeService _tickTackToe; static void Main(string[] args) { _tickTackToe = new TicTacToeService(); Console.WriteLine("Welcome"); PlayTurn(); } private static void PlayTurn() { Console.Write("Player input (with ,): "); var input = Console.ReadLine(); var row = new Row(int.Parse(input.Split(',')[0])); var col = new Column(int.Parse(input.Split(',')[1])); var board = _tickTackToe.Play(row, col); Console.Clear(); if (!board.Contains("WINNER")) { for (int i = 0; i < board.Length; i++) { if ((i+1) % 3 == 0) { Console.WriteLine(board[i]); } else { Console.Write(board[i]); } } PlayTurn(); } Console.WriteLine(board); Console.WriteLine("Bye"); Console.Read(); } } }
using UnityEngine; using System.Collections; //public enum Dir_Arma { Derecha, Izquierda } public class Player : Character { public Player(string image, float size, float posX, float posY) { this.size = size; this.image = image; this.posX = posX; this.posY = posY; } public override void Start() { base.Start (); } public override void Put() { base.Put (); sc.sortingOrder = 7; this.tag = "Player"; Instantiate (this, new Vector3 (this.posX, this.posY, 0f), Quaternion.identity); } void FixedUpdate() { if (GameObject.FindWithTag ("Left") == null) { StopWalk (); } } }
using System; using System.Collections.Generic; namespace _03_Decimal_to_Binary_Converter { public class _03_Decimal_to_Binary_Converter { public static void Main() { var number = int.Parse(Console.ReadLine()); var binaryNumber = new Stack<int>(); if (number == 0) { Console.WriteLine(0); } else { while (number != 0) { var binaryDigit = number % 2; number /= 2; binaryNumber.Push(binaryDigit); } } var length = binaryNumber.Count; for (int i = 0; i < length; i++) { Console.Write(binaryNumber.Pop()); } Console.WriteLine(); } } }
namespace GraphQLDynamic.Model { public enum AttributeType { Text, Number, Date, Time, DateTime, DropDown } }
namespace HobbyGen.Controllers { using System.Collections.Generic; using HobbyGen.Controllers.Managers; using HobbyGen.Models; using HobbyGen.Persistance; using Microsoft.AspNetCore.Mvc; /// <summary> /// WebAPI for communicating with user services /// </summary> [Route("api/[controller]")] public class UserController : DatabaseController { private UserManager uManager; public UserController(GeneralContext context) : base(context) { this.uManager = new UserManager(context); } // GET api/user [HttpGet] public IEnumerable<User> Get() => this.uManager.GetAll(); // GET api/user/5 [HttpGet("id/{id}")] public User GetById(uint id) => this.uManager.GetById(id); // GET api/user/hendrik [HttpGet("name/{name}")] public IEnumerable<User> GetByName(string name) => this.uManager.SearchByName(name); // GET api/user [HttpPost("hobby")] public IEnumerable<User> GetByHobby([FromBody]string[] hobbies) => this.uManager.SearchByHobby(hobbies); // POST api/user [HttpPost] public User Post([FromBody]User u) => this.uManager.CreateUser(u); // PUT api/user/5 [HttpPut("{id}")] public User Put(uint id, [FromBody]HobbyDelta delta) => this.uManager.UpdateUser(id, delta.HobbiesAdded, delta.HobbiesRemoved); // DELETE api/user/5 [HttpDelete("{id}")] public void Delete(uint id) => this.uManager.DeleteUser(id); } }
using System.IO; using Core.FileReader.Contracts; namespace Core.FileReader { public class FileReader : IFileReader { public string ReadFile(string path) { return File.ReadAllText(path); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace PeriodicTable { //localization stuff, similar to resources //at first, I was thinking to add resources to library, but it seems unnecessary //it's used in both OxygenBalance, ChemicalSubstance and Explosives files static class Localization { //russian private static Dictionary<string, string> LocalRus; //english private static Dictionary<string, string> LocalEng; //the one we work with private static Dictionary<string, string> Local; static Localization() { LocalRus = new Dictionary<string, string>() { { "Weight", "Молекулярная масса" }, { "OxygenBalance", "Кислородный баланс" }, { "NoSubstance", "Не удалось найти химическое вещество под названием " } }; LocalEng = new Dictionary<string, string>() { { "Weight", "Weight" }, { "OxygenBalance", "Oxygen Balance" }, { "NoSubstance", "There's no such chemical substance named " } }; Local = new Dictionary<string, string>(); } //indexator with culture switch public static string GetString(string index) { //clear working dictionary //check culture //set new working dictionary if (Explosives.CurCult.Name == "ru-RU") { Local = LocalRus; } else { Local = LocalEng; } //try get value if (Local.TryGetValue(index, out string value)) return value; else throw new Exception("Can't get element " + index); } } }
// Copyright 2021 by Hextant Studios. https://HextantStudios.com // This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ using UnityEditor; namespace Hextant.Editor { // A custom inspector for Settings that does not draw the "Script" field. [CustomEditor( typeof( Settings<> ), true )] public class SettingsEditor : UnityEditor.Editor { public override void OnInspectorGUI() => DrawDefaultInspector(); // Draws the UI for exposed properties *without* the "Script" field. protected new bool DrawDefaultInspector() { if( serializedObject.targetObject == null ) return false; EditorGUI.BeginChangeCheck(); serializedObject.UpdateIfRequiredOrScript(); DrawPropertiesExcluding( serializedObject, _excludedFields ); serializedObject.ApplyModifiedProperties(); return EditorGUI.EndChangeCheck(); } static readonly string[] _excludedFields = { "m_Script" }; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Drawing; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Win32; using UseFul.ClientApi; using UseFul.ClientApi.Dtos; using UseFul.Forms.Welic; using UseFul.Uteis; using UseFul.Uteis.UI; namespace Welic.WinForm { public partial class FrmLogin : FormWelic { private readonly ConfiguracaoApi _configuracaoApi; public FrmLogin() { InitializeComponent(); _configuracaoApi = new ConfiguracaoApi(); _configuracaoApi.Configurar(); Program.MainForm.DefinirApi(_configuracaoApi.ObterClientApiPadraoNaoAutenticado()); } private void CarregarDadosDoUltimoAcesso() { try { const string path = @"SOFTWARE\Solution\Welic\"; RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(path); if (registryKey != null) { //if (registryKey.GetValue("Empresa_Padrao") != null) //{ // DropDownListEmpresa.SelectedValue = registryKey.GetValue("Empresa_Padrao"); //} if (registryKey.GetValue("Usuario_Padrao") != null) { txtUsuario.Text = registryKey.GetValue("Usuario_Padrao").ToString(); txtSenha.Select(); } registryKey.Close(); } } catch (Exception exception) { AppLogging.LogException("Erro carregar o registro", exception, LogType.Error); } } private void Login() { try { StartWaitCursor(); AutenticacaoApi(); Seguranca.BuscaAutenticacaoUsuario(txtUsuario.Text, txtSenha.Text); CarregarSistema(); } catch (CustomException exception) { ProcessMessage(exception.Message, MessageType.Error); } catch (Exception exception) { ProcessMessage(exception.Message, MessageType.Error); AppLogging.LogException("Erro ao Efetuar o Login.", exception, LogType.Error); } StopWaitCursor(); } private void AutenticacaoApi() { _configuracaoApi.Autenticar(txtUsuario.Text.Trim(), txtSenha.Text); if (CboEmpresa.SelectedItem is EmpresaDto empresaSelecionada) { HttpResponseMessage response = ClienteApi.Instance.RequisicaoGet($"Empresas/ValidaEmpresa/{txtUsuario.Text}/{empresaSelecionada.IdEmpresa}"); bool retorno = ClienteApi.Instance.ObterResposta<bool>(response); if (retorno) { ConfigurarOAcesso(_configuracaoApi.Usuario); } else { throw CustomErro.Erro("Usuário não tem permissão de acesso a empresa selecionada."); } } } private void GravarNoRegistroOsDadosDoUltimoAcesso() { try { const string path = @"SOFTWARE\Solutions\Welic\"; RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(path); if (registryKey != null) { registryKey.SetValue("Usuario_Padrao", txtUsuario.Text); registryKey.SetValue("Empresa_Padrao", CboEmpresa.SelectedValue); registryKey.Close(); } } catch (Exception exception) { AppLogging.LogException("Erro Registro", exception, LogType.Error); } } private void CarregarSistema() { Program.MainForm.EmpresaLogin = CboEmpresa.SelectedItem as EmpresaDto; DialogResult = DialogResult.OK; Program.MainForm.Show(); } private void ConfigurarOAcesso(string usuario) { Program.MainForm.UsuarioLogin = UserDto.Instance.ConsultaUsuarioPorEmail(usuario); GravarNoRegistroOsDadosDoUltimoAcesso(); } private void CarregarEmpresa() { StartWaitCursor(); try { HttpResponseMessage response = ClienteApi.Instance.RequisicaoGet("empresas/get"); BindingComboEmpresa.DataSource = ClienteApi.Instance.ObterResposta<List<EmpresaDto>>(response); } catch (CustomException Exception) { ProcessMessage(Exception.Message, MessageType.Error); } catch (Exception exception) { ProcessMessage(exception.Message, MessageType.Error); } StopWaitCursor(); } private void btFechar_Click(object sender, EventArgs e) { if (DialogResult != DialogResult.OK) { Application.Exit(); } } private void btEntrar_Click(object sender, EventArgs e) { Login(); //if (string.IsNullOrEmpty(txtUsuario.Text) || string.IsNullOrEmpty(txtSenha.Text)) // MessageBox.Show("Usuário ou senha não preenchido!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning); //else //{ // try // { // string banco = string.Empty; // if (File.Exists(@"K:/cert_sis.omt")) // { // FormLoginDesenvolvedor fLoginDes = new FormLoginDesenvolvedor(); // fLoginDes.ShowDialog(); // banco = fLoginDes.Banco; // } // else // banco = "ACAD"; // else // { // this.Dispose(); // } // } // catch (Exception ex) // { // MessageBox.Show("Falha ao tentar conectar ao banco.\nMotivo:" + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} } private void btFechar_MouseEnter(object sender, EventArgs e) { btFechar.Visible = true; btFechar.Focus(); } private void btFecharRed_Click(object sender, EventArgs e) { Application.Exit(); } private void btFecharRed_MouseLeave(object sender, EventArgs e) { btFechar.Visible = false; } private void btEntra_Click(object sender, EventArgs e) { btEntrar_Click(btEntrar, e); } private void FormLogin_Load(object sender, EventArgs e) { try { //lblVersion.Text = $@"Versão - {Application.VersaoSistema}"; //DefinirConexao(); CarregarEmpresa(); CarregarDadosDoUltimoAcesso(); #if (DEBUG) txtUsuario.Text = ConfigurationManager.AppSettings["Usuario-Padrao"]; txtSenha.Text = ConfigurationManager.AppSettings["Senha-Padrao"]; btEntrar.PerformLayout(); #endif } catch (CustomException Exception) { ProcessMessage(Exception.Message, MessageType.Error); } catch (Exception exception) { ProcessMessage(exception.Message, MessageType.Error); AppLogging.LogException("Erro ao Efetuar o Login.", exception, LogType.Error); } //Autenticacao a = new Autenticacao(); //if (a.AutenticaTemporiaUsuario()) // this.Close(); } } }
using System; using VisitorReal.Model; using Xunit; namespace VisitorReal.Test { public class VisitorRealTest { private Employees _employees; public VisitorRealTest() { _employees = new Employees(); _employees.Attach(new Clerk()); _employees.Attach(new Director()); _employees.Attach(new President()); } [Fact] public void IncomeVisitorTest() { _employees.Accept(new IncomeVisitor()); Assert.Equal(27500, (int)(_employees.Get("Hank").Income)); Assert.Equal(38500, (int)(_employees.Get("Elly").Income)); } [Fact] public void VacationVisitorTest() { _employees.Accept(new VacationVisitor()); Assert.Equal(24, _employees.Get("Dick").VacationDays); Assert.Equal(19, _employees.Get("Elly").VacationDays); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using CODE.Framework.Core.Utilities; using CODE.Framework.Wpf.Utilities; namespace CODE.Framework.Wpf.Layout { /// <summary> /// Special layout panel geared towards rendering 1-to-many UIs (such as customers and their orders) /// </summary> public class OneToManyPanel : Panel { /// <summary>Object used to render the captions</summary> public AutoLayoutHeaderRenderer CaptionRenderer { get { return (AutoLayoutHeaderRenderer)GetValue(CaptionRendererProperty); } set { SetValue(CaptionRendererProperty, value); } } /// <summary>Object used to render the captions</summary> public static readonly DependencyProperty CaptionRendererProperty = DependencyProperty.Register("CaptionRenderer", typeof(AutoLayoutHeaderRenderer), typeof(OneToManyPanel), new UIPropertyMetadata(null, InvalidateEverything)); /// <summary>Font family used to render group headers</summary> public FontFamily CaptionFontFamily { get { return (FontFamily)GetValue(CaptionFontFamilyProperty); } set { SetValue(CaptionFontFamilyProperty, value); } } /// <summary>Font family used to render group headers</summary> public static readonly DependencyProperty CaptionFontFamilyProperty = DependencyProperty.Register("CaptionFontFamily", typeof(FontFamily), typeof(OneToManyPanel), new UIPropertyMetadata(new FontFamily("Segoe UI"), InvalidateEverything)); /// <summary>Font style used to render group headers</summary> public FontStyle CaptionFontStyle { get { return (FontStyle)GetValue(CaptionFontStyleProperty); } set { SetValue(CaptionFontStyleProperty, value); } } /// <summary>Font style used to render group headers</summary> public static readonly DependencyProperty CaptionFontStyleProperty = DependencyProperty.Register("CaptionFontStyle", typeof(FontStyle), typeof(OneToManyPanel), new UIPropertyMetadata(FontStyles.Normal, InvalidateEverything)); /// <summary>Font weight used to render group headers</summary> public FontWeight CaptionFontWeight { get { return (FontWeight)GetValue(CaptionFontWeightProperty); } set { SetValue(CaptionFontWeightProperty, value); } } /// <summary>Font weight used to render group headers</summary> public static readonly DependencyProperty CaptionFontWeightProperty = DependencyProperty.Register("CaptionFontWeight", typeof(FontWeight), typeof(OneToManyPanel), new UIPropertyMetadata(FontWeights.Bold, InvalidateEverything)); /// <summary>Font size used to render group headers</summary> public double CaptionFontSize { get { return (double)GetValue(CaptionFontSizeProperty); } set { SetValue(CaptionFontSizeProperty, value); } } /// <summary>Font size used to render group headers</summary> public static readonly DependencyProperty CaptionFontSizeProperty = DependencyProperty.Register("CaptionFontSize", typeof(double), typeof(OneToManyPanel), new UIPropertyMetadata(12d, InvalidateEverything)); /// <summary>Foreground brush used to render group headers</summary> public Brush CaptionForegroundBrush { get { return (Brush)GetValue(CaptionForegroundBrushProperty); } set { SetValue(CaptionForegroundBrushProperty, value); } } /// <summary>Foreground brush used to render group headers</summary> public static readonly DependencyProperty CaptionForegroundBrushProperty = DependencyProperty.Register("CaptionForegroundBrush", typeof(Brush), typeof(OneToManyPanel), new UIPropertyMetadata(Brushes.Black, InvalidateEverything)); /// <summary>Indicates whether the general layout is horizontal or vertical</summary> public Orientation Orientation { get { return (Orientation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } /// <summary>Indicates whether the general layout is horizontal or vertical</summary> public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(OneToManyPanel), new UIPropertyMetadata(Orientation.Vertical, InvalidateEverything)); /// <summary>Spacing between the 2 elements</summary> public double Spacing { get { return (double)GetValue(SpacingProperty); } set { SetValue(SpacingProperty, value); } } /// <summary>Spacing between the 2 elements</summary> public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register("Spacing", typeof(double), typeof(OneToManyPanel), new UIPropertyMetadata(8d, InvalidateEverything)); /// <summary>Spacing between the caption and the element</summary> public double CaptionSpacing { get { return (double)GetValue(CaptionSpacingProperty); } set { SetValue(CaptionSpacingProperty, value); } } /// <summary>Spacing between the caption and the element</summary> public static readonly DependencyProperty CaptionSpacingProperty = DependencyProperty.Register("CaptionSpacing", typeof(double), typeof(OneToManyPanel), new UIPropertyMetadata(8d, InvalidateEverything)); /// <summary>Caption for elements within a one-to-many panel</summary> public static readonly DependencyProperty CaptionProperty = DependencyProperty.RegisterAttached("Caption", typeof(string), typeof(OneToManyPanel), new UIPropertyMetadata("", InvalidateEverything)); /// <summary>Caption for elements within a one-to-many panel</summary> /// <param name="obj">The dependency object the value is associated with</param> public static string GetCaption(DependencyObject obj) { return (string)obj.GetValue(CaptionProperty); } /// <summary>Caption for elements within a one-to-many panel</summary> /// <param name="obj">The dependency object the value is associated with</param> /// <param name="value">Value</param> public static void SetCaption(DependencyObject obj, string value) { obj.SetValue(CaptionProperty, value); } /// <summary>Invalidates all layout, measurement, and rendering</summary> /// <param name="dependencyObject">One-To-Many panel to invalidate</param> /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void InvalidateEverything(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var panel = dependencyObject as OneToManyPanel; if (panel != null) { panel.InvalidateArrange(); panel.InvalidateMeasure(); panel.InvalidateVisual(); } else { var element = dependencyObject as FrameworkElement; if (element != null && element.Parent != null) InvalidateEverything(element.Parent, e); } } /// <summary> /// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement"/>-derived class. /// </summary> /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param> /// <returns> /// The size that this element determines it needs during layout, based on its calculations of child element sizes. /// </returns> protected override Size MeasureOverride(Size availableSize) { if (Children.Count != 2) return base.MeasureOverride(availableSize); // Not much we can do until we have exactly two elements; // First, we check whether we have any headers _headers.Clear(); var header1 = GetCaption(Children[0]); var header2 = GetCaption(Children[1]); if (Orientation == Orientation.Vertical) { var maxHeaderHeight = 0d; if (!string.IsNullOrEmpty(header1) || !string.IsNullOrEmpty(header2)) { _headers.Add(new AutoHeaderTextRenderInfo { Text = header1, FormattedText = new FormattedText(header1, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }); _headers.Add(new AutoHeaderTextRenderInfo { Text = header2, FormattedText = new FormattedText(header2, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }); maxHeaderHeight = Math.Max(_headers[0].FormattedText.Height, _headers[1].FormattedText.Height); } var top = maxHeaderHeight + CaptionSpacing; var height = Math.Max(availableSize.Height - top, 0); var width = Math.Max((availableSize.Width - Spacing) / 2, 0); var measureSize = GeometryHelper.NewSize(width, height); Children[0].Measure(measureSize); Children[1].Measure(measureSize); } else { var top = 0d; var height = Math.Max((availableSize.Height - Spacing) / 2, 0); var height1 = height; var height2 = height; if (!string.IsNullOrEmpty(header1)) { var text1 = new AutoHeaderTextRenderInfo { Text = header1, FormattedText = new FormattedText(header1, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }; _headers.Add(text1); text1.RenderRect = GeometryHelper.NewRect(0d, 0d, availableSize.Width, text1.FormattedText.Height); top += text1.FormattedText.Height + CaptionSpacing; height1 -= (text1.FormattedText.Height + CaptionSpacing); } Children[0].Measure(GeometryHelper.NewSize(availableSize.Width, height1)); if (!string.IsNullOrEmpty(header2)) { var text2 = new AutoHeaderTextRenderInfo { Text = header2, FormattedText = new FormattedText(header2, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }; _headers.Add(text2); text2.RenderRect = GeometryHelper.NewRect(0d, 0d, availableSize.Width, text2.FormattedText.Height); top += text2.FormattedText.Height + CaptionSpacing; height2 -= (text2.FormattedText.Height + CaptionSpacing); } Children[1].Measure(GeometryHelper.NewSize(availableSize.Width, height2)); } return base.MeasureOverride(availableSize); } /// <summary> /// When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement"/> derived class. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns> /// The actual size used. /// </returns> protected override Size ArrangeOverride(Size finalSize) { if (Children.Count != 2) return base.ArrangeOverride(finalSize); // Not much we can do until we have exactly two elements; // First, we check whether we have any headers _headers.Clear(); var header1 = GetCaption(Children[0]); var header2 = GetCaption(Children[1]); if (Orientation == Orientation.Vertical) { var maxHeaderHeight = 0d; if (!string.IsNullOrEmpty(header1) || !string.IsNullOrEmpty(header2)) { _headers.Add(new AutoHeaderTextRenderInfo { Text = header1, FormattedText = new FormattedText(header1, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }); _headers.Add(new AutoHeaderTextRenderInfo { Text = header2, FormattedText = new FormattedText(header2, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }); maxHeaderHeight = Math.Max(_headers[0].FormattedText.Height, _headers[1].FormattedText.Height); } var top = maxHeaderHeight + CaptionSpacing; var height = Math.Max(finalSize.Height - top, 0); var width = Math.Max((finalSize.Width - Spacing) / 2, 0); Children[0].Arrange(GeometryHelper.NewRect(0d, top, width, height)); Children[1].Arrange(GeometryHelper.NewRect(width + Spacing, top, width, height)); if (maxHeaderHeight > 0d) { _headers[0].RenderRect = GeometryHelper.NewRect(0d, 0d, width, maxHeaderHeight); _headers[1].RenderRect = GeometryHelper.NewRect(width + Spacing, 0d, width, maxHeaderHeight); } } else { var top = 0d; var height = Math.Max((finalSize.Height - Spacing) / 2, 0); var height1 = height; var height2 = height; if (!string.IsNullOrEmpty(header1)) { var text1 = new AutoHeaderTextRenderInfo { Text = header1, FormattedText = new FormattedText(header1, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }; _headers.Add(text1); text1.RenderRect = GeometryHelper.NewRect(0d, 0d, finalSize.Width, text1.FormattedText.Height); top += text1.FormattedText.Height + CaptionSpacing; height1 -= (text1.FormattedText.Height + CaptionSpacing); } Children[0].Arrange(GeometryHelper.NewRect(0d, top, finalSize.Width, height1)); if (!string.IsNullOrEmpty(header2)) { var text2 = new AutoHeaderTextRenderInfo { Text = header2, FormattedText = new FormattedText(header2, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(CaptionFontFamily, CaptionFontStyle, CaptionFontWeight, FontStretches.Normal), CaptionFontSize, CaptionForegroundBrush) }; _headers.Add(text2); text2.RenderRect = GeometryHelper.NewRect(0d, 0d, finalSize.Width, text2.FormattedText.Height); top += text2.FormattedText.Height + CaptionSpacing; height2 -= (text2.FormattedText.Height + CaptionSpacing); } Children[1].Arrange(GeometryHelper.NewRect(0d, top, finalSize.Width, height2)); } return finalSize; } private readonly List<AutoHeaderTextRenderInfo> _headers = new List<AutoHeaderTextRenderInfo>(); /// <summary> /// Draws the content of a <see cref="T:System.Windows.Media.DrawingContext"/> object during the render pass of a <see cref="T:System.Windows.Controls.Panel"/> element. /// </summary> /// <param name="dc">The <see cref="T:System.Windows.Media.DrawingContext"/> object to draw.</param> protected override void OnRender(DrawingContext dc) { base.OnRender(dc); if (CaptionRenderer == null) CaptionRenderer = new AutoLayoutHeaderRenderer(); var offset = new Point(); foreach (var header in _headers) CaptionRenderer.RenderHeader(dc, header, 1d, offset); } } }
using System; using System.Collections.Generic; using System.Text; using Raiding.Models; namespace Raiding.Core { public class Engine : IEngine { private const string INVALID_HERO = "Invalid hero!"; public Engine() { } public void Run() { List<BaseHero> allHero = new List<BaseHero>(); BaseHero hero = null; int lines = int.Parse(Console.ReadLine()); int allDmg = 0; int counter = 0; while (lines != counter) { string name = Console.ReadLine(); string heroClass = Console.ReadLine(); try { switch (heroClass) { case "Druid": hero = new Druid(name); break; case "Paladin": hero = new Paladin(name); break; case "Rogue": hero = new Rogue(name); break; case "Warrior": hero = new Warrior(name); break; default: throw new InvalidOperationException(INVALID_HERO); } counter++; allDmg += hero.Power; allHero.Add(hero); } catch (InvalidOperationException ioe) { Console.WriteLine(ioe.Message); } } foreach (var heros in allHero) { Console.WriteLine(heros.CastAbility()); } string result = EndGame(allDmg); Console.WriteLine(result); } private string EndGame(int allDmg) { int bossDmg = int.Parse(Console.ReadLine()); if (allDmg >= bossDmg) { return "Victory!"; } return "Defeat..."; } } }
using LimenawebApp.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data.Entity; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; namespace LimenawebApp.Controllers { public class FormsActionsController : Controller { private dbLimenaEntities dblim = new dbLimenaEntities(); private dbComerciaEntities dbcmk = new dbComerciaEntities(); private DLI_PROEntities dlipro = new DLI_PROEntities(); public class MyObj_formtemplate { public string id { get; set; } public string text { get; set; } public string value { get; set; } } public class subcategories { public string FirmCode { get; set; } public string FirmName { get; set; } public string Category { get; set; } public Boolean isselected { get; set; } } public class categories { public string FirmCode { get; set; } public string FirmName { get; set; } public string Customer { get; set; } public Boolean isselected { get; set; } } public class brands { public string FirmCode { get; set; } public string FirmName { get; set; } public string Customer { get; set; } public Boolean isselected { get; set; } } public class productline { public string Id_subcategory { get; set; } public string SubCategory { get; set; } public string Brand { get; set; } public Boolean isselected { get; set; } } public class brandcompetitor { public string Id_brandc { get; set; } public string namec { get; set; } public string Brand { get; set; } public Boolean isselected { get; set; } } public JsonResult Finish_activity(string id, string lat, string lng, string check_out) { try { int IDU = Convert.ToInt32(Session["IDusuario"]); if (id != null) { int act = Convert.ToInt32(id); ActivitiesM activity = dbcmk.ActivitiesM.Find(act); //if (lat != null || lat != "") //{ // //Guardamos el log de la actividad // ActivitiesM_log nuevoLog = new ActivitiesM_log(); // nuevoLog.latitude = lat; // nuevoLog.longitude = lng; // nuevoLog.ID_usuario = IDU; // nuevoLog.ID_activity = Convert.ToInt32(id); // nuevoLog.fecha_conexion = Convert.ToDateTime(check_out); // nuevoLog.query1 = ""; // nuevoLog.query2 = ""; // nuevoLog.action = "FINISH ACTIVITY - " + activity.description; // nuevoLog.ip = ""; // nuevoLog.hostname = ""; // nuevoLog.typeh = ""; // nuevoLog.continent_name = ""; // nuevoLog.country_code = ""; // nuevoLog.country_name = ""; // nuevoLog.region_code = ""; // nuevoLog.region_name = ""; // nuevoLog.city = ""; // dbcmk.ActivitiesM_log.Add(nuevoLog); // dbcmk.SaveChanges(); //} activity.check_out = Convert.ToDateTime(check_out); activity.isfinished = true; dbcmk.Entry(activity).State = EntityState.Modified; dbcmk.SaveChanges(); return Json(new { Result = "Success" }); } return Json(new { Result = "Warning" }); } catch (Exception ex) { return Json(new { Result = "Warning" + ex.Message }); } } public JsonResult Finish_activitySurvey(string id, string lat, string lng, string check_out) { try { int IDU = Convert.ToInt32(Session["IDusuario"]); if (id != null) { int act = Convert.ToInt32(id); Tasks activity = dbcmk.Tasks.Find(act); //if (lat != null || lat != "") //{ // //Guardamos el log de la actividad // ActivitiesM_log nuevoLog = new ActivitiesM_log(); // nuevoLog.latitude = lat; // nuevoLog.longitude = lng; // nuevoLog.ID_usuario = IDU; // nuevoLog.ID_activity = Convert.ToInt32(id); // nuevoLog.fecha_conexion = Convert.ToDateTime(check_out); // nuevoLog.query1 = ""; // nuevoLog.query2 = ""; // nuevoLog.action = "FINISH ACTIVITY - " + activity.description; // nuevoLog.ip = ""; // nuevoLog.hostname = ""; // nuevoLog.typeh = ""; // nuevoLog.continent_name = ""; // nuevoLog.country_code = ""; // nuevoLog.country_name = ""; // nuevoLog.region_code = ""; // nuevoLog.region_name = ""; // nuevoLog.city = ""; // dbcmk.ActivitiesM_log.Add(nuevoLog); // dbcmk.SaveChanges(); //} activity.end_date = Convert.ToDateTime(check_out); activity.ID_taskstatus = 4; dbcmk.Entry(activity).State = EntityState.Modified; dbcmk.SaveChanges(); return Json(new { Result = "Success" }); } return Json(new { Result = "Warning" }); } catch (Exception ex) { return Json(new { Result = "Warning" + ex.Message }); } } public ActionResult GetCategories(string customerID, string idvisit) { try { if (customerID != null) { int bra = Convert.ToInt32(customerID); try { int IDV = Convert.ToInt32(idvisit); var lstcat = dlipro.BI_Dim_Products .Where(i => i.id_brand == bra) .Select(i => new categories { FirmCode = i.id_category.ToString(), FirmName = i.category_name, isselected = false, Customer = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); var itemselectcat = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 30 && br.ID_visit == IDV) select br).FirstOrDefault(); if (itemselectcat != null) { foreach (var item in lstcat) { if (item.FirmCode.ToString() == itemselectcat.fvalueText) { item.isselected = true; } } } //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstcat); return Json(result, JsonRequestBehavior.AllowGet); } catch { var lstcat = dlipro.BI_Dim_Products .Where(i => i.id_brand == bra) .Select(i => new categories { FirmCode = i.id_category.ToString(), FirmName = i.category_name, isselected = false, Customer = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstcat); return Json(result, JsonRequestBehavior.AllowGet); } } } catch { int IDV = Convert.ToInt32(idvisit); var lstcat = dlipro.BI_Dim_Products .Where(i => i.id_Vendor == customerID) .Select(i => new categories { FirmCode = i.id_category.ToString(), FirmName = i.category_name, isselected = false, Customer = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); var itemselectcat = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 30 && br.ID_visit == IDV) select br).FirstOrDefault(); if (itemselectcat != null) { foreach (var item in lstcat) { if (item.FirmCode.ToString() == itemselectcat.fvalueText) { item.isselected = true; } } } //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstcat); return Json(result, JsonRequestBehavior.AllowGet); } return Json("error", JsonRequestBehavior.AllowGet); } public ActionResult getSubcategories(string customerID, string catID, string idvisit) { try { if (catID != null) { try { int bra = Convert.ToInt32(customerID); int IDV = Convert.ToInt32(idvisit); var lstcat = dlipro.BI_Dim_Products .Where(i => i.id_category == catID && i.id_brand == bra) .Select(i => new subcategories { FirmCode = i.id_subcategory.ToString(), FirmName = i.subcategory_name, isselected = false, Category = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); var itemselectcat = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 31 && br.ID_visit == IDV) select br).FirstOrDefault(); List<string> brandssplit = new List<string>(itemselectcat.fvalueText.Split(new string[] { "," }, StringSplitOptions.None)); if (itemselectcat != null) { foreach (var item in lstcat) { if (itemselectcat.fvalueText.Contains(item.FirmCode.ToString())) { item.isselected = true; } } } //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstcat); return Json(result, JsonRequestBehavior.AllowGet); } catch { int bra = Convert.ToInt32(customerID); var lstcat = dlipro.BI_Dim_Products .Where(i => i.id_category == catID && i.id_brand == bra) .Select(i => new subcategories { FirmCode = i.id_subcategory.ToString(), FirmName = i.subcategory_name, isselected = false, Category = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstcat); return Json(result, JsonRequestBehavior.AllowGet); } } } catch { return Json("error", JsonRequestBehavior.AllowGet); } return Json("error", JsonRequestBehavior.AllowGet); } public ActionResult GetRefImg(string brandID, string catID, string subcatID) { if (brandID != null) { int subcat = Convert.ToInt32(subcatID); int brand = Convert.ToInt32(brandID); var img = (from a in dbcmk.Activities_RefImg where (a.ID_brand == brand && a.ID_category == catID && a.ID_subcategory == subcat) select a).FirstOrDefault(); var sr = ""; if (img != null) { sr = Url.Content(img.src); } string result = sr; return Json(result, JsonRequestBehavior.AllowGet); } return Json("error", JsonRequestBehavior.AllowGet); } //public ActionResult Getbrandcompetitors(string brandID, string idvisit) //{ // if (brandID != null) // { // var lstbrand = dbcmk.Brand_competitors //.Where(i => i.ID_brand == brandID) //.Select(i => new brandcompetitor { Id_brandc = i.ID_competitor.ToString(), namec = i.Name, isselected = false, Brand = "" }) //.Distinct() //.OrderByDescending(i => i.namec) //.ToList(); // int IDV = Convert.ToInt32(idvisit); // var itemselectbrand = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 15 && br.ID_visit == IDV) select br).FirstOrDefault(); // if (itemselectbrand != null) // { // foreach (var item in lstbrand) // { // if (item.Id_brandc.ToString() == itemselectbrand.fvalueText) // { // item.isselected = true; // } // } // } // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstbrand); // return Json(result, JsonRequestBehavior.AllowGet); // } // return Json("error", JsonRequestBehavior.AllowGet); //} public ActionResult Getbrands(string customerID, string idvisit, string catID, string subID) { try { if (customerID != null) { try { int sub = Convert.ToInt32(subID);//customerID is SubcategoryID int IDV = Convert.ToInt32(idvisit); var lstbrands = dlipro.BI_Dim_Products .Where(i => i.id_Vendor == customerID) .Select(i => new brands { FirmCode = i.id_brand.ToString(), FirmName = i.Brand_Name, isselected = false, Customer = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); var itemselectbrand = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 13 && br.ID_visit == IDV) select br).FirstOrDefault(); if (itemselectbrand != null) { foreach (var item in lstbrands) { if (item.FirmCode.ToString() == itemselectbrand.fvalueText) { item.isselected = true; } } } //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstbrands); return Json(result, JsonRequestBehavior.AllowGet); } catch { int sub = Convert.ToInt32(subID);//customerID is SubcategoryID var lstbrands = dlipro.BI_Dim_Products .Where(i => i.id_subcategory == sub && i.id_Vendor == customerID && i.id_category == catID) .Select(i => new brands { FirmCode = i.id_brand.ToString(), FirmName = i.Brand_Name, isselected = false, Customer = "" }) .Distinct() .OrderByDescending(i => i.FirmName) .ToList(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstbrands); return Json(result, JsonRequestBehavior.AllowGet); } } } catch { return Json("error", JsonRequestBehavior.AllowGet); } return Json("error", JsonRequestBehavior.AllowGet); } //public ActionResult Getbrands(string customerID, string idvisit, string catID, string subID) //{ // try // { // if (customerID != null) // { // try // { // int sub = Convert.ToInt32(subID);//customerID is SubcategoryID // int IDV = Convert.ToInt32(idvisit); // var lstbrands = dlipro.BI_Dim_Products // .Where(i => i.id_subcategory == sub && i.id_Vendor == customerID && i.id_category == catID) // .Select(i => new brands { FirmCode = i.id_brand.ToString(), FirmName = i.Brand_Name, isselected = false, Customer = "" }) // .Distinct() // .OrderByDescending(i => i.FirmName) // .ToList(); // var itemselectbrand = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 13 && br.ID_visit == IDV) select br).FirstOrDefault(); // if (itemselectbrand != null) // { // foreach (var item in lstbrands) // { // if (item.FirmCode.ToString() == itemselectbrand.fvalueText) // { // item.isselected = true; // } // } // } // //} // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstbrands); // return Json(result, JsonRequestBehavior.AllowGet); // } // catch { // int sub = Convert.ToInt32(subID);//customerID is SubcategoryID // var lstbrands = dlipro.BI_Dim_Products // .Where(i => i.id_subcategory == sub && i.id_Vendor == customerID && i.id_category == catID) // .Select(i => new brands { FirmCode = i.id_brand.ToString(), FirmName = i.Brand_Name, isselected = false, Customer = "" }) // .Distinct() // .OrderByDescending(i => i.FirmName) // .ToList(); // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstbrands); // return Json(result, JsonRequestBehavior.AllowGet); // } // } // } // catch // { // return Json("error", JsonRequestBehavior.AllowGet); // } // return Json("error", JsonRequestBehavior.AllowGet); //} public ActionResult GetDynamicProducts(string activityID, string ID_customer, string ID_category, string ID_subcategory, string ID_brand) { try { int idact = Convert.ToInt32(activityID); List<BI_Dim_Products> lstproduct = new List<BI_Dim_Products>(); string vendoriD = ID_customer; int brand = Convert.ToInt32(ID_brand); List<string> subcatsplit = new List<string>(ID_subcategory.Split(new string[] { "," }, StringSplitOptions.None)); List<int?> subInt = new List<int?>(); foreach (var item in subcatsplit) { subInt.Add(Convert.ToInt32(item)); } //int sub = Convert.ToInt32(ID_subcategory); using (DLI_PROEntities dbmk = new DLI_PROEntities()) { lstproduct = (dlipro.BI_Dim_Products.Where(x => x.id_brand==brand && subInt.Contains(x.id_subcategory) && x.id_category == ID_category && x.Pepperi=="Yes" && x.Active=="Y")).OrderBy(c=>c.id_subcategory).ToList<BI_Dim_Products>(); } if (lstproduct.Count > 0) { ActivitiesM act = (from actd in dbcmk.ActivitiesM where (actd.ID_activity == idact) select actd).FirstOrDefault(); var countItems = (from a in dbcmk.FormsM_details where (a.ID_visit == idact) select a).Count(); var nuevacuenta = countItems + 20; var activeSub = ""; var countp = 0; var totalpro = lstproduct.Count(); var subcatid = 0; var subcatname = ""; List<FormsM_details> detailstoinsert = new List<FormsM_details>(); foreach (var item in lstproduct) { try { if (countp == 0) { FormsM_details detalle_subcatnuevo = new FormsM_details(); //Category detalle_subcatnuevo.ID_formresourcetype = 95; detalle_subcatnuevo.fsource = ""; detalle_subcatnuevo.fdescription = ""; detalle_subcatnuevo.fvalue = 0; detalle_subcatnuevo.fvalueDecimal = 0; detalle_subcatnuevo.fvalueText = item.subcategory_name; detalle_subcatnuevo.ID_formM = act.ID_form; detalle_subcatnuevo.ID_visit = idact; detalle_subcatnuevo.original = false; //Colocamos numero de orden detalle_subcatnuevo.obj_order = nuevacuenta; //Colocamos grupo si tiene detalle_subcatnuevo.obj_group = Convert.ToInt32(item.id_subcategory); //Colocamos ID generado por editor detalle_subcatnuevo.idkey = nuevacuenta; detalle_subcatnuevo.query1 = ""; detalle_subcatnuevo.query2 = ""; detalle_subcatnuevo.parent = 13; detalle_subcatnuevo.ID_empresa = 11; detailstoinsert.Add(detalle_subcatnuevo); nuevacuenta++; subcatid= Convert.ToInt32(item.id_subcategory); subcatname = item.subcategory_name; activeSub = item.subcategory_name; } if (activeSub == item.subcategory_name) { } else { //SUBCATEGORY //inicial FormsM_details detalle_subcatnuevo2 = new FormsM_details(); //Subcategory detalle_subcatnuevo2.ID_formresourcetype = 95; detalle_subcatnuevo2.fsource = ""; detalle_subcatnuevo2.fdescription = ""; detalle_subcatnuevo2.fvalue = 0; detalle_subcatnuevo2.fvalueDecimal = 0; detalle_subcatnuevo2.fvalueText = item.subcategory_name; detalle_subcatnuevo2.ID_formM = act.ID_form; detalle_subcatnuevo2.ID_visit = idact; detalle_subcatnuevo2.original = false; //Colocamos numero de orden detalle_subcatnuevo2.obj_order = nuevacuenta; //Colocamos grupo si tiene detalle_subcatnuevo2.obj_group = Convert.ToInt32(item.id_subcategory); //Colocamos ID generado por editor detalle_subcatnuevo2.idkey = nuevacuenta; detalle_subcatnuevo2.query1 = ""; detalle_subcatnuevo2.query2 = ""; detalle_subcatnuevo2.parent = 13; detalle_subcatnuevo2.ID_empresa = 11; detailstoinsert.Add(detalle_subcatnuevo2); nuevacuenta++; subcatid = Convert.ToInt32(item.id_subcategory); subcatname = item.subcategory_name; activeSub = item.subcategory_name; } countp++; FormsM_details detalle_nuevo = new FormsM_details(); //Producto detalle_nuevo.ID_formresourcetype = 3; detalle_nuevo.fsource = item.id; detalle_nuevo.fdescription = item.Product; detalle_nuevo.fvalue = 0; detalle_nuevo.fvalueDecimal = 0; detalle_nuevo.fvalueText = item.subcategory_name; detalle_nuevo.ID_formM = act.ID_form; detalle_nuevo.ID_visit = idact; detalle_nuevo.original = false; //Colocamos numero de orden detalle_nuevo.obj_order = nuevacuenta; //Colocamos grupo si tiene detalle_nuevo.obj_group =Convert.ToInt32(item.id_subcategory); //Colocamos ID generado por editor detalle_nuevo.idkey = nuevacuenta; detalle_nuevo.query1 = ""; detalle_nuevo.query2 = ""; detalle_nuevo.parent = 13; detalle_nuevo.ID_empresa = 11; detailstoinsert.Add(detalle_nuevo); //dbcmk.SaveChanges(); var padrec = nuevacuenta; nuevacuenta++; var padredetalle = 0; //Creamos los elementos que contendra cada producto (nuevo metodo 08/04/2020) for (var i = 0; i < 31; i++) { FormsM_details detalle_nuevodeProducto = new FormsM_details(); //0=¿Producto Disponible? -8 //1=Disponible -19 //2=No Disponible-19 //3=¿Cuantas caras tiene el producto/sku? - 17 //4=¿Como se encuentra actualmente la selección de precio? -8 //5=Precio sugerido -21 //6=Precio tienda -21 //7=¿Producto posee alguna promocion? -8 //8=SI -19 //9=NO -19 //10=ANALISIS DE VISIBILIDAD Y COMUNICACIÓN - 8 //11=¿La tienda cuenta con material pop? -8 //12=SI -19 //13=NO -19 //14=¿Qué tipo de material pop y exhibicion permite la tienda colocar para el producto? (se puede seleccionar más de una opción) //15=Cross -16 //16=Bandeja -16 //17=Carrilera -16 //18=Glorificador -16 //19=Sticker Precio (preciadores) -16 //20=Cintillo (channel strips) -16 //21=Gráficas de piso -16 //22=Sticker en Nevera -16 //23=Displays / Racks -16 //24=Afiche o imágenes en paredes -16 //25=No permite -16 //26=¿En que posición de la gondola se encuetra el producto? -8 //27=Stretch Level -16 //28=Eye Level -16 //29=Touch Level -16 //30=Stoop Level -16 detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = ""; detalle_nuevodeProducto.fdescription = ""; detalle_nuevodeProducto.fvalue = 0; detalle_nuevodeProducto.fvalueDecimal = 0; detalle_nuevodeProducto.fvalueText = ""; detalle_nuevodeProducto.parent = padrec; switch (i) { case 0: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "¿Producto Disponible?"; padredetalle = nuevacuenta; break; case 1: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "SI"; detalle_nuevodeProducto.parent = padredetalle; break; case 2: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "NO"; detalle_nuevodeProducto.parent = padredetalle; break; case 3: detalle_nuevodeProducto.ID_formresourcetype = 17; detalle_nuevodeProducto.fsource = "¿Cuantas caras tiene el producto/sku?"; break; case 4: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "¿Como se encuentra actualmente la selección de precio?"; padredetalle = nuevacuenta; break; case 5: detalle_nuevodeProducto.ID_formresourcetype = 21; detalle_nuevodeProducto.fsource = "Precio sugerido"; detalle_nuevodeProducto.fvalueDecimal = Convert.ToDecimal(item.SRP); //PRECIO SUGERIDO DESDE SAP detalle_nuevodeProducto.parent = padredetalle; break; case 6: detalle_nuevodeProducto.ID_formresourcetype = 21; detalle_nuevodeProducto.fsource = "Precio tienda (editar solo si es diferente a precio sugerido)"; detalle_nuevodeProducto.parent = padredetalle; break; case 7: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "¿Producto posee alguna promocion?"; padredetalle = nuevacuenta; break; case 8: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "SI"; detalle_nuevodeProducto.parent = padredetalle; break; case 9: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "NO"; detalle_nuevodeProducto.parent = padredetalle; break; case 10: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "ANALISIS DE VISIBILIDAD Y COMUNICACIÓN"; break; case 11: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "¿La tienda cuenta con material pop?"; padredetalle = nuevacuenta; break; case 12: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "SI"; detalle_nuevodeProducto.parent = padredetalle; break; case 13: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "NO"; detalle_nuevodeProducto.parent = padredetalle; break; case 14: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "¿Qué tipo de material pop y exhibicion permite la tienda colocar para el producto? (se puede seleccionar más de una opción)"; padredetalle = nuevacuenta; break; case 15: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Cross"; detalle_nuevodeProducto.parent = padredetalle; break; case 16: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Bandeja"; detalle_nuevodeProducto.parent = padredetalle; break; case 17: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Carrilera"; detalle_nuevodeProducto.parent = padredetalle; break; case 18: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Glorificador"; detalle_nuevodeProducto.parent = padredetalle; break; case 19: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Sticker Precio (preciadores)"; detalle_nuevodeProducto.parent = padredetalle; break; case 20: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Cintillo (channel strips)"; detalle_nuevodeProducto.parent = padredetalle; break; case 21: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Gráficas de piso"; detalle_nuevodeProducto.parent = padredetalle; break; case 22: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Sticker en Nevera"; detalle_nuevodeProducto.parent = padredetalle; break; case 23: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Displays / Racks"; detalle_nuevodeProducto.parent = padredetalle; break; case 24: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "Afiche o imágenes en paredes"; detalle_nuevodeProducto.parent = padredetalle; break; case 25: detalle_nuevodeProducto.ID_formresourcetype = 16; detalle_nuevodeProducto.fsource = "No permite"; detalle_nuevodeProducto.parent = padredetalle; break; case 26: detalle_nuevodeProducto.ID_formresourcetype = 8; detalle_nuevodeProducto.fsource = "¿En que posición de la gondola se encuetra el producto?"; padredetalle = nuevacuenta; break; case 27: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "Stretch Level"; detalle_nuevodeProducto.parent = padredetalle; break; case 28: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "Eye Level"; detalle_nuevodeProducto.parent = padredetalle; break; case 29: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "Touch Level"; detalle_nuevodeProducto.parent = padredetalle; break; case 30: detalle_nuevodeProducto.ID_formresourcetype = 19; detalle_nuevodeProducto.fsource = "Stoop Level"; detalle_nuevodeProducto.parent = padredetalle; break; } //Deatalles que no se evaluan detalle_nuevodeProducto.ID_formM = act.ID_form; detalle_nuevodeProducto.ID_visit = idact; detalle_nuevodeProducto.original = false; //Colocamos numero de orden detalle_nuevodeProducto.obj_order = nuevacuenta; //Colocamos grupo si tiene detalle_nuevodeProducto.obj_group = 0; //Colocamos ID generado por editor detalle_nuevodeProducto.idkey = nuevacuenta; detalle_nuevodeProducto.query1 = ""; detalle_nuevodeProducto.query2 = ""; detalle_nuevodeProducto.ID_empresa = 11; detailstoinsert.Add(detalle_nuevodeProducto); nuevacuenta++; } } catch (Exception ex) { var error = ex.Message; } } dbcmk.BulkInsert(detailstoinsert); //FormsM_details lastitem = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == (countItems - 2)) select a).FirstOrDefault(); //lastitem.obj_order = nuevacuenta + 200; //lastitem.idkey = nuevacuenta + 200; //dbcmk.Entry(lastitem).State = EntityState.Modified; ////dbcmk.SaveChanges(); //nuevacuenta++; //FormsM_details lastitem2 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == (countItems - 1)) select a).FirstOrDefault(); //lastitem2.obj_order = nuevacuenta + 200; //lastitem2.idkey = nuevacuenta + 200; //dbcmk.Entry(lastitem2).State = EntityState.Modified; ////dbcmk.SaveChanges(); //nuevacuenta++; //FormsM_details lastitem3 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == countItems) select a).FirstOrDefault(); //lastitem3.obj_order = nuevacuenta + 200; //lastitem3.idkey = nuevacuenta + 200; //dbcmk.Entry(lastitem3).State = EntityState.Modified; //dbcmk.SaveChanges(); string result = "Success"; return Json(result, JsonRequestBehavior.AllowGet); } else { string result = "Nodata"; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { string result = "Error"; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult GetDynamicBarcodeforKlassForm(string activityID) { try { int idact = Convert.ToInt32(activityID); ActivitiesM act = (from actd in dbcmk.ActivitiesM where (actd.ID_activity == idact) select actd).FirstOrDefault(); var countItems = (from a in dbcmk.FormsM_details where (a.ID_visit == idact) select a).Count(); var nuevacuenta = countItems + 4; try { FormsM_details detalle_nuevo = new FormsM_details(); //Producto detalle_nuevo.ID_formresourcetype = 28; detalle_nuevo.fsource = ""; detalle_nuevo.fdescription = ""; detalle_nuevo.fvalue = 0; detalle_nuevo.fvalueDecimal = 0; detalle_nuevo.fvalueText = ""; detalle_nuevo.ID_formM = act.ID_form; detalle_nuevo.ID_visit = idact; detalle_nuevo.original = false; //Colocamos numero de orden detalle_nuevo.obj_order = nuevacuenta; //Colocamos grupo si tiene detalle_nuevo.obj_group = 0; //Colocamos ID generado por editor detalle_nuevo.idkey = nuevacuenta; detalle_nuevo.query1 = ""; detalle_nuevo.query2 = ""; detalle_nuevo.parent = 0; detalle_nuevo.ID_empresa = 11; dbcmk.FormsM_details.Add(detalle_nuevo); dbcmk.SaveChanges(); nuevacuenta++; } catch (Exception ex) { var error = ex.Message; } FormsM_details lastitem = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.ID_formresourcetype== 8 && a.fsource.Contains("AFTER")) select a).FirstOrDefault(); lastitem.obj_order = nuevacuenta + 400; lastitem.idkey = nuevacuenta + 400; dbcmk.Entry(lastitem).State = EntityState.Modified; dbcmk.SaveChanges(); nuevacuenta++; FormsM_details lastitem2 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.ID_formresourcetype == 5 && a.fdescription.Contains("PICTURE 2(AFTER)")) select a).FirstOrDefault(); lastitem2.obj_order = nuevacuenta + 400; lastitem2.idkey = nuevacuenta + 400; dbcmk.Entry(lastitem2).State = EntityState.Modified; dbcmk.SaveChanges(); string result = "Success"; return Json(result, JsonRequestBehavior.AllowGet); } catch { string result = "Error"; return Json(result, JsonRequestBehavior.AllowGet); } } //public ActionResult Getdisplays(string vendorID) //{ // List<OITM> lstproduct = new List<OITM>(); // string vendoriD = vendorID; // using (COM_MKEntities dbmk = new COM_MKEntities()) // { // lstproduct = (dbmk.OITM.Where(x => x.U_CustomerCM == vendoriD && x.ItemCode.Contains("DIS%"))).ToList<OITM>(); // } // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstproduct); // return Json(result, JsonRequestBehavior.AllowGet); //} //public ActionResult GetDynamicProducts(string activityID, string ID_customer) //{ // try // { // int idact = Convert.ToInt32(activityID); // List<OITM> lstproduct = new List<OITM>(); // string vendoriD = ID_customer; // using (COM_MKEntities dbmk = new COM_MKEntities()) // { // lstproduct = (dbmk.OITM.Where(x => x.U_CustomerCM == vendoriD)).ToList<OITM>(); // } // ActivitiesM act = (from actd in dbcmk.ActivitiesM where (actd.ID_activity == idact) select actd).FirstOrDefault(); // var countItems = (from a in dbcmk.FormsM_details where (a.ID_visit == idact) select a).Count(); // var nuevacuenta = countItems + 4; // foreach (var item in lstproduct) // { // try // { // FormsM_details detalle_nuevo = new FormsM_details(); // detalle_nuevo.ID_formresourcetype = 3; // detalle_nuevo.fsource = item.ItemCode; // detalle_nuevo.fdescription = item.ItemName; // detalle_nuevo.fvalue = 0; // detalle_nuevo.fvalueDecimal = 0; // detalle_nuevo.fvalueText = ""; // detalle_nuevo.ID_formM = act.ID_form; // detalle_nuevo.ID_visit = idact; // detalle_nuevo.original = false; // //Colocamos numero de orden // detalle_nuevo.obj_order = nuevacuenta; // //Colocamos grupo si tiene // detalle_nuevo.obj_group = 0; // //Colocamos ID generado por editor // detalle_nuevo.idkey = nuevacuenta; // detalle_nuevo.query1 = ""; // detalle_nuevo.query2 = ""; // detalle_nuevo.parent = 0; // detalle_nuevo.ID_empresa = GlobalVariables.ID_EMPRESA_USUARIO; // dbcmk.FormsM_details.Add(detalle_nuevo); // dbcmk.SaveChanges(); // nuevacuenta++; // } // catch (Exception ex) // { // var error = ex.Message; // } // } // FormsM_details lastitem = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == (countItems - 2)) select a).FirstOrDefault(); // lastitem.obj_order = nuevacuenta + 1; // lastitem.idkey = nuevacuenta + 1; // dbcmk.Entry(lastitem).State = EntityState.Modified; // dbcmk.SaveChanges(); // nuevacuenta++; // FormsM_details lastitem2 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == (countItems - 1)) select a).FirstOrDefault(); // lastitem2.obj_order = nuevacuenta + 1; // lastitem2.idkey = nuevacuenta + 1; // dbcmk.Entry(lastitem2).State = EntityState.Modified; // dbcmk.SaveChanges(); // nuevacuenta++; // FormsM_details lastitem3 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == countItems) select a).FirstOrDefault(); // lastitem3.obj_order = nuevacuenta + 1; // lastitem3.idkey = nuevacuenta + 1; // dbcmk.Entry(lastitem3).State = EntityState.Modified; // dbcmk.SaveChanges(); // var customer = (from cust in COM_MKdb.OCRD where (cust.CardCode == ID_customer) select cust).FirstOrDefault(); // act.ID_customer = ID_customer; // act.Customer = customer.CardName; // db.Entry(act).State = EntityState.Modified; // dbcmk.SaveChanges(); // string result = "Success"; // return Json(result, JsonRequestBehavior.AllowGet); // } // catch // { // string result = "Error"; // return Json(result, JsonRequestBehavior.AllowGet); // } //} //public ActionResult GetDynamicProductsByBrand(string activityID, string ID_customer, string ID_brand) //{ // try // { // int idact = Convert.ToInt32(activityID); // List<OITM> lstproduct = new List<OITM>(); // string vendoriD = ID_customer; // int brand = Convert.ToInt32(ID_brand); // using (COM_MKEntities dbmk = new COM_MKEntities()) // { // lstproduct = (dbmk.OITM.Where(x => x.U_CustomerCM == vendoriD && x.FirmCode == brand)).ToList<OITM>(); // } // ActivitiesM act = (from actd in dbcmk.ActivitiesM where (actd.ID_activity == idact) select actd).FirstOrDefault(); // var countItems = (from a in dbcmk.FormsM_details where (a.ID_visit == idact) select a).Count(); // var nuevacuenta = countItems + 2; // foreach (var item in lstproduct) // { // try // { // FormsM_details detalle_nuevo = new FormsM_details(); // detalle_nuevo.ID_formresourcetype = 3; // detalle_nuevo.fsource = item.ItemCode; // detalle_nuevo.fdescription = item.ItemName; // detalle_nuevo.fvalue = 0; // detalle_nuevo.fvalueDecimal = 0; // detalle_nuevo.fvalueText = ""; // detalle_nuevo.ID_formM = act.ID_form; // detalle_nuevo.ID_visit = idact; // detalle_nuevo.original = false; // //Colocamos numero de orden // detalle_nuevo.obj_order = nuevacuenta; // //Colocamos grupo si tiene // detalle_nuevo.obj_group = 0; // //Colocamos ID generado por editor // detalle_nuevo.idkey = nuevacuenta; // detalle_nuevo.query1 = ""; // detalle_nuevo.query2 = ""; // detalle_nuevo.parent = 0; // detalle_nuevo.ID_empresa = GlobalVariables.ID_EMPRESA_USUARIO; // dbcmk.FormsM_details.Add(detalle_nuevo); // dbcmk.SaveChanges(); // nuevacuenta++; // FormsM_details detalle_nuevo2 = new FormsM_details(); // detalle_nuevo2.ID_formresourcetype = 22; // detalle_nuevo2.fsource = "Expiration Date"; // detalle_nuevo2.fdescription = ""; // detalle_nuevo2.fvalue = 0; // detalle_nuevo2.fvalueDecimal = 0; // detalle_nuevo2.fvalueText = ""; // detalle_nuevo2.ID_formM = act.ID_form; // detalle_nuevo2.ID_visit = idact; // detalle_nuevo2.original = false; // //Colocamos numero de orden // detalle_nuevo2.obj_order = nuevacuenta; // //Colocamos grupo si tiene // detalle_nuevo2.obj_group = 0; // //Colocamos ID generado por editor // detalle_nuevo2.idkey = nuevacuenta; // detalle_nuevo2.query1 = ""; // detalle_nuevo2.query2 = ""; // detalle_nuevo2.parent = 0; // detalle_nuevo2.ID_empresa = GlobalVariables.ID_EMPRESA_USUARIO; // dbcmk.FormsM_details.Add(detalle_nuevo2); // dbcmk.SaveChanges(); // nuevacuenta++; // } // catch (Exception ex) // { // var error = ex.Message; // } // } // //FormsM_details lastitem = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == (countItems - 2)) select a).FirstOrDefault(); // //lastitem.obj_order = nuevacuenta + 1; // //lastitem.idkey = nuevacuenta + 1; // //dbcmk.Entry(lastitem).State = EntityState.Modified; // //dbcmk.SaveChanges(); // //nuevacuenta++; // FormsM_details lastitem2 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == (countItems - 1)) select a).FirstOrDefault(); // lastitem2.obj_order = nuevacuenta + 1; // lastitem2.idkey = nuevacuenta + 1; // dbcmk.Entry(lastitem2).State = EntityState.Modified; // dbcmk.SaveChanges(); // nuevacuenta++; // FormsM_details lastitem3 = (from a in dbcmk.FormsM_details where (a.ID_visit == idact && a.idkey == countItems) select a).FirstOrDefault(); // lastitem3.obj_order = nuevacuenta + 1; // lastitem3.idkey = nuevacuenta + 1; // dbcmk.Entry(lastitem3).State = EntityState.Modified; // dbcmk.SaveChanges(); // var customer = (from cust in COM_MKdb.OCRD where (cust.CardCode == ID_customer) select cust).FirstOrDefault(); // act.ID_customer = ID_customer; // act.Customer = customer.CardName; // dbcmk.Entry(act).State = EntityState.Modified; // dbcmk.SaveChanges(); // string result = "Success"; // return Json(result, JsonRequestBehavior.AllowGet); // } // catch // { // string result = "Error"; // return Json(result, JsonRequestBehavior.AllowGet); // } //} //public ActionResult Getgifts(string vendorID) //{ // List<OITM> lstproduct = new List<OITM>(); // string vendoriD = vendorID; // using (COM_MKEntities dbmk = new COM_MKEntities()) // { // lstproduct = (dbmk.OITM.Where(x => x.U_CustomerCM == vendoriD && x.ItmsGrpCod == 108)).ToList<OITM>(); // } // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstproduct); // return Json(result, JsonRequestBehavior.AllowGet); //} //public ActionResult Getproductline(string brandID, string idvisit) //{ // //List<view_CMKEditorB> lstproductline = new List<view_CMKEditorB>(); // //using (COM_MKEntities dbmk = new COM_MKEntities()) // //{ // // lstproductline = (dbmk.view_CMKEditorB.Where(x => x.FirmCode.ToString() == brandID)).ToList<view_CMKEditorB>(); // //} // if (brandID != null) // { // var lstproductline = COM_MKdb.view_CMKEditorB //.Where(i => i.Id_subcategory != null && i.FirmCode.ToString() == brandID) //.Select(i => new productline { Id_subcategory = i.Id_subcategory, SubCategory = i.SubCategory, isselected = false, Brand = "" }) //.Distinct() //.OrderByDescending(i => i.SubCategory) //.ToList(); // int IDV = Convert.ToInt32(idvisit); // var itemselectbrand = (from br in dbcmk.FormsM_details where (br.ID_formresourcetype == 14 && br.ID_visit == IDV) select br).FirstOrDefault(); // if (itemselectbrand != null) // { // foreach (var item in lstproductline) // { // if (item.Id_subcategory.ToString() == itemselectbrand.fvalueText) // { // item.isselected = true; // } // } // } // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstproductline); // return Json(result, JsonRequestBehavior.AllowGet); // } // return Json("error", JsonRequestBehavior.AllowGet); //} //public ActionResult Getproducts(string vendorID) //{ // List<OITM> lstproduct = new List<OITM>(); // string vendoriD = vendorID; // using (COM_MKEntities dbmk = new COM_MKEntities()) // { // lstproduct = (dbmk.OITM.Where(x => x.U_CustomerCM == vendoriD)).OrderBy(x => x.ItemName).ToList<OITM>(); // } // foreach (var item in lstproduct) // { // item.ItemName = item.ItemName.Replace("\'", ""); // } // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstproduct); // return Json(result, JsonRequestBehavior.AllowGet); //} //public ActionResult Getsamples(string vendorID) //{ // List<OITM> lstproduct = new List<OITM>(); // string vendoriD = vendorID; // using (COM_MKEntities dbmk = new COM_MKEntities()) // { // lstproduct = (dbmk.OITM.Where(x => x.U_CustomerCM == vendoriD && x.ItmsGrpCod == 107)).ToList<OITM>(); // } // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string result = javaScriptSerializer.Serialize(lstproduct); // return Json(result, JsonRequestBehavior.AllowGet); //} public JsonResult Save_activity(string id, List<MyObj_formtemplate> objects, string lat, string lng, string check_in) { List<FormsM_details> detailsForm = Session["detailsForm"] as List<FormsM_details>; try { int IDU = Convert.ToInt32(Session["IDusuario"]); if (id != null) { int act = Convert.ToInt32(id); //ActivitiesM activity = db.ActivitiesM.Find(act); //activity.check_out = Convert.ToDateTime(check_in); //db.Entry(activity).State = EntityState.Modified; //db.SaveChanges(); //if (lat != null || lat != "") //{ // //Guardamos el log de la actividad // ActivitiesM_log nuevoLog = new ActivitiesM_log(); // nuevoLog.latitude = lat; // nuevoLog.longitude = lng; // nuevoLog.ID_usuario = IDU; // nuevoLog.ID_activity = Convert.ToInt32(id); // nuevoLog.fecha_conexion = Convert.ToDateTime(check_in); // nuevoLog.query1 = ""; // nuevoLog.query2 = ""; // nuevoLog.action = "SAVE ACTIVITY - " + activity.description; // nuevoLog.ip = ""; // nuevoLog.hostname = ""; // nuevoLog.typeh = ""; // nuevoLog.continent_name = ""; // nuevoLog.country_code = ""; // nuevoLog.country_name = ""; // nuevoLog.region_code = ""; // nuevoLog.region_name = ""; // nuevoLog.city = ""; // db.ActivitiesM_log.Add(nuevoLog); // db.SaveChanges(); //} //Guardamos el detalle del formlario if (objects != null) { foreach (var item in objects) { int IDItem = Convert.ToInt32(item.id); FormsM_details detail = (from f in detailsForm where (f.ID_visit == act && f.idkey == IDItem) select f).FirstOrDefault(); if (detail == null) { } else { //if (detail.ID_formresourcetype == 3 || detail.ID_formresourcetype == 4 || detail.ID_formresourcetype == 10)//Products, Samples,Gift //{ // if (item.value == "" || item.value == null) { item.value = "0"; } // detail.fvalue = Convert.ToInt32(item.value); // db.Entry(detail).State = EntityState.Modified; // db.SaveChanges(); //} //else if (detail.ID_formresourcetype == 5) //Picture { // if (item.value == "100") { var path = detail.fsource; //eliminamos la ruta detail.fsource = ""; dbcmk.Entry(detail).State = EntityState.Modified; if (System.IO.File.Exists(Server.MapPath(path))) { try { System.IO.File.Delete(Server.MapPath(path)); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } } else if (detail.ID_formresourcetype == 9) //Input text y Electronic Signature { if (item.value == "" || item.value == null) { item.value = ""; } if (detail.fsource != item.value) { detail.fsource = item.value; dbcmk.Entry(detail).State = EntityState.Modified; } } //} else { //No hacemos nada porque no esta registrado } } } dbcmk.SaveChanges(); Session["detailsForm"] = detailsForm; } return Json(new { Result = "Success" }); } return Json(new { Result = "Warning" }); } catch (Exception ex) { return Json(new { Result = "Warning" + ex.Message }); } } public JsonResult Save_activitySurvey(string id, List<MyObj_formtemplate> objects, string lat, string lng, string check_in) { List<FormsM_detailsTasks> detailsForm = Session["detailsForm"] as List<FormsM_detailsTasks>; try { int IDU = Convert.ToInt32(Session["IDusuario"]); if (id != null) { int act = Convert.ToInt32(id); //ActivitiesM activity = db.ActivitiesM.Find(act); //activity.check_out = Convert.ToDateTime(check_in); //db.Entry(activity).State = EntityState.Modified; //db.SaveChanges(); //if (lat != null || lat != "") //{ // //Guardamos el log de la actividad // ActivitiesM_log nuevoLog = new ActivitiesM_log(); // nuevoLog.latitude = lat; // nuevoLog.longitude = lng; // nuevoLog.ID_usuario = IDU; // nuevoLog.ID_activity = Convert.ToInt32(id); // nuevoLog.fecha_conexion = Convert.ToDateTime(check_in); // nuevoLog.query1 = ""; // nuevoLog.query2 = ""; // nuevoLog.action = "SAVE ACTIVITY - " + activity.description; // nuevoLog.ip = ""; // nuevoLog.hostname = ""; // nuevoLog.typeh = ""; // nuevoLog.continent_name = ""; // nuevoLog.country_code = ""; // nuevoLog.country_name = ""; // nuevoLog.region_code = ""; // nuevoLog.region_name = ""; // nuevoLog.city = ""; // db.ActivitiesM_log.Add(nuevoLog); // db.SaveChanges(); //} //Guardamos el detalle del formlario if (objects != null) { foreach (var item in objects) { int IDItem = Convert.ToInt32(item.id); FormsM_detailsTasks detail = (from f in detailsForm where (f.ID_visit == act && f.idkey == IDItem) select f).FirstOrDefault(); if (detail == null) { } else { //if (detail.ID_formresourcetype == 3 || detail.ID_formresourcetype == 4 || detail.ID_formresourcetype == 10)//Products, Samples,Gift //{ // if (item.value == "" || item.value == null) { item.value = "0"; } // detail.fvalue = Convert.ToInt32(item.value); // db.Entry(detail).State = EntityState.Modified; // db.SaveChanges(); //} //else if (detail.ID_formresourcetype == 5) //Picture { // if (item.value == "100") { var path = detail.fsource; //eliminamos la ruta detail.fsource = ""; dbcmk.Entry(detail).State = EntityState.Modified; if (System.IO.File.Exists(Server.MapPath(path))) { try { System.IO.File.Delete(Server.MapPath(path)); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } } else if (detail.ID_formresourcetype == 9) //Input text y Electronic Signature { if (item.value == "" || item.value == null) { item.value = ""; } if (detail.fsource != item.value) { detail.fsource = item.value; dbcmk.Entry(detail).State = EntityState.Modified; } } else if (detail.ID_formresourcetype == 38) //Input text y Electronic Signature { if (item.value == "" || item.value == null) { item.value = ""; } detail.fvalueText = item.value; dbcmk.Entry(detail).State = EntityState.Modified; } //} else { //No hacemos nada porque no esta registrado } } } dbcmk.SaveChanges(); Session["detailsForm"] = detailsForm; } return Json(new { Result = "Success" }); } return Json(new { Result = "Warning" }); } catch (Exception ex) { return Json(new { Result = "Warning" + ex.Message }); } } public JsonResult Save_activityByitem(string id, List<MyObj_formtemplate> objects) { try { List<FormsM_details> detailsForm = Session["detailsForm"] as List<FormsM_details>; int act = Convert.ToInt32(id); if (detailsForm != null) { } else { using (var dbs = new dbComerciaEntities()) { detailsForm = dbs.FormsM_details.Where(a => a.ID_visit == act).ToList(); } } //int IDU = Convert.ToInt32(Session["IDusuario"]); if (id != null) { //Guardamos el detalle del formlario foreach (var item in objects) { int IDItem = Convert.ToInt32(item.id); var detail = (from f in detailsForm where (f.ID_visit == act && f.idkey == IDItem) select f).FirstOrDefault(); if (detail == null) { } else { if (detail.ID_formresourcetype == 3 || detail.ID_formresourcetype == 4 || detail.ID_formresourcetype == 10)//Products, Samples,Gift { if (item.value == "" || item.value == null) { item.value = "0"; } if (detail.fvalue != Convert.ToInt32(item.value)) { detail.fvalue = Convert.ToInt32(item.value); dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 5) //Picture { if (item.value == "100") { var path = detail.fsource; //eliminamos la ruta detail.fsource = ""; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); if (System.IO.File.Exists(Server.MapPath(path))) { try { System.IO.File.Delete(Server.MapPath(path)); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } } else if (detail.ID_formresourcetype == 6 || detail.ID_formresourcetype == 9) //Input text y Electronic Signature { if (item.value == "" || item.value == null) { item.value = ""; } if (detail.fsource != item.value) { detail.fsource = item.value; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 28) //BARCODE { if (item.value == "" || item.value == null) { item.value = ""; } if (detail.fsource != item.value) { detail.fsource = item.value; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 18) //Input number { if (item.value == "" || item.value == null) { item.value = "0"; } if (detail.fvalueDecimal != Convert.ToDecimal(item.value)) { detail.fvalueDecimal = Convert.ToDecimal(item.value); dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 21) // currency { if (item.value == "" || item.value == null) { item.value = "0"; } if (detail.fvalueDecimal != Convert.ToDecimal(item.value)) { detail.fvalueDecimal = Convert.ToDecimal(item.value); dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 22) // Date { if (item.value == "" || item.value == null) { item.value = ""; } try { detail.fvalueText = Convert.ToDateTime(item.value).ToShortDateString(); } catch { detail.fvalueText = ""; } dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); //db.Entry(detail).State = EntityState.Modified; //db.SaveChanges(); } //Select, Customer, Brands,Product line, Brand Competitors else if (detail.ID_formresourcetype == 17 || detail.ID_formresourcetype == 12 || detail.ID_formresourcetype == 13 || detail.ID_formresourcetype == 14 || detail.ID_formresourcetype == 15 || detail.ID_formresourcetype == 30 || detail.ID_formresourcetype == 31) { if (detail.fvalueText != item.value) { detail.fvalueText = item.value; //Lo guardamos como texto por si colocan ID tipo cadena detail.fdescription = item.text; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 19 || detail.ID_formresourcetype == 16) //checkbox,radio { if (item.value == "" || item.value == null) { item.value = "false"; } int seleccionado = 0; if (item.value == "false") { seleccionado = 0; } else if (item.value == "true") { seleccionado = 1; } if (detail.fvalue != seleccionado) { detail.fvalue = seleccionado; //Lo guardamos como entero dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else { //No hacemos nada porque no esta registrado } } } Session["detailsForm"] = detailsForm; return Json(new { Result = "Success" }); } //} return Json(new { Result = "Warning" }); } catch (Exception ex) { return Json(new { Result = "Warning" + ex.Message }); } } public JsonResult Save_activityByitemSurvey(string id, List<MyObj_formtemplate> objects) { try { List<FormsM_detailsTasks> detailsForm = Session["detailsForm"] as List<FormsM_detailsTasks>; int act = Convert.ToInt32(id); if (detailsForm != null) { } else { using (var dbs = new dbComerciaEntities()) { detailsForm = dbs.FormsM_detailsTasks.Where(a => a.ID_visit == act).ToList(); } } //int IDU = Convert.ToInt32(Session["IDusuario"]); if (id != null) { //Guardamos el detalle del formlario foreach (var item in objects) { int IDItem = Convert.ToInt32(item.id); var detail = (from f in detailsForm where (f.ID_visit == act && f.idkey == IDItem) select f).FirstOrDefault(); if (detail == null) { } else { if (detail.ID_formresourcetype == 3 || detail.ID_formresourcetype == 4 || detail.ID_formresourcetype == 10)//Products, Samples,Gift { if (item.value == "" || item.value == null) { item.value = "0"; } if (detail.fvalue != Convert.ToInt32(item.value)) { detail.fvalue = Convert.ToInt32(item.value); dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 5) //Picture { if (item.value == "100") { var path = detail.fsource; //eliminamos la ruta detail.fsource = ""; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); if (System.IO.File.Exists(Server.MapPath(path))) { try { System.IO.File.Delete(Server.MapPath(path)); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } } else if (detail.ID_formresourcetype == 6 || detail.ID_formresourcetype == 9) //Input text y Electronic Signature { if (item.value == "" || item.value == null) { item.value = ""; } if (detail.fsource != item.value) { detail.fsource = item.value; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 28) //BARCODE { if (item.value == "" || item.value == null) { item.value = ""; } if (detail.fsource != item.value) { detail.fsource = item.value; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 18) //Input number { if (item.value == "" || item.value == null) { item.value = "0"; } if (detail.fvalueDecimal != Convert.ToDecimal(item.value)) { detail.fvalueDecimal = Convert.ToDecimal(item.value); dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 21) // currency { if (item.value == "" || item.value == null) { item.value = "0"; } if (detail.fvalueDecimal != Convert.ToDecimal(item.value)) { detail.fvalueDecimal = Convert.ToDecimal(item.value); dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 38) // Time Range { if (item.value == "" || item.value == null) { item.value = ""; } detail.fvalueText = item.value; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } else if (detail.ID_formresourcetype == 22) // Date { if (item.value == "" || item.value == null) { item.value = ""; } try { detail.fvalueText = Convert.ToDateTime(item.value).ToShortDateString(); } catch { detail.fvalueText = ""; } dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); //db.Entry(detail).State = EntityState.Modified; //db.SaveChanges(); } //Select, Customer, Brands,Product line, Brand Competitors else if (detail.ID_formresourcetype == 17 || detail.ID_formresourcetype == 12 || detail.ID_formresourcetype == 13 || detail.ID_formresourcetype == 14 || detail.ID_formresourcetype == 15 || detail.ID_formresourcetype == 30 || detail.ID_formresourcetype == 31) { if (detail.fvalueText != item.value) { detail.fvalueText = item.value; //Lo guardamos como texto por si colocan ID tipo cadena detail.fdescription = item.text; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else if (detail.ID_formresourcetype == 19 || detail.ID_formresourcetype == 16) //checkbox,radio { if (item.value == "" || item.value == null) { item.value = "false"; } int seleccionado = 0; if (item.value == "false") { seleccionado = 0; } else if (item.value == "true") { seleccionado = 1; } if (detail.fvalue != seleccionado) { detail.fvalue = seleccionado; //Lo guardamos como entero dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); } } else { //No hacemos nada porque no esta registrado } } } Session["detailsForm"] = detailsForm; return Json(new { Result = "Success" }); } //} return Json(new { Result = "Warning" }); } catch (Exception ex) { return Json(new { Result = "Warning" + ex.Message }); } } public static Image ScaleImage(Image image, int maxWidth, int maxHeight) { var ratioX = (double)maxWidth / image.Width; var ratioY = (double)maxHeight / image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(newImage)) graphics.DrawImage(image, 0, 0, newWidth, newHeight); return newImage; } [HttpPost] public ActionResult UploadFiles(string id,string visitareal, string idvisita, string orientation) { // Checking no of files injected in Request object if (Request.Files.Count > 0) { try { HttpFileCollectionBase files = Request.Files; for (int i = 0; i < files.Count; i++) { HttpPostedFileBase file = files[i]; string fname; // Checking for Internet Explorer if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); fname = testfiles[testfiles.Length - 1]; } else { fname = file.FileName; } Image TargetImg = Image.FromStream(file.InputStream, true, true); try { int or = Convert.ToInt32(orientation); switch (or) { case 1: // landscape, do nothing break; case 8: // rotated 90 right // de-rotate: TargetImg.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone); break; case 3: // bottoms up TargetImg.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone); break; case 6: // rotated 90 left TargetImg.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone); break; } } catch { } //buscamos el id del detalle List<FormsM_details> detailsForm = Session["detailsForm"] as List<FormsM_details>; int iddetalle = Convert.ToInt32(id); int idvisitareal = Convert.ToInt32(visitareal); int idactividad = Convert.ToInt32(idvisita); FormsM_details detail = new FormsM_details(); if (detailsForm != null) { detail = (from d in detailsForm where (d.idkey == iddetalle && d.ID_visit == idactividad) select d).FirstOrDefault(); } else { using (var dbs = new dbComerciaEntities()) { detail = dbs.FormsM_details.Where(a => a.ID_visit == idactividad && a.idkey == iddetalle).FirstOrDefault(); } } var pathimg = detail.fsource; DateTime time = DateTime.Now; using (Graphics g = Graphics.FromImage(TargetImg)) { Image imagenfinal = (Image)TargetImg.Clone(); int footerHeight = 35; Bitmap bitmapImg = new Bitmap(imagenfinal);// Original Image Bitmap bitmapComment = new Bitmap(imagenfinal.Width, footerHeight);// Footer Bitmap bitmapNewImage = new Bitmap(imagenfinal.Width, imagenfinal.Height + footerHeight);//New Image Graphics graphicImage = Graphics.FromImage(bitmapNewImage); graphicImage.Clear(Color.White); graphicImage.DrawImage(bitmapImg, new Point(0, 0)); graphicImage.DrawImage(bitmapComment, new Point(bitmapComment.Width, 0)); var path = Path.Combine(Server.MapPath("~/SharedContent/images/activities"), id + "_activity_" + detail.ID_visit + "_" + time.Minute + time.Second + ".jpg"); var tam = file.ContentLength; Image newimage; //Cambiar tamano no calidad if (orientation == "-1") { newimage = ScaleImage(bitmapNewImage, 768, 1360); } else { newimage = ScaleImage(bitmapNewImage, 1360, 768); } newimage.Save(path, ImageFormat.Jpeg); bitmapImg.Dispose(); bitmapComment.Dispose(); bitmapNewImage.Dispose(); } detail.fsource = "~/SharedContent/images/activities/" + id + "_activity_" + detail.ID_visit + "_" + time.Minute + time.Second + ".jpg"; dbcmk.Entry(detail).State = EntityState.Modified; dbcmk.SaveChanges(); // Returns message that successfully uploaded } return Json("File Uploaded Successfully!"); } catch (Exception ex) { return Json("Error: " + ex.Message); } } else { return Json("No files selected."); } } private ImageCodecInfo GetEncoder(ImageFormat format) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); foreach (ImageCodecInfo codec in codecs) { if (codec.FormatID == format.Guid) { return codec; } } return null; } //CLASE PARA ALMACENAR OBJETOS public class MyObj { public string id_resource { get; set; } public string fsource { get; set; } public string fdescription { get; set; } public string fvalue { get; set; } public int idkey { get; set; } public int parent { get; set; } public IList<MyObj> children { get; set; } } public ActionResult Getformdata(string IDform) { FormsM formsM = dbcmk.FormsM.Find(Convert.ToInt32(IDform)); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = formsM.query1; //Deserealizamos los datos JavaScriptSerializer js = new JavaScriptSerializer(); MyObj[] details = js.Deserialize<MyObj[]>(formsM.query2); return Json(details, JsonRequestBehavior.AllowGet); } public int order2 = 0; public string nest = ""; public void Savelist(IList<MyObj> parentList, int formid, int parent_id = 0, int order = 0) { foreach (var item in parentList) { //AUMENTAMOS EL CONTADOR PARA ORDENAMIENTO order2++; // GUARDAMOS EL DETALLE PRINCIPAL O EL NODO HIJO FormsM_details detalle_nuevo = new FormsM_details(); if (parent_id != 0) { Console.WriteLine("GUARDANDO HIJO. PADRE ID: " + parent_id + ". ID: " + item.idkey + "description: " + item.fsource); //Si es nodo hijo se coloca el idkey del padre detalle_nuevo.parent = parent_id; item.parent = parent_id; } else { Console.WriteLine("GUARDANDO PADRE. ID: " + item.idkey + "description: " + item.fsource); //Si es nodo hijo se coloca el idkey del padre detalle_nuevo.parent = 0; item.parent = 0; } detalle_nuevo.ID_formresourcetype = Convert.ToInt32(item.id_resource); detalle_nuevo.fsource = Convert.ToString(item.fsource); detalle_nuevo.fvalueText = ""; if (Convert.ToInt32(item.id_resource) == 6) { detalle_nuevo.fsource = ""; detalle_nuevo.fvalueText = Convert.ToString(item.fsource); } detalle_nuevo.fdescription = Convert.ToString(item.fdescription); detalle_nuevo.fvalue = 0; detalle_nuevo.fvalueDecimal = 0; detalle_nuevo.ID_formM = formid; //colocamos 0 ya que esta seria la plantila detalle_nuevo.ID_visit = 0; //Se coloca true ya que con esto identificamos que es un item del template original detalle_nuevo.original = true; //Colocamos numero de orden detalle_nuevo.obj_order = order2; //Colocamos grupo si tiene detalle_nuevo.obj_group = 0; //Colocamos ID generado por editor detalle_nuevo.idkey = order2; detalle_nuevo.query1 = ""; detalle_nuevo.query2 = ""; detalle_nuevo.ID_empresa = 11; //Guardando por tipo de recurso if (Convert.ToInt32(item.id_resource) == 6) //6 es el ID de del recurso de input_text para el tipo de comentario //Categorias { detalle_nuevo.fvalue = Convert.ToInt32(item.fvalue); } dbcmk.FormsM_details.Add(detalle_nuevo); dbcmk.SaveChanges(); //FIN NODO PADRE O HIJO //VERIFICAMOS SI TIENE NODOS HIJOS Y REALIZAMOS UN BUCLE A NUESTRO CONSTRUCTOR if (item.children != null) { Savelist(item.children, formid, order2, order2); } } //Le asignamos los padres eh hijos al codigo para leerlo posteriormente JavaScriptSerializer js = new JavaScriptSerializer(); nest = js.Serialize(parentList); } [ValidateAntiForgeryToken] public ActionResult DeleteForm(string idFormD) { try { int IDform = Convert.ToInt32(idFormD); FormsM form = dbcmk.FormsM.Find(IDform); dbcmk.FormsM.Remove(form); dbcmk.SaveChanges(); var detalle = (from d in dbcmk.FormsM_details where (d.ID_formM == IDform && d.original == true) select d).ToList(); foreach (var det in detalle) { FormsM_details detf = dbcmk.FormsM_details.Find(det.ID_details); dbcmk.FormsM_details.Remove(detf); dbcmk.SaveChanges(); } //TempData["exito"] = "Form deleted successfully."; return RedirectToAction("FormsM", "Management", null); } catch (Exception ex) { //TempData["advertencia"] = "Something wrong happened, try again. " + ex.Message; return RedirectToAction("FormsM", "Management", null); } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult CreateForm([Bind(Include = "ID_form,name,description, ID_activity,active")] FormsM formsM, string nestable_output, string action, string possibleID) { formsM.active = true; formsM.query1 = nestable_output; formsM.query2 = ""; formsM.ID_empresa = 11; // codigo de LIMENA EN COMERCIA WEB APP if (ModelState.IsValid) { //Deserealizamos los datos JavaScriptSerializer js = new JavaScriptSerializer(); MyObj[] details = js.Deserialize<MyObj[]>(nestable_output); int idfinal = 0; if (details.Count() > 0) { ////Guardamos formulario //Determinamos si es un update o un create if (action == "update") { FormsM formsMi = dbcmk.FormsM.Find(Convert.ToInt32(possibleID)); formsMi.name = formsM.name; formsMi.description = formsM.description; formsMi.ID_activity = formsM.ID_activity; formsMi.query1 = nestable_output; formsMi.query2 = ""; formsMi.ID_empresa = formsM.ID_empresa; dbcmk.Entry(formsMi).State = EntityState.Modified; dbcmk.SaveChanges(); idfinal = formsMi.ID_form; //Eliminamos el detalle var detalles = (from t in dbcmk.FormsM_details where (t.ID_formM == formsMi.ID_form && t.original == true) select t).ToList(); foreach (var detalle in detalles) { FormsM_details formsMDet = dbcmk.FormsM_details.Find(detalle.ID_details); dbcmk.FormsM_details.Remove(formsMDet); dbcmk.SaveChanges(); } } else if (action == "create") { dbcmk.FormsM.Add(formsM); dbcmk.SaveChanges(); idfinal = formsM.ID_form; } ////Guardamos detalle de formulario con Original = true //Llamamos el constructor el cual consiste en un bucle "infinito" en base a los nodos padre eh hijos que contenta el array de objetos del editor //del formulario order2 = 0; if (formsM.ID_activity == 2) { Savelist_retail(details, idfinal); } else { Savelist(details, idfinal); } FormsM formsMlast = dbcmk.FormsM.Find(idfinal); formsMlast.query2 = nest; dbcmk.Entry(formsMlast).State = EntityState.Modified; dbcmk.SaveChanges(); ////*********************************************** //TempData["exito"] = "Form created successfully."; return RedirectToAction("FormsM", "Management", null); } else { //TempData["advertencia"] = "No data found, try again."; return RedirectToAction("FormsM", "Management", null); } } //TempData["advertencia"] = "Something wrong happened, try again."; return RedirectToAction("FormsM", "Home", null); } public void Savelist_retail(IList<MyObj> parentList, int formid, int parent_id = 0, int order = 0) { var mainlist = parentList; var listaColumnas = (from a in parentList where (a.id_resource == "24") select a).ToList(); foreach (var item in parentList) { //AUMENTAMOS EL CONTADOR PARA ORDENAMIENTO order2++; // GUARDAMOS EL DETALLE PRINCIPAL O EL NODO HIJO FormsM_details detalle_nuevo = new FormsM_details(); detalle_nuevo.parent = 0; detalle_nuevo.ID_formresourcetype = Convert.ToInt32(item.id_resource); detalle_nuevo.fsource = Convert.ToString(item.fsource); detalle_nuevo.fvalueText = ""; if (Convert.ToInt32(item.id_resource) == 6) { detalle_nuevo.fsource = ""; detalle_nuevo.fvalueText = Convert.ToString(item.fsource); } detalle_nuevo.fdescription = Convert.ToString(item.fdescription); detalle_nuevo.fvalue = 0; detalle_nuevo.fvalueDecimal = 0; detalle_nuevo.ID_formM = formid; //colocamos 0 ya que esta seria la plantila detalle_nuevo.ID_visit = 0; //Se coloca true ya que con esto identificamos que es un item del template original detalle_nuevo.original = true; //Colocamos numero de orden detalle_nuevo.obj_order = order2; //Colocamos grupo si tiene detalle_nuevo.obj_group = 0; //Colocamos ID generado por editor detalle_nuevo.idkey = order2; detalle_nuevo.query1 = ""; detalle_nuevo.query2 = ""; detalle_nuevo.ID_empresa = 11; //Guardando por tipo de recurso if (Convert.ToInt32(item.id_resource) == 6) //6 es el ID de del recurso de input_text para el tipo de comentario //Categorias { detalle_nuevo.fvalue = Convert.ToInt32(item.fvalue); } if (Convert.ToInt32(item.id_resource) == 24) //24 es el ID de del recurso de Column para el tipo de datos //Tipo de datos { detalle_nuevo.fvalue = Convert.ToInt32(item.fvalue); } dbcmk.FormsM_details.Add(detalle_nuevo); dbcmk.SaveChanges(); if (Convert.ToInt32(item.id_resource) == 3) { //PARA PRODUCTO foreach (var itemColumna in listaColumnas) { //AUMENTAMOS EL CONTADOR PARA ORDENAMIENTO order2++; if (itemColumna.fvalue == "16") { //Multiple choice FormsM_details Subdetalle_nuevo = new FormsM_details(); Subdetalle_nuevo.parent = detalle_nuevo.idkey; Subdetalle_nuevo.ID_formresourcetype = 16; Subdetalle_nuevo.fsource = ""; Subdetalle_nuevo.fvalueText = ""; Subdetalle_nuevo.fdescription = Convert.ToString(itemColumna.fdescription); Subdetalle_nuevo.fvalue = 0; Subdetalle_nuevo.fvalueDecimal = 0; Subdetalle_nuevo.ID_formM = formid; //colocamos 0 ya que esta seria la plantila Subdetalle_nuevo.ID_visit = 0; //Se coloca true ya que con esto identificamos que es un item del template original Subdetalle_nuevo.original = true; //Colocamos numero de orden Subdetalle_nuevo.obj_order = order2; //Colocamos grupo si tiene Subdetalle_nuevo.obj_group = 0; //Colocamos ID generado por editor Subdetalle_nuevo.idkey = order2; Subdetalle_nuevo.query1 = ""; Subdetalle_nuevo.query2 = ""; Subdetalle_nuevo.ID_empresa = 11; dbcmk.FormsM_details.Add(Subdetalle_nuevo); dbcmk.SaveChanges(); } else if (itemColumna.fvalue == "21") { //Currency FormsM_details Subdetalle_nuevo = new FormsM_details(); Subdetalle_nuevo.parent = detalle_nuevo.idkey; Subdetalle_nuevo.ID_formresourcetype = 21; Subdetalle_nuevo.fsource = ""; Subdetalle_nuevo.fvalueText = ""; Subdetalle_nuevo.fdescription = Convert.ToString(itemColumna.fdescription); Subdetalle_nuevo.fvalue = 0; Subdetalle_nuevo.fvalueDecimal = 0; Subdetalle_nuevo.ID_formM = formid; //colocamos 0 ya que esta seria la plantila Subdetalle_nuevo.ID_visit = 0; //Se coloca true ya que con esto identificamos que es un item del template original Subdetalle_nuevo.original = true; //Colocamos numero de orden Subdetalle_nuevo.obj_order = order2; //Colocamos grupo si tiene Subdetalle_nuevo.obj_group = 0; //Colocamos ID generado por editor Subdetalle_nuevo.idkey = order2; Subdetalle_nuevo.query1 = ""; Subdetalle_nuevo.query2 = ""; Subdetalle_nuevo.ID_empresa = 11; dbcmk.FormsM_details.Add(Subdetalle_nuevo); dbcmk.SaveChanges(); } } } } //Le asignamos los padres eh hijos al codigo para leerlo posteriormente JavaScriptSerializer js = new JavaScriptSerializer(); nest = js.Serialize(parentList); } //FUNCIONANDO 01/17/2020 //[HttpPost] //public ActionResult UploadFiles(string id, string idvisita, string orientation) //{ // List<FormsM_details> detailsForm = Session["detailsForm"] as List<FormsM_details>; // int act = Convert.ToInt32(id); // if (detailsForm != null) // { // } // else // { // using (var dbs = new dbComerciaEntities()) // { // detailsForm = dbs.FormsM_details.Where(a => a.ID_visit == act).ToList(); // } // } // // Checking no of files injected in Request object // if (Request.Files.Count > 0) // { // try // { // // Get all files from Request object // HttpFileCollectionBase files = Request.Files; // for (int i = 0; i < files.Count; i++) // { // //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/"; // //string filename = Path.GetFileName(Request.Files[i].FileName); // HttpPostedFileBase file = files[i]; // string fname; // // Checking for Internet Explorer // if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") // { // string[] testfiles = file.FileName.Split(new char[] { '\\' }); // fname = testfiles[testfiles.Length - 1]; // } // else // { // fname = file.FileName; // } // // Adding watermark to the image and saving it into the specified folder!!!! // //Image image = Image.FromStream(file.InputStream, true, true); // Image TargetImg = Image.FromStream(file.InputStream, true, true); // try // { // int or = Convert.ToInt32(orientation); // switch (or) // { // case 1: // landscape, do nothing // break; // case 8: // rotated 90 right // // de-rotate: // TargetImg.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone); // break; // case 3: // bottoms up // TargetImg.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone); // break; // case 6: // rotated 90 left // TargetImg.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone); // break; // } // } // catch // { // } // //buscamos el id del detalle // int idf = Convert.ToInt32(id); // FormsM_details detail = new FormsM_details(); // FormsM_details detailBrand = new FormsM_details(); // try // { // int idvisit = Convert.ToInt32(idvisita); // detail = (from d in detailsForm where (d.idkey == idf && d.ID_visit == idvisit) select d).FirstOrDefault(); // } // catch // { // var sqlQueryText = string.Format("SELECT * FROM FormsM_details WHERE query2 LIKE '{0}' and idkey='" + idf + "'", idvisita); // detail = dbcmk.FormsM_details.SqlQuery(sqlQueryText).FirstOrDefault(); //returns 0 or more rows satisfying sql query // } // try // { // int idvisit2 = Convert.ToInt32(idvisita); // detailBrand = (from d in detailsForm where (d.ID_visit == idvisit2 && d.ID_formresourcetype == 13) select d).FirstOrDefault(); // } // catch { } // var pathimg = detail.fsource; // DateTime time = DateTime.Now; // var footer = (from a in dbcmk.ActivitiesM where (a.ID_activity == detail.ID_visit) select a).FirstOrDefault(); // var customer = ""; // var date = ""; // var activi = ""; // var store = ""; // var brand = ""; // if (detailBrand != null) // { // brand = detailBrand.fdescription; // } // if (footer != null) // { // var visit = (from a in dbcmk.VisitsM where (a.ID_visit == footer.ID_visit) select a).FirstOrDefault(); // if (visit != null) // { // store = visit.store + ", " + visit.address + ", " + visit.city + ", " + visit.state; // } // customer = footer.ID_customer + "-" + footer.Customer; // date = visit.visit_date.ToShortDateString(); // activi = footer.ID_activity + "-" + footer.description; // } // using (Image watermark = Image.FromFile(Server.MapPath("~/Content/images/Logo_watermark.png"))) // using (Graphics g = Graphics.FromImage(TargetImg)) // { // Image thumb = watermark.GetThumbnailImage((TargetImg.Width / 2), (TargetImg.Height / 3), null, IntPtr.Zero); // var destX = (TargetImg.Width / 2 - thumb.Width / 2); // var destY = (TargetImg.Height / 2 - thumb.Height / 2); // g.DrawImage(watermark, new Rectangle(destX, // destY, // TargetImg.Width / 2, // TargetImg.Height / 4)); // // display a clone for demo purposes // //pb2.Image = (Image)TargetImg.Clone(); // Image imagenfinal = (Image)TargetImg.Clone(); // int footerHeight = 35; // Bitmap bitmapImg = new Bitmap(imagenfinal);// Original Image // Bitmap bitmapComment = new Bitmap(imagenfinal.Width, footerHeight);// Footer // Bitmap bitmapNewImage = new Bitmap(imagenfinal.Width, imagenfinal.Height + footerHeight);//New Image // Graphics graphicImage = Graphics.FromImage(bitmapNewImage); // graphicImage.Clear(Color.White); // graphicImage.DrawImage(bitmapImg, new Point(0, 0)); // graphicImage.DrawImage(bitmapComment, new Point(bitmapComment.Width, 0)); // graphicImage.DrawString((store + " | " + brand + " | " + date + " | " + activi), new Font("Arial", 19), new SolidBrush(Color.Black), 0, bitmapImg.Height + footerHeight / 6); // var path = Path.Combine(Server.MapPath("~/SharedContent/images/activities"), id + "_activity_" + detail.ID_visit + "_" + time.Minute + time.Second + ".jpg"); // var tam = file.ContentLength; // //if (tam < 600000) // //{ // //bitmapNewImage.Save(path, ImageFormat.Jpeg); // Image newimage; // //Cambiar tamano no calidad // if (orientation == "-1") // { // newimage = ScaleImage(bitmapNewImage, 768, 1360); // } // else // { // newimage = ScaleImage(bitmapNewImage, 1360, 768); // } // newimage.Save(path, ImageFormat.Jpeg); // bitmapImg.Dispose(); // bitmapComment.Dispose(); // bitmapNewImage.Dispose(); // } // //fname = Path.Combine(Server.MapPath("~/Content/images/ftp_demo"), fname); // //file.SaveAs(fname); // //Luego guardamos la url en la db // //Forms_details detail = dbcmk.Forms_details.Find(Convert.ToInt32(id)); //se movio hacia arriba // detail.fsource = "~/SharedContent/images/activities/" + id + "_activity_" + detail.ID_visit + "_" + time.Minute + time.Second + ".jpg"; // dbcmk.Entry(detail).State = EntityState.Modified; // dbcmk.SaveChanges(); // if (System.IO.File.Exists(Server.MapPath(pathimg))) // { // try // { // System.IO.File.Delete(Server.MapPath(pathimg)); // } // catch (System.IO.IOException e) // { // Console.WriteLine(e.Message); // } // } // } // // Returns message that successfully uploaded // return Json("File Uploaded Successfully!"); // } // catch (Exception ex) // { // return Json("Error occurred."); // } // } // else // { // return Json("No files selected."); // } //} } }
using System.Collections; using System.Collections.Generic; using AlmenaraGames; using UnityEngine; /// <summary> /// Tracks team ID /// Track if it is in the Nest /// Tracks whether it is held /// </summary> public class Egg : MonoBehaviour { //0 = red, 1 = blue public int TeamID; //Bools public bool IsHeld; public bool OutOfNest; public bool IsSpawning; public bool inWhirlpool; //Audio public AudioObject SplashSound; //Particle public GameObject EggParticle; //Colliders private Collider[] _colliders; //Play splash on contact with water private void OnCollisionEnter(Collision other) { if (other.transform.CompareTag("Water")) { MultiAudioManager.PlayAudioObject(SplashSound, transform.position); } } public void DestroyEgg() { Instantiate(EggParticle, transform.position, Quaternion.identity); Destroy(gameObject); } }
using System.Collections.Concurrent; using System.Collections.Generic; namespace gView.Framework.IO { public class ErrorReport : IErrorReport { #region IErrorReport private ConcurrentBag<string> _warnings = new ConcurrentBag<string>(); private ConcurrentBag<string> _errors = new ConcurrentBag<string>(); public void AddWarning(string warning, object source) { if (source != null) { warning = $"{warning} ({source.ToString()})"; } _warnings.Add($"Warning: {warning}"); } public void AddError(string error, object source) { if (source != null) { error = $"{error} ({source.ToString()})"; } _errors.Add($"Error: {error}"); } public IEnumerable<string> Warnings { get { return _warnings.ToArray(); } } public IEnumerable<string> Errors { get { return _errors.ToArray(); } } public void ClearErrorsAndWarnings() { if (_warnings.Count > 0) { _warnings = new ConcurrentBag<string>(); } if (_errors.Count > 0) { _errors = new ConcurrentBag<string>(); } } #endregion } }
using System; using SQLite; namespace Tianhai.OujiangApp.Schedule.Models.Preferences{ public class Token{ [PrimaryKey] public int Id{get;set;}=1; public DateTime ValidBefore{get;set;} public string AccessToken{get;set;} public bool IsLoggedIn{get;set;}=false; } }
namespace FamousQuoteQuiz.Data.RepositoryModels { public class User { public int Id { get; set; } public int RoleId { get; set; } public string UserName { get; set; } public string Password { get; set; } public bool IsActive { get; set; } public bool IsDeleted { get; set; } public byte? Mode { get; set; } } }
using LibraryCoder.UnitConversions; using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.UI.Xaml; using SampleUWP.BeamDesign; using System; using System.Diagnostics; using System.Numerics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace SampleUWP { public sealed partial class P01 : Page { // A pointer to MainPage is needed if you want to call methods or variables in MainPage. // private MainPage mainPage = MainPage.mainPagePointer; // Set up drawing session variables and initialize them for first draw on page load. // Need to use separate values in drawing session or input changes trigger premature draws. // Drawing sessions use floats vs. doubles. // Forces up are positive and forces down are negative. private float dsLength = 10; // Beam length private float dsLoadPosition = 5; // Position of load on beam from left private float dsLoad = -1000; // Beam load down (negative) private float dsReactionL = 500; // Equals -dsLoad / 2 (positive) private float dsReactionR = 500; // Equals -dsLoad / 2 (positive) private float dsShearL = 500; // Equals dsReactionL (positive) private float dsShearR = -500; // Equals -dsReactionR (negative) private float dsMoment = 2500; // Equals dsLoad * dsLength / 4 private float dsLoadMax = 1000; // Equals dsLoad private float dsShearMax = 1000; // Equals dsLoad private float dsMomentMax = 2500; // Equals dsLoad * dsLength / 4 // Input variables, use doubles for beam calculations. private double bLength; private double bLoadPosition; private double bLoad; // Enter from TextBox as positive but convert to negative in calculations!!! //private double bElasticity; // Not used yet. //private double bInertia; // Not used yet. // Do not allow beam calculation until all user input is valid, equals true. private bool bLengthValid = false; private bool bLoadPositionValid = false; private bool bLoadValid = false; // Use SI units if true, otherwise use UCS units. private bool siUnits = false; // CanvasControl Class: http://microsoft.github.io/Win2D/html/T_Microsoft_Graphics_Canvas_UI_Xaml_CanvasControl.htm public P01() { this.InitializeComponent(); W2DPrint.PrintDrawer = PageDrawer; // Set print delegate to PageDrawer method on this page. W2DPrint.printTitle = BDType01.beamDiagramLable; // Set the title bar text in the print dialog. BDLib.UnitsUSC(); // Set default units to USC vs. SI. ChangeUnits(); // Win2D doesn't like caching and will throw exception. No canvas present when coming back to page since // cleaned up Win2D before leaving page. //this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required; // Cache page state. } /* Rect imageableRect = args.PrintTaskOptions.GetPageDescription(1).ImageableRect; Vector2 leftTop = new Vector2((float)imageableRect.X, (float)imageableRect.Y); Vector2 rightBot = new Vector2(leftTop.X + (float)imageableRect.Width, leftTop.Y + (float)imageableRect.Height); */ /// <summary> /// This is invoked by XAML from canvas:CanvasControl. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void Beam_Draw(CanvasControl sender, CanvasDrawEventArgs args) { BDLib.ColorsDisplay(); // Draw all items using display color. Only applies to colors defined in Blib. Vector2 leftTop = new Vector2(0, 0); // On display use 0,0 as leftTop. Vector2 rightBot = sender.Size.ToVector2(); PageDrawer(args.DrawingSession, leftTop, rightBot); } /// <summary> /// Use same Drawer regardless of display or printing. With printing added, can not assume leftTop is 0,0 /// since need to offset for required printer margins. If using colors defined in LibBeamItems, then display colors /// can be toggled from color to black. /// </summary> /// <param name="ds"></param> /// <param name="leftTop"></param> /// <param name="rightBot"></param> private void PageDrawer(CanvasDrawingSession ds, Vector2 leftTop, Vector2 rightBot) { BDType01.BeamDraw(ds, leftTop, rightBot, dsLength, dsLoadPosition, dsLoad, dsReactionL, dsReactionR, dsShearL, dsShearR, dsMoment, dsLoadMax, dsShearMax, dsMomentMax); } /// <summary> /// Forward print request to W2DPrint to do the printing. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonPrint_Click(object sender, RoutedEventArgs e) { W2DPrint.ButtonPrintOptionSelected(sender, e); } private void ButtonCalc_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. // Calculation nomenclature from AISC Beam Diagrams and Formulas. // Positive values are up, negaitive are down. Drawing coordinates are opposite so somewhat confusing! if (!siUnits) { // Experimental to see if can access unit conversions.... // Test decimal methods. decimal L5 = LibUC.ConvertValue((decimal)bLength, EnumConversionsLength.foot, EnumConversionsLength.meter); Debug.WriteLine("ButtonCalc_Click(): Test decimal methods: bLength=[" + bLength + "] feet converted to [" + L5 + "] meters"); decimal L6 = LibUC.ConvertValue(L5, EnumConversionsLength.meter, EnumConversionsLength.foot); Debug.WriteLine("ButtonCalc_Click(): Test decimal methods: bLength=[" + L5 + "] meters converted back to [" + L6 + "] feet"); // Test double methods. double L7 = LibUC.ConvertValue(bLength, EnumConversionsLength.foot, EnumConversionsLength.meter); Debug.WriteLine("ButtonCalc_Click(): Test double methods: bLength=[" + bLength + "] feet converted to [" + L7 + "] meters"); double L8 = LibUC.ConvertValue(L7, EnumConversionsLength.meter, EnumConversionsLength.foot); Debug.WriteLine("ButtonCalc_Click(): Test double methods: bLength=[" + L7 + "] meters converted back to [" + L8 + "] feet"); // Test float methods. float L9 = LibUC.ConvertValue((float)bLength, EnumConversionsLength.foot, EnumConversionsLength.meter); Debug.WriteLine("ButtonCalc_Click(): Test float methods: bLength=[" + bLength + "] feet converted to [" + L9 + "] meters"); float L10 = LibUC.ConvertValue((float)L5, EnumConversionsLength.meter, EnumConversionsLength.foot); Debug.WriteLine("ButtonCalc_Click(): Test float methods: bLength=[" + L9 + "] meters converted back to [" + L10 + "] feet"); } double L = bLength; double a = bLoadPosition; double P = -bLoad; double b = bLength - a; double Rr = -P * a / L; double Rl = -P - Rr; double Vl = 0; // Special Case: Shear is zero at beam ends, otherwise is equal to reaction. if (a > 0) Vl = Rl; double Vr = 0; if (a < L) Vr = -Rr; double Mp = -P * a * b / L; double Mmax = -P * L / 4; // Used for scaling moment diagram. Max moment occurs when load is at center of beam. // Transfer calculated values to drawing session and initiate redraw. dsLength = (float)L; dsLoadPosition = (float)a; dsLoad = (float)P; dsReactionL = (float)Rl; dsReactionR = (float)Rr; dsShearL = (float)Vl; dsShearR = (float)Vr; dsMoment = (float)Mp; dsLoadMax = (float)P; dsShearMax = (float)P; dsMomentMax = (float)Mmax; canvas.Invalidate(); // Redraw the canvas/beam. buttonPrint.IsEnabled = true; // Enable the print button since results calculated. } private void CboxUnits_SelectionChanged(object sender, SelectionChangedEventArgs e) { _ = sender; // Discard unused parameter. string beamUnits = e.AddedItems[0].ToString(); switch (beamUnits) { case "USC": status.Text = "USC units selected"; siUnits = false; BDLib.UnitsUSC(); ChangeUnits(); break; case "SI": status.Text = "SI units selected"; siUnits = true; BDLib.UnitsSI(); ChangeUnits(); break; default: // Throw exception so error can be discovered and corrected. throw new NotSupportedException("Invalid switch (beamUnits)."); } } // Keep local since changes local page values???? private void ChangeUnits() { tboxLength.PlaceholderText = BDLib.pTextLength; tboxLoadPosition.PlaceholderText = BDLib.pTextLoadPosition; tboxLoad.PlaceholderText = BDLib.pTextLoad; tboxElasticity.PlaceholderText = BDLib.pTextElasticity; tboxInertia.PlaceholderText = BDLib.pTextInertia; // Whole bunch of issues here. Redraw using current or defalt values..... canvas.Invalidate(); } /// <summary> /// Invoked when user presses 'Enter' key. Then passes control to TboxLength_LostFocus(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxLength_KeyDown(object sender, KeyRoutedEventArgs e) { _ = sender; // Discard unused parameter. if (e.Key == Windows.System.VirtualKey.Enter) // Check if 'Enter' key was pressed. Ignore everything else. { TboxLength_LostFocus(null, null); } } /// <summary> /// Invoked when focus moves from beam length TextBox. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxLength_LostFocus(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. // Get bLength if (double.TryParse(tboxLength.Text, out bLength)) // Returns "True" if the string was converted to a double. { if (bLength > 0) { bLengthValid = true; // Converted text to double > 0. status.Text = string.Empty; } else { bLengthValid = false; // Converted text to double but <= 0. status.Text = "Invalid beam length, not greater than zero"; } } else { bLengthValid = false; // Could not convert text to double. status.Text = "Invalid beam length, not a number."; } if (bLengthValid && bLoadPositionValid && bLoadValid) { buttonCalc.IsEnabled = true; buttonCalc.Focus(FocusState.Programmatic); // Set focus on Calc button since have all needed input. } else buttonCalc.IsEnabled = false; } /// <summary> /// Invoked when user presses 'Enter' key. Then passes control to TboxLoadPosition_LostFocus(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxLoadPosition_KeyDown(object sender, KeyRoutedEventArgs e) { _ = sender; // Discard unused parameter. if (e.Key == Windows.System.VirtualKey.Enter) // Check if 'Enter' key was pressed. Ignore everything else. { TboxLoadPosition_LostFocus(null, null); } } /// <summary> /// Invoked when focus moves from load position TextBox. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxLoadPosition_LostFocus(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. // Get bLoadPosition if (double.TryParse(tboxLoadPosition.Text, out bLoadPosition)) // Returns "True" if the string was converted to a double. { if (bLoadPosition >= 0 && bLoadPosition <= bLength) { bLoadPositionValid = true; // Converted text to double. status.Text = string.Empty; } else { bLoadPositionValid = false; // Converted text to double but < 0 or greater than bEnumConversionsLength. status.Text = "Invalid load postion, does not fall on beam."; } } else { bLoadPositionValid = false; // Could not convert text to double. status.Text = "Invalid load position, not a number."; } if (bLengthValid && bLoadPositionValid && bLoadValid) { buttonCalc.IsEnabled = true; buttonCalc.Focus(FocusState.Programmatic); // Set focus on Calc button since have all needed input. } else buttonCalc.IsEnabled = false; } /// <summary> /// Invoked when user presses 'Enter' key. Then passes control to TboxLoad_LostFocus(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxLoad_KeyDown(object sender, KeyRoutedEventArgs e) { _ = sender; // Discard unused parameter. if (e.Key == Windows.System.VirtualKey.Enter) // Check if 'Enter' key was pressed. Ignore everything else. { TboxLoad_LostFocus(null, null); } } /// <summary> /// Invoked when focus moves from load TextBox. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxLoad_LostFocus(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. // Get bLoad if (double.TryParse(tboxLoad.Text, out bLoad)) // Returns "True" if the string was converted to a double. { if (bLoad > 0) //Load needs to be positive or will need to duplicate solution text layout to accomodate negative loading. { bLoadValid = true; // Converted text to double. status.Text = string.Empty; } else { bLoadValid = false; // Converted text to double but <= 0. status.Text = "Invalid beam load, not greater than zero"; } } else { bLoadValid = false; // Could not convert text to double. status.Text = "Invalid beam load, not a number."; } if (bLengthValid && bLoadPositionValid && bLoadValid) { buttonCalc.IsEnabled = true; buttonCalc.Focus(FocusState.Programmatic); // Set focus on Calc button since have all needed input. } else buttonCalc.IsEnabled = false; } /// <summary> /// Invoked when user presses 'Enter' key. Then passes control to TboxElasticity_LostFocus(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxElasticity_KeyDown(object sender, KeyRoutedEventArgs e) { _ = sender; // Discard unused parameter. if (e.Key == Windows.System.VirtualKey.Enter) // Check if 'Enter' key was pressed. Ignore everything else. { TboxElasticity_LostFocus(null, null); } } private void TboxElasticity_LostFocus(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. } /// <summary> /// Invoked when user presses 'Enter' key. Then passes control to TboxInertia_LostFocus(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TboxInertia_KeyDown(object sender, KeyRoutedEventArgs e) { _ = sender; // Discard unused parameter. if (e.Key == Windows.System.VirtualKey.Enter) // Check if 'Enter' key was pressed. Ignore everything else. { TboxInertia_LostFocus(null, null); } } private void TboxInertia_LostFocus(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. } /// <summary> /// Invoked when page loaded. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_Loaded(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. tboxLength.Focus(FocusState.Programmatic); // Set focus on beam length TextBox. } /// <summary> /// Clean up all Win2D items when leaving page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_Unloaded(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. if (W2DPrint.printTitle != null) // Clear the text in the print dialog title bar. W2DPrint.printTitle = null; if (W2DPrint.printDocument != null) { W2DPrint.printDocument.Dispose(); // Get rid of printDocument to complete print garbage collection. W2DPrint.printDocument = null; } canvas.RemoveFromVisualTree(); // Explicitly remove all canvas references to allow Win2D to complete garbage collection. canvas = null; } } }
using Atc.Resources; // ReSharper disable InconsistentNaming // ReSharper disable once CheckNamespace namespace Atc { /// <summary> /// Enumeration: LogCategoryType categories available for logging. /// </summary> public enum LogCategoryType { /// <summary> /// Critical. /// </summary> [LocalizedDescription("LogCategoryTypeCritical", typeof(EnumResources))] Critical, /// <summary> /// Error. /// </summary> [LocalizedDescription("LogCategoryTypeError", typeof(EnumResources))] Error, /// <summary> /// Warning. /// </summary> [LocalizedDescription("LogCategoryTypeWarning", typeof(EnumResources))] Warning, /// <summary> /// Security. /// </summary> [LocalizedDescription("LogCategoryTypeSecurity", typeof(EnumResources))] Security, /// <summary> /// Audit. /// </summary> [LocalizedDescription("LogCategoryTypeAudit", typeof(EnumResources))] Audit, /// <summary> /// Service. /// </summary> [LocalizedDescription("LogCategoryTypeService", typeof(EnumResources))] Service, /// <summary> /// UI. /// </summary> [LocalizedDescription("LogCategoryTypeUI", typeof(EnumResources))] UI, /// <summary> /// Information. /// </summary> [LocalizedDescription("LogCategoryTypeInformation", typeof(EnumResources))] Information, /// <summary> /// Debug. /// </summary> [LocalizedDescription("LogCategoryTypeDebug", typeof(EnumResources))] Debug, /// <summary> /// Trace. /// </summary> [LocalizedDescription("LogCategoryTypeTrace", typeof(EnumResources))] Trace, } }