text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Navigation.Mvc.Models { /// <summary> /// Classes that implement this interface could be used as model for the Navigation widget. /// </summary> public interface INavigationModel { /// <summary> /// Gets or sets the list of site map nodes that will be displayed in the navigation widget. /// </summary> /// <value> /// The nodes. /// </value> [Browsable(false)] IList<NodeViewModel> Nodes { get; } /// <summary> /// Gets or sets the CSS class that will be applied on the wrapper div of the NavigationWidget (if such is presented). /// </summary> /// <value> /// The CSS class. /// </value> string CssClass { set; get; } /// <summary> /// Gets the current site map node. /// </summary> /// <value> /// The current site map node. /// </value> [Browsable(false)] SiteMapNode CurrentSiteMapNode { get; } /// <summary> /// Gets or sets whether to show parent page /// </summary> bool ShowParentPage { get; set; } /// <summary> /// Gets or sets the levels to include. /// </summary> int? LevelsToInclude { get; set; } /// <summary> /// Gets or sets the page links to display selection mode. /// </summary> /// <value>The page display mode.</value> PageSelectionMode SelectionMode { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimilarPair { public class Node { public int value { get; set; } public Node Parent { get; set; } public Node Child { get; set; } } public class Graph<T> where T : Node, new() { //public List<List<Node>> _adjMatrix { get; set; } public List<List<T>> _adjMatrix { get; set; } public Graph() { } public Graph(int totalVertices) { //_adjMatrix = new List<List<Node>>(totalVertices); _adjMatrix = new List<List<T>>(totalVertices); for (int i = 0; i < totalVertices; ++i) { _adjMatrix.Add(new List<T>()); //new int[totalVertices])); //_adjMatrix.Add(new List<Node>()); //new Node[totalVertices])); } } public Graph(int totalVertices, int totalEdges) { //_adjMatrix = new List<List<Node>>(totalVertices); _adjMatrix = new List<List<T>>(totalVertices); for (int i = 0; i < totalVertices; ++i) { _adjMatrix.Add(new List<T>()); //new int[totalVertices])); //_adjMatrix.Add(new List<Node>(new Node[totalVertices])); } } //public void AddEdge(int from, int to) public void AddEdge(int from, int to) //where T : Node { /* _adjMatrix[from].Add(to); _adjMatrix[to].Add(from); */ T fromNode = new T() { value = from }; T toNode = new T() { value = to }; fromNode.Child = toNode; toNode.Parent = fromNode; _adjMatrix[from].Add(toNode); _adjMatrix[to].Add(fromNode); } } public class GraphUtility { public List<bool> visited { get; set; } public uint totalSpecialPairs { get; set; } public int currentParentValue { get; set; } public int specialKCondition { get; set; } public bool MeetPairCondition(Node b) { //if (b.value == currentParentValue) // return false; bool condition = Math.Abs(currentParentValue - b.value) <= specialKCondition; if (condition == true && b.Parent != null && b.Parent.value == currentParentValue) return true; return false; } public GraphUtility() { visited = new List<bool>(); } public GraphUtility(int totalVertices) { visited = new List<bool>(totalVertices); for(int i = 0; i < totalVertices; ++i) { visited.Add(false); } } public void DFS(Node node, Graph<Node> _g) { visited[node.value] = true; //Console.WriteLine(node.value + 1); if(MeetPairCondition(node)) { ++totalSpecialPairs; Console.WriteLine($"Special pair: {currentParentValue} , {node.value}"); } foreach(Node n in _g._adjMatrix[node.value]) { if(!visited[n.value]) { DFS(n, _g); } } Console.WriteLine("-----------------------"); } } public class SimilarPair { /* Main program. About: The goal of this program is to find the number of similar pairs (a,b) satisfying the following conditions: 1. Node a is the ancestor of node b 2. abs(a - b) <= k, where k is an arbitrary qualifier The goal is to determine the amount of similar pairs in the tree. */ public void Run() { // Get two space separated integers representing # of nodes (n) & similar pair qualifier (k) string[] input = Console.ReadLine().Split(' '); int n = Int32.Parse(input[0]); int k = Int32.Parse(input[1]); Graph<Node> graph = new Graph<Node>(n); //List<Node> parentNodes = new List<Node>(); List<int> parentNodes = new List<int>(); // Collect the edges to form the graph // Note: The first node in the line is said to be the parent of the second node. Each node <= n. for(int i = 0; i < n - 1; ++i) { input = Console.ReadLine().Split(' '); int parent = Int32.Parse(input[0]) - 1; int child = Int32.Parse(input[1]) - 1; parentNodes.Add(parent); graph.AddEdge(parent, child); } GraphUtility gutility = new GraphUtility(n); //gutility.DFS(new Node() { value = 0 }, graph); foreach(int parentNode in parentNodes) { Console.WriteLine($"For parent node {parentNode}:"); gutility.currentParentValue = parentNode; gutility.specialKCondition = k; gutility.DFS(new Node() { value = parentNode }, graph); gutility.visited = new List<bool>(new bool[n]); gutility.visited.ForEach(x => x = false); } Console.WriteLine(gutility.totalSpecialPairs); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NADD { class Questoes : FabricaQuestoes { private double _valor; private string _tipo; private string _observacao; public Questoes(double valor, string tipo, string observacao) { Valor = valor; Tipo = tipo; Observacao = observacao; } public double Valor { get => _valor; set => _valor = value; } public string Tipo { get => _tipo; set => _tipo = value; } public string Observacao { get => _observacao; set => _observacao = value; } public override IQuestao criarQuestao() { if (Tipo.Equals("Objetiva")) { return new Objetiva(Valor, Tipo, Observacao); } else { return new Discursiva(Valor, Tipo, Observacao); } } } }
namespace _01.ChatA { using IronMQ; using IronMQ.Data; using System; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; public class Startup { private static string GetLocalIPAddress() { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } throw new Exception("Local IP Address Not Found!"); } private static async Task<string> GetInputAsync() { return await Task.Run(() => Console.ReadLine()); } private static async void SendMsg(Queue queue) { Task<string> getInput = GetInputAsync(); // independent work which doesn't need the result of LongRunningOperationAsync can be done here //and now we call await on the task string msg = await getInput; //use the result queue.Push(GetLocalIPAddress() + ": " + msg); } public static void Main() { Client client = new Client("5649aff573d0cd00060000be", "CxkKy2oQPPvMfD9kQvW9"); Queue receiveQueue = client.Queue("A"); Queue sendQueue = client.Queue("B"); Console.WriteLine("Listening for new messages from IronMQ server:"); while (true) { Message msgReceive = receiveQueue.Get(); if (msgReceive != null) { Console.WriteLine(msgReceive.Body); receiveQueue.DeleteMessage(msgReceive); } SendMsg(sendQueue); } } } }
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace PluralsightDemo { public class PluralsightUserDbContext : IdentityDbContext<PluralsightUser> { // public DbSet<pendingstudent> UserLogt { get; set; } public PluralsightUserDbContext(DbContextOptions<PluralsightUserDbContext> options) : base(options) { } //public DbSet<pendingobject> PendingTable { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); //builder.Entity<Notitie>() // .WithMany(a => a.Notifications) // .HasForeignKey(n => n.ApplicationUserId) // .WillCascadeOnDelete(false); builder.Entity<PluralsightUser>() .HasMany(x => x.Notities) .WithOne(y => y.User).HasForeignKey(x=>x.UserId) .IsRequired(); //builder.Entity<Notitie>(notitie => //{ // notitie.ToTable("Notities"); // notitie.HasKey(x => x.Id); // notitie.HasOne<PluralsightUser>().WithMany().HasPrincipalKey(x => x.NotititieId).IsRequired(false); //}); //builder.Entity<pendingobject>(pending => { // pending.ToTable("Pendingobjects"); // pending.HasKey(x=>x.ID); //}); //builder.Entity<pendingobject>(user => user.HasIndex(x => x.anothervairalbe).IsUnique(false)); //builder.Entity<pendingobject>(user => user.HasIndex(x => x.weerietsanders).IsUnique(false)); //builder.Entity<PluralsightUser>(user => user.HasIndex(x => x.Locale).IsUnique(false)); //builder.Entity<Organization>(org => //{ // org.ToTable("Organizations"); // org.HasKey(x => x.Id); // org.HasMany<PluralsightUser>().WithOne().HasForeignKey(x => x.OrgId).IsRequired(false); //}); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Negozio.DataAccess.DbModel { public class Film { [Key] public int FilmId { get; set; } public string Titolo { get; set; } public int NegoziooId { get; set; } public DateTime Anno { get; set; } public decimal Prezzo { get; set; } public virtual Negozioo Negozioo { get; set; } public virtual List<FilmRegista> FilmRegistas { get; set; } public virtual List<FilmAttore> FilmAttores { get; set; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Specialized; namespace Unicorn { public class ScriptMoth : UniBehaviour { // Used player components RigidBody enemyRB; Variables enemyVar; Navigator enemyNavigator; //<- Get Navigator // Transform myPosition; // Other entity's components public int player_ID; ScriptPlayer script_Player; // Player Stats, default values public static float enemyForce = 100000.0f; // Move force while human public static float maxEnemySpd = 500.0f; // spawn point public static Vector3 spawnPoint; // Move dir for camera to player Vector3 moveDir = new Vector3(0.0f, 0.0f, 0.0f); //For init public bool startPatroling = false; public bool startIdling = false; public bool startPaused = false; //For update public bool isPatroling = true; public bool isIdling = false; public bool isPaused = false; public bool dectectsPlayer = false; //Boolean to react to player later on //Vector3 inVec; // accumulated dt private float accumulatedDt = 0.0f; bool invalidPath; //for Behaviour float pathSwitchTimer; float decisionTimer; bool thinking; bool possessed; public bool activate; public override void Init() { enemyRB = GetRigidBody(id); enemyNavigator = GetNavigator(id); enemyVar = GetVariables(id); //myPosition = GetTransform(id); player_ID = GameObjectFind("Player"); // Get default values from variables maxEnemySpd = enemyVar.GetFloat(0); //enemyNavigator.NavState = 0; thinking = true; } public override void LateInit() { script_Player = GetScript(player_ID); } public override void Update() { Decision(); Move(); Control(); if (activate == true) { //Set Player State to possessionstate SwitchOnFunction(); if (script_Player.CurrentState == ScriptPlayer.State.Human) { SwitchOffFunction(); activate = false; } } if (enemyNavigator.NavState == 0) { pathSwitchTimer += RealDT(); if(pathSwitchTimer > 0.5f) { enemyNavigator.NavState = 1; pathSwitchTimer = 0; if(thinking== false) { thinking = true; } } } //// -------Dismount logic //if (possessed == true) //{ // if(script_Player.CurrentState == ScriptPlayer.State.Moth) //} } public void ActivateWP(int ID) { enemyNavigator.SetWpActive(ID, true); Print("Start"); } public void DeactivateWP(int ID) { enemyNavigator.SetWpActive(ID, false); Print("off"); } public override void FixedUpdate() { } public override void OnCollisionEnter(int other) { } public override void OnTriggerEnter(int other) { //Transform tag // tag 1 = Possessable // //Transform otherTransform = GetTransform(other); if (GetTransform(other).tag == 200) { if (script_Player.CurrentState == ScriptPlayer.State.Moth/* && other == player_ID && activate == false*/) { // Set player script nextspawn position == possessionSpawnPos //script_Player.NextState = ScriptPlayer.State.Possessed; // Set Camera script position == possessionSpawnPos // script_Player.camScript.tgtID = id; // Go and expose other tgt in scriptcamera. //Audio.PlayOnce("13"); activate = true; ScriptPlayer.flying = false; enemyNavigator.isPaused = false; // possessed = true; } } } public override void Exit() { } //If need a ai state like behaviour, just rough idea only public void Decision() { //======Init phase====// //Print("Thinking"); //---- Moth Logic----// if (thinking == true && invalidPath ==false ) { decisionTimer += RealDT(); if (decisionTimer > 4.0f) { if (enemyNavigator.MoreThenOneWPActive()) { enemyNavigator.NavState = 0; decisionTimer = 0; Print("target"); thinking = false; } else { Print("No target"); decisionTimer = 0; Decision(); } } } //else if (thinking == true && invalidPath == true) //{ // thinking = false; //} // Wait for 1s // Check if there is another waypoint active // if yes () // change to mode & back if (startIdling) { } if (startPaused) { } if (startPatroling) { } } // Enemy functions public void Move() { //Console.WriteLine("bla"); //======================// //====Update phase=====// //Console.WriteLine(enemyNavigator.isPaused); if (isIdling || isPaused) //Stop movement if idle/pause return; if (isPatroling) { //Any unique movement behaviour can be stated here } //=================// } public void Control() { //Key for debug //Pause and unpause movement if (Input.GetKeyPress(VK.IKEY_M)) { enemyNavigator.isPaused = !enemyNavigator.isPaused; /* if (isPatroling) startPaused = true; else startPatroling = true; */ } // 0 -> Patrol // 1 -> Circling at cur_wp if (Input.GetKeyPress(VK.IKEY_Y)) { enemyNavigator.NavState = 0; } if (Input.GetKeyPress(VK.IKEY_U)) { enemyNavigator.NavState = 1; } //Set active to specify wp if (Input.GetKeyPress(VK.IKEY_J)) { enemyNavigator.SetWpActive(1, false); } //Speed up if (Input.GetKeyPress(VK.IKEY_K)) { if (enemyNavigator.speed < maxEnemySpd) { Console.WriteLine("Increasing...."); enemyNavigator.speed += 0.5f; } } //Slow down if (Input.GetKeyPress(VK.IKEY_L)) { if (enemyNavigator.speed > 1.0f) enemyNavigator.speed -= 0.5f; } } public void SwitchOnFunction() { GetTransform(player_ID).SetPosition(GetTransform(id).GetPosition()); } public void SwitchOffFunction() { } public void PauseAI() { enemyNavigator.isPaused = true; } } }
using System; namespace ClassTesting { public class Dog : Pet { public Dog() : base() { } public Dog(string name, int age) : base(name,age) { } public override void Speak() { Console.WriteLine(string.Format("My name is {0} and I am {1} years old..WOOF WOOF", this.Name, this.Age)); } } }
using UnityEngine; using System.Collections; public class Cell : MonoBehaviour { string _position; int _cost; public string Position { get { return _position; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace EBV { public partial class RegisterCompany : System.Web.UI.Page { BLL.BLL objbll = new BLL.BLL(); protected void Page_Load(object sender, EventArgs e) { } protected void Register_Click(object sender, EventArgs e) { if (objbll.checkRegister(txtComapny.Text)) { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Request Already Received.Wait For Confirmation Mail')", true); } else if (objbll.insertRegister(txtComapny.Text, txtMail.Text, txtPhone.Text)) { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Admin Notified.Wait For Confirmation Mail')", true); } else { ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "alert", "alert('Company Name not yet added.Contact Admin')", true); } txtPhone.Text = ""; txtMail.Text = ""; txtComapny.Text = ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Prism.Commands; using Prism.Navigation; using Prism.Logging; using Prism.Services; namespace fictionalbroccoli.ViewModels { public class BrocoBonusViewModel : ViewModelBase { public BrocoBonusViewModel(INavigationService navigationService) : base(navigationService) { Title = "List des Bonus"; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pizza_FinalProject.Domain { public class Pizza { public int Id { get; set; } [EnumDataType(typeof(PizzaNameEnum))] public PizzaNameEnum PizzaName { get; set; } public enum PizzaNameEnum { Cheese = 1, All_Dressed = 2, Hawaiian = 3, Salami = 4, Vegetarian = 5 } [NotMapped] public byte[] Photo { get; set; } public double price { get; set; } public PizzaSizeEnum Size { get; set; } public enum PizzaSizeEnum { Small = 1, Medium = 2, Large = 3 } // Item and Pizza: one-to-many. One pizza can exist in more than one Item table (for different orders) public ICollection<Item> ItemsContainPizza { get; set; } public void InsertPizzaTable() { Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Cheese, Size = PizzaSizeEnum.Small, price = 9.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Cheese, Size = PizzaSizeEnum.Medium, price = 11.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Cheese, Size = PizzaSizeEnum.Large, price = 13.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.All_Dressed, Size = PizzaSizeEnum.Small, price = 9.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.All_Dressed, Size = PizzaSizeEnum.Medium, price = 11.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.All_Dressed, Size = PizzaSizeEnum.Large, price = 13.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Hawaiian, Size = PizzaSizeEnum.Small, price = 9.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Hawaiian, Size = PizzaSizeEnum.Medium, price = 11.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Hawaiian, Size = PizzaSizeEnum.Large, price = 13.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Salami, Size = PizzaSizeEnum.Small, price = 9.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Salami, Size = PizzaSizeEnum.Medium, price = 11.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Salami, Size = PizzaSizeEnum.Large, price = 13.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Vegetarian, Size = PizzaSizeEnum.Small, price = 9.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Vegetarian, Size = PizzaSizeEnum.Medium, price = 11.00 }); Global.ctx.Pizzas.Add(new Pizza() { PizzaName = PizzaNameEnum.Vegetarian, Size = PizzaSizeEnum.Large, price = 13.00 }); Global.ctx.SaveChanges(); } } }
using UnityEngine; using TMPro; public class LobbyMainMenu : MonoBehaviour { public TMP_InputField ipInput; public GameEvent OnJoinGame; public GameEvent OnHostGame; public StringVariable IpAdress; public void OnEnable() { ipInput.onEndEdit.RemoveAllListeners(); ipInput.onEndEdit.AddListener(onEndEditIP); } public void OnClickHost() { OnHostGame.Raise(); } public void OnClickJoin() { OnJoinGame.Raise(); } public void OnQuit() { Application.Quit(); } void onEndEditIP(string text) { IpAdress.Value = text; if (Input.GetKeyDown(KeyCode.Return)) { OnClickJoin(); } } }
using System; using System.Collections.Generic; using System.Text; namespace DilemaPrisionero { class Aleatorio : IEstrategia { public int DevuelveAccion() { Random rm = new Random(); return rm.Next(0, 2); } } }
using CMS.Core.Interfaces; using System; using System.ComponentModel.DataAnnotations; namespace CMS.Core.Model { public class UserLog : IEntity { public int Id { get; set; } [Required] public string UserId { get; set; } public string IP { get; set; } public string UserAgent { get; set; } public DateTime Date { get; set; } [Required] public string Operation { get; set; } public User User { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace CarParkingSystem.Models { public class CheckOut { [Key] public int Id { get; set; } public int CheckInId { get; set; } public virtual CheckIn CheckIn { get; set; } public DateTime CheckOutTime { get; set; } public string UserCode { get; set; } public int CarId { get; set; } public virtual Car Car { get; set; } public virtual ICollection<Bill> Bills { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Application.Common.Dtos; using Application.Common.Exceptions; using Application.Common.Interface; using Application.Common.Models; using AutoMapper; using AutoMapper.QueryableExtensions; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Application.Discounts.Queries { public class GetDiscountDetailQueryByName : IRequest<List<DiscountDto>> { public string Name { get; set; } } public class GetDiscountDetailQueryByNameHandler : BaseCommandHandler<GetDiscountDetailQueryByNameHandler>, IRequestHandler<GetDiscountDetailQueryByName, List<DiscountDto>> { public GetDiscountDetailQueryByNameHandler (IAppDbContext context, IMapper mapper, ILogger<GetDiscountDetailQueryByNameHandler> logger) : base (context, mapper, logger) { } public async Task<List<DiscountDto>> Handle (GetDiscountDetailQueryByName request, CancellationToken cancellationToken) { var entity = await Context.Discounts.Where (x => x.DiscountName.Contains (request.Name)).ProjectTo<DiscountDto> (Mapper.ConfigurationProvider).ToListAsync (cancellationToken); if (entity == null) throw new NotFoundException ("Discount", "Discount not found"); return entity; } } }
namespace TiendeoAPI.Helpers.enums { public enum ServiceTypes { Info, WC, ATM, Delivery } }
// ----------------------------------------------------------------------- // <copyright file="Native.Linux.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root // for license information. // </copyright> // ----------------------------------------------------------------------- using System; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; namespace Mlos.Core.Linux { /// <summary> /// Linux PInvoke functions. /// </summary> internal static unsafe class Native { private const string RtLib = "rt"; private const string SystemNative = "System.Native"; /// <summary> /// Represents invalid pointer (void *) -1. /// </summary> internal static IntPtr InvalidPointer = IntPtr.Subtract(IntPtr.Zero, 1); #pragma warning disable CA2101 // Specify marshaling for P/Invoke string arguments (CharSet.Ansi is considered unsafe). /// <summary> /// Receives a message on a socket. /// </summary> /// <returns>Returns number of bytes read.</returns> /// <param name="socketFd"></param> /// <param name="msg"></param> /// <param name="flags"></param> [DllImport(RtLib, EntryPoint = "recvmsg", SetLastError = true)] internal static extern ulong ReceiveMessage(IntPtr socketFd, ref MessageHeader msg, MsgFlags flags); /// <summary> /// Sends a message on a socket. /// </summary> /// <returns>Returns number of bytes written.</returns> /// <param name="socketFd"></param> /// <param name="msg"></param> /// <param name="flags"></param> [DllImport(RtLib, EntryPoint = "sendmsg", SetLastError = true)] internal static extern ulong SendMessage(IntPtr socketFd, ref MessageHeader msg, MsgFlags flags); /// <summary> /// Creates a new POSIX semaphore or opens an existing semaphore. The semaphore is identified by name. /// </summary> /// <param name="name"></param> /// <param name="openFlags"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "sem_open", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern SemaphoreSafeHandle SemaphoreOpen(string name, OpenFlags openFlags); /// <summary> /// Creates a new POSIX semaphore or opens an existing semaphore. The semaphore is identified by name. /// </summary> /// <param name="name"></param> /// <param name="openFlags"></param> /// <param name="mode"></param> /// <param name="value"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "sem_open", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern SemaphoreSafeHandle SemaphoreOpen(string name, OpenFlags openFlags, ModeFlags mode, int value); /// <summary> /// Increments (unlocks) the semaphore pointed to by sem. If the semaphore's value consequently becomes greater than zero, /// then another process or thread blocked in a sem_wait(3) call will be woken up and proceed to lock the semaphore. /// </summary> /// <param name="handle"></param> /// <returns> /// Returns 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error. /// </returns> [DllImport(RtLib, EntryPoint = "sem_post", SetLastError = true)] internal static extern int SemaphorePost(SemaphoreSafeHandle handle); /// <summary> /// Decrements (locks) the semaphore pointed to by sem. If the semaphore's value is greater than zero, then the decrement /// proceeds, and the function returns, immediately. If the semaphore currently has the value zero, then the call blocks until either it /// becomes possible to perform the decrement (i.e., the semaphore value rises above zero), or a signal handler interrupts the call. /// </summary> /// <param name="handle"></param> /// <returns>Return 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned.</returns> [DllImport(RtLib, EntryPoint = "sem_wait", SetLastError = true)] internal static extern int SemaphoreWait(SemaphoreSafeHandle handle); [DllImport(RtLib, EntryPoint = "sem_close", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern int SemaphoreClose(IntPtr handle); /// <summary> /// Removes the named semaphore referred to by name. The semaphore name is removed immediately. /// The semaphore is destroyed once all other processes that have the semaphore open close it. /// </summary> /// <param name="name"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "sem_unlink", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern int SemaphoreUnlink(string name); /// <summary> /// Creates and opens a new, or opens an existing, POSIX shared memory object. /// </summary> /// <param name="name"></param> /// <param name="openFlags"></param> /// <param name="mode"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "shm_open", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern SharedMemorySafeHandle SharedMemoryOpen(string name, OpenFlags openFlags, ModeFlags mode); [DllImport(RtLib, EntryPoint = "shm_unlink", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern int SharedMemoryUnlink(string name); [DllImport(RtLib, EntryPoint = "unlink", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern int FileSystemUnlink(string name); /// <summary> /// Gets a file status. /// </summary> /// <param name="fd"></param> /// <param name="output"></param> /// <returns>Returns zero on success.</returns> [DllImport(SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)] internal static extern int FileStats(IntPtr fd, out FileStatus output); /// <summary> /// Map files or devices into the memory. /// </summary> /// <param name="address"></param> /// <param name="length"></param> /// <param name="protFlags"></param> /// <param name="mapFlags"></param> /// <param name="handle"></param> /// <param name="offset"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "mmap", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern IntPtr MapMemory(IntPtr address, ulong length, ProtFlags protFlags, MapFlags mapFlags, SharedMemorySafeHandle handle, long offset); /// <summary> /// Truncates a file to a specified length. /// </summary> /// <param name="handle"></param> /// <param name="length"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "ftruncate", SetLastError = true)] internal static extern int FileTruncate(SharedMemorySafeHandle handle, long length); /// <summary> /// Closes a file descriptor. /// </summary> /// <param name="handle"></param> /// <returns></returns> [DllImport(RtLib, EntryPoint = "close", CharSet = CharSet.Ansi, SetLastError = true)] internal static extern int Close(IntPtr handle); [DllImport(RtLib, EntryPoint ="perror", CharSet = CharSet.Ansi)] internal static extern void PrintError(string name); #pragma warning restore CA2101 // Specify marshaling for P/Invoke string arguments [Flags] internal enum OpenFlags : int { O_RDONLY = 0, O_WRONLY = 1, O_RDWR = 2, /// <summary> /// If pathname does not exist, create it as a regular file. /// </summary> O_CREAT = 0x40, /// <summary> /// Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, /// and pathname already exists, then open() fails with the error EEXIST. /// </summary> O_EXCL = 0x80, } [Flags] internal enum ModeFlags : uint { /// <summary> /// Execute by owner. /// </summary> S_IXUSR = 0x0040, /// <summary> /// Write by owner. /// </summary> S_IWUSR = 0x80, /// <summary> /// Read by owner. /// </summary> S_IRUSR = 0x0100, S_IRWXU = S_IRUSR | S_IWUSR | S_IXUSR, } /// <summary> /// Desired memory protection of memory mapping. /// </summary> [Flags] internal enum ProtFlags : int { PROT_NONE = 0x0, PROT_READ = 0x1, PROT_WRITE = 0x2, PROT_EXEC = 0x4, /// <summary> /// Extend change to start of growsdown vma (mprotect only). /// </summary> PROT_GROWSDOWN = 0x1000000, /// <summary> /// Extend change to start of growsup vma (mprotect only). /// </summary> PROT_GROWNSUP = 0x2000000, } /// <summary> /// Additional parameters for mmap. /// </summary> [Flags] internal enum MapFlags : int { /// <summary> /// Compability flag. /// </summary> MAP_FILE = 0, /// <summary> /// Share this mapping. Mutually exclusive with MAP_PRIVATE. /// </summary> MAP_SHARED = 0x1, /// <summary> /// Create a private copy-on-write mapping. Mutually exclusive with MAP_SHARED. /// </summary> MAP_PRIVATE = 0x2, /// <summary> /// Mask for type fields. /// </summary> MAP_TYPE = 0xf, /// <summary> /// Place mapping at exactly the address specified in addr. /// </summary> MAP_FIXED = 0x10, /// <summary> /// Mapping is not backed by any file. Content is initialized to zero. /// </summary> MAP_ANONYMOUS = 0x20, } [Flags] internal enum ShmIpcFlags : int { /// <summary> /// Mark the segment to be destroyed. The segment will actually be destroyed only after the last process detaches it. /// </summary> IPC_RMID = 0x0, /// <summary> /// Set the user ID of the owner, the group ID of the owner, and the permissions for the shared memory segment to the values /// in the shm_perm.uid, shm_perm.gid, and shm_perm.mode members of the shmid_ds data structure pointed to by *buf. /// </summary> IPC_SET = 0x1, } [Flags] internal enum MsgFlags : int { /// <summary> /// Process out-of-band data. /// </summary> MSG_OOB = 0x01, /// <summary> /// Peek at incoming messages. /// </summary> MSG_PEEK = 0x02, /// <summary> /// Don't use local routing. /// </summary> MSG_DONTROUTE = 0x04, /// <summary> /// Control data lost before delivery. /// </summary> MSG_CTRUNC = 0x08, /// <summary> /// Supply or ask second address. /// </summary> MSG_PROXY = 0x10, MSG_TRUNC = 0x20, } } /// <summary> /// Semaphore handle. /// </summary> [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] internal class SemaphoreSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public SemaphoreSafeHandle() : base(true) { } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { return Native.SemaphoreClose(handle) == 0; } } /// <summary> /// Shared memory handle. /// </summary> [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] internal class SharedMemorySafeHandle : SafeHandleZeroOrMinusOneIsInvalid { /// <summary> /// Invalid handle. /// </summary> internal static readonly SharedMemorySafeHandle Invalid = new SharedMemorySafeHandle(); internal SharedMemorySafeHandle() : base(true) { } internal SharedMemorySafeHandle(IntPtr fileDescriptor) : base(true) { SetHandle(fileDescriptor); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { return Native.Close(handle) == 0; } } /// <summary> /// File stats structure. /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct FileStatus { internal int Flags; internal int Mode; internal uint Uid; internal uint Gid; internal long Size; internal long ATime; internal long ATimeNsec; internal long MTime; internal long MTimeNsec; internal long CTime; internal long CTimeNsec; internal long BirthTime; internal long BirthTimeNsec; internal long Dev; internal long Ino; internal uint UserFlags; } /// <summary> /// Definition of structure iovec. /// This must match the definitions in struct_iovec.h. /// </summary> [StructLayout(LayoutKind.Sequential, Pack=8)] internal struct IoVec { /// <summary> /// Pointer to data. /// </summary> internal IntPtr IovBase; /// <summary> /// Length of data. /// </summary> internal ulong IovLength; } [StructLayout(LayoutKind.Sequential, Pack=8)] internal struct MessageHeader { /// <summary> /// Address to send to/receive from. /// </summary> internal IntPtr MessageName; /// <summary> /// Length of address data. /// </summary> internal uint MessageNameLength; /// <summary> /// Vector of data to send/receive into. /// </summary> internal unsafe IoVec* MessageIoVec; /// <summary> /// Number of elements in the vector. /// </summary> public ulong MessageIoVecLength; /// <summary> /// Ancillary data (eg BSD file descriptor passing). /// </summary> internal unsafe ControlMessageHeader* MessageControl; /// <summary> /// Ancillary data buffer length. /// </summary> internal ulong MessageControlLength; /// <summary> /// Flags on received message. /// </summary> internal int MessageFlags; } /// <summary> /// Socket level message types. /// This must match the definitions in linux/socket.h. /// </summary> internal enum SocketLevelMessageType : int { /// <summary> /// Transfer file descriptors. /// </summary> ScmRights = 0x01, /// <summary> /// Credentials passing. /// </summary> ScmCredentials = 0x02, } /// <summary> /// Structure used for storage of ancillary data object information. /// </summary> /// <remarks> /// Struct cmsghdr. /// </remarks> [StructLayout(LayoutKind.Sequential, Pack=8)] internal struct ControlMessageHeader { /// <summary> /// Length of data in cmsg_data plus length of cmsghdr structure. /// </summary> internal ulong ControlMessageLength; /// <summary> /// Originating protocol. /// </summary> internal int ControlMessageLevel; /// <summary> /// Protocol specific type. /// </summary> internal SocketLevelMessageType ControlMessageType; } /// <summary> /// Structure used for storage of ancillary data object information of type {T}. /// </summary> /// <typeparam name="T">Type of stored object.</typeparam> [StructLayout(LayoutKind.Sequential, Pack=1)] internal struct ControlMessage<T> where T : struct { /// <summary> /// Cmsghdr struct. /// </summary> internal ControlMessageHeader Header; /// <summary> /// Value included in the message. /// </summary> internal T Value; } }
using System; [AttributeUsage(AttributeTargets.Field)] public class PlayerActionAttribute : Attribute { // If the action can be removed over time public bool AlwaysTracked { get; private set; } // an action that will be cancelled when the action is taken (eg. place action cancels pickup as the player is not currently holding) public PlayerAction CancelAction { get; private set; } public PlayerActionAttribute(bool alwaysTracked, PlayerAction cancelAction) { AlwaysTracked = alwaysTracked; CancelAction = cancelAction; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.Net; using InvoiceClient.Properties; using Utility; using Model.Schema.TXN; using InvoiceClient.Helper; using InvoiceClient.TransferManagement; using System.Diagnostics; using System.Threading.Tasks; namespace InvoiceClient.Agent { public class InvoicePDFInspector : ServerInspector { protected DateTime _dateCounter; protected Task[] _tasks; protected String _prefix_name = "taiwan_uxb2b_scanned_gui_pdf_"; public InvoicePDFInspector() { initializeCounter(); if(Settings.Default.ProcessCount>0) { _tasks = new Task[Settings.Default.ProcessCount]; } } private void initializeCounter() { _dateCounter = DateTime.Now; } public virtual String GetSaleInvoices(int? index = null) { WS_Invoice.eInvoiceService invSvc = InvoiceWatcher.CreateInvoiceService(); try { Root token = this.CreateMessageToken("下載電子發票PDF"); if (index >= 0 && Settings.Default.ProcessCount > 0) { token.Request.processIndexSpecified = token.Request.totalProcessCountSpecified = true; token.Request.processIndex = index.Value + Settings.Default.ProcessArrayIndex; token.Request.totalProcessCount = Math.Max(Settings.Default.ProcessArrayCount, Settings.Default.ProcessCount); Logger.Info($"retrieve PDF by ProcIdx:{token.Request.processIndex}/{token.Request.totalProcessCount}"); } String storedPath = Settings.Default.DownloadDataInAbsolutePath ? Settings.Default.DownloadSaleInvoiceFolder : Path.Combine(Settings.Default.InvoiceTxnPath, Settings.Default.DownloadSaleInvoiceFolder); ValueValidity.CheckAndCreatePath(storedPath); //storedPath = ValueValidity.GetDateStylePath(storedPath); String tmpPath = Path.Combine(Logger.LogDailyPath, $"{(index ?? 0):0000}"); bool hasNew = false; XmlDocument signedReq = token.ConvertToXml().Sign(); string[] items = invSvc.ReceiveContentAsPDF(signedReq, Settings.Default.ClientID); if (items != null && items.Length > 1) { hasNew = true; Directory.CreateDirectory(tmpPath); String serviceUrl = items[0]; void proc(int i) { var item = items[i]; String[] paramValue = item.Split('\t'); String invNo = paramValue[0]; String pdfFile = Path.Combine(tmpPath, _prefix_name + paramValue[1] + "_" + invNo + ".pdf"); //String pdfFile = Path.Combine(storedPath, string.Format("{0}{1}.pdf", "taiwan_uxb2b_scanned_gui_pdf_", invNo)); //token = this.CreateMessageToken("已下載電子發票PDF:" + invNo);// //signedReq = token.ConvertToXml().Sign(); var url = $"{serviceUrl}?keyID={paramValue[2]}"; Logger.Info($"retrieve PDF:{item}"); //var content = signedReq.UploadData(url, 43200000); fetchPDF(pdfFile, url); } //if (Settings.Default.ProcessCount > 1) //{ // int start = 1; // while (start < items.Length) // { // int end = Math.Min(start + Settings.Default.ProcessCount, items.Length); // Parallel.For(start, end, (idx) => // { // proc(idx); // }); // start = end; // } //} //else //{ // for (int i = 1; i < items.Length; i++) // { // proc(i); // } //} Parallel.For(1, items.Length, (idx) => { proc(idx); }); } if (hasNew) { String args = String.Format("{0}{1:yyyyMMddHHmmssffff}{4:0000} \"{2}\" \"{3}\"", _prefix_name, DateTime.Now, tmpPath, storedPath, index ?? 0); //if (index.HasValue) //{ // ZipPDFFactory.Notify(args); //} //else { Logger.Info($"zip PDF:{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZipPDF.bat")} {args}"); Process proc = Process.Start(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZipPDF.bat"), args); } } return hasNew ? storedPath : null; } catch (Exception ex) { Logger.Error(ex); } return null; } protected virtual void fetchPDF(string pdfFile, string url) { using (WebClientEx client = new WebClientEx { Timeout = 43200000 }) { client.DownloadFile(url, pdfFile); Logger.Info($"finish PDF:{url}"); url = $"{url}&ackDel={true}"; client.DownloadString(url); } } public override void StartUp() { if (Settings.Default.IsAutoInvService && !_isRunning) { ThreadPool.QueueUserWorkItem(p => { while (Settings.Default.IsAutoInvService) { _isRunning = true; ServerInspector.AcknowledgeServer(); String result = null; if (_tasks != null) { do { result = null; Logger.Info($"start retrieving PDF:{DateTime.Now}"); for (int i = 0; i < Settings.Default.ProcessCount; i++) { int index = i; _tasks[i] = new Task(() => { result = GetSaleInvoices(index); }) { }; _tasks[i].Start(); } var t = Task.Factory.ContinueWhenAll(_tasks, ts => { Logger.Info($"end retrieving PDF:{DateTime.Now}"); }); t.Wait(); } while (result != null); } else { while ((result = GetSaleInvoices()) != null) ; } Thread.Sleep(Settings.Default.AutoInvServiceInterval > 0 ? Settings.Default.AutoInvServiceInterval * 60 * 1000 : 1800000); } _isRunning = false; }); } } public override Type UIConfigType { get { return typeof(InvoiceClient.MainContent.GoogleInvoiceServerConfig); } } public override void ExecutiveService(List<string> pathInfo) { if (!Settings.Default.IsAutoInvService) { String path; while ((path = this.GetSaleInvoices()) != null) { pathInfo.Add(path); } } base.ExecutiveService(pathInfo); } } }
using AzureFunctions.Extensions.Swashbuckle.Attribute; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using SkillsGardenApi.Filters; using SkillsGardenApi.Models; using SkillsGardenApi.Services; using SkillsGardenApi.Utils; using SkillsGardenDTO; using SkillsGardenDTO.Error; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; namespace SkillsGardenApi.Controllers { public class LocationController { private LocationService locationService; public LocationController(LocationService locationService) { this.locationService = locationService; } [FunctionName("LocationGetAll")] [ProducesResponseType(typeof(List<Location>), StatusCodes.Status200OK)] public async Task<IActionResult> LocationGetAll( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "locations")] HttpRequest req) { // get the locations List<Location> locations = await locationService.GetLocations(); return new OkObjectResult(locations); } [FunctionName("LocationGet")] [ProducesResponseType(typeof(Location), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task<IActionResult> LocationGet( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "locations/{locationId}")] HttpRequest req, int locationId) { // get the location Location location = await locationService.GetLocation(locationId); // check if requested location exists if (location == null) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)); return new OkObjectResult(location); } [FunctionName("LocationCreate")] [FormDataItem(Name = "Name", Description = "The name the location", Type = "string")] [FormDataItem(Name = "City", Description = "The city of the location", Type = "string")] [FormDataItem(Name = "Lat", Description = "The lat of the location", Type = "double")] [FormDataItem(Name = "Lng", Description = "The lng of the location", Type = "double")] [FormDataItem(Name = "Image", Description = "The image of the location", Format = "binary", Type = "file")] [ProducesResponseType(typeof(Location), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task<IActionResult> LocationCreate( [HttpTrigger(AuthorizationLevel.User, "post", Route = "locations")] HttpRequest req, [SwaggerIgnore] ClaimsPrincipal user) { // check if user has admin rights if (!user.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // get the form data IFormCollection formdata = await req.ReadFormAsync(); LocationBody locationBody; try { locationBody = SerializationUtil.DeserializeFormData<LocationBody>(formdata); } catch (ValidationException e) { return new BadRequestObjectResult(new ErrorResponse(400, e.Message)); } // check if all fields are filled in if (locationBody.Name == null || locationBody.City == null || locationBody.Lat == null || locationBody.Lng == null || locationBody.Image == null) return new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_REQUEST_BODY)); // create new location int locationId = await locationService.CreateLocation(locationBody); // get the created location Location createdLocation = await locationService.GetLocation(locationId); return new OkObjectResult(createdLocation); } /// <summary> /// Update location /// </summary> [FunctionName("LocationUpdate")] [FormDataItem(Name = "Name", Description = "The name the location", Type = "string")] [FormDataItem(Name = "City", Description = "The city of the location", Type = "string")] [FormDataItem(Name = "Lat", Description = "The lat of the location", Type = "double")] [FormDataItem(Name = "Lng", Description = "The lng of the location", Type = "double")] [FormDataItem(Name = "Image", Description = "The image of the location", Format = "binary", Type = "file")] [ProducesResponseType(typeof(Location), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task<IActionResult> LocationUpdate( [HttpTrigger(AuthorizationLevel.User, "put", Route = "locations/{locationId}")] HttpRequest req, int locationId, [SwaggerIgnore] ClaimsPrincipal user) { // check if user has admin rights if (!user.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // check if requested location exists if (!await locationService.Exists(locationId)) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)); // get the form data IFormCollection formdata = await req.ReadFormAsync(); LocationBody locationBody; try { locationBody = SerializationUtil.DeserializeFormData<LocationBody>(formdata); } catch (ValidationException e) { return new BadRequestObjectResult(new ErrorResponse(400, e.Message)); } // update location await locationService.UpdateLocation(locationBody, locationId); // get the updated location Location updatedLocation = await locationService.GetLocation(locationId); return new OkObjectResult(updatedLocation); } /// <summary> /// Delete location /// </summary> [FunctionName("LocationDelete")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task<IActionResult> LocationDelete( [HttpTrigger(AuthorizationLevel.User, "delete", Route = "locations/{locationId}")] HttpRequest req, int locationId, [SwaggerIgnore] ClaimsPrincipal user) { // only admin can delete location if (!user.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // delete location bool isDeleted = await locationService.DeleteLocation(locationId); // if the location was not found if (!isDeleted) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)); return new OkResult(); } } }
using System.Collections; using System.Collections.Generic; namespace VideoServiceBL.DTOs.MoviesDtos { public class MovieDto { public long Id { get; set; } public string Name { get; set; } public long GenreId { get; set; } public GenreDto Genre { get; set; } public byte NumberInStock { get; set; } public double Rate { get; set; } public long CoverId { get; set; } public CoverDto Cover { get; set; } } }
using Xamarin.Forms; namespace MCCForms { public class LabelRegularFont : Label { public LabelRegularFont () { TextColor = Color.Black; } } }
namespace MiHomeLibrary.Communication.Responses { sealed class GatewayProps { public long rgb { get; set; } public int illumination { get; set; } public string proto_version { get; set; } } }
using BusinessLaag.models; using DataLaag; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; namespace DataLaagTest { [TestClass] public class ContinentTest { [TestMethod] public void ContinentRepoTest() { UnitOfWork uow = new UnitOfWork(new DataContext()); //Leegmaken van tabellen uow.cityRepo.RemoveAll(); uow.countryRepo.RemoveAllCountries(); uow.continentRepo.RemoveAllContinents(); //Aanmaak Continent uow.continentRepo.Add(new Continent("TestCont")); Continent continent = uow.continentRepo.GetAllContinents()[0]; //Vergelijken van Continent Assert.AreEqual("TestCont", continent.Name); continent.SetName("NaamAangepastCont"); uow.continentRepo.UpdateContinent(continent); continent = uow.continentRepo.GetAllContinents()[0]; Assert.AreEqual("NaamAangepastCont", continent.Name); //Verwijderen van Continent uow.continentRepo.DeleteById(continent.ID); List<Continent> continents = uow.continentRepo.GetAllContinents(); Assert.AreEqual(0, continents.Count); //Leegmaken van tabellen uow.cityRepo.RemoveAll(); uow.countryRepo.RemoveAllCountries(); uow.continentRepo.RemoveAllContinents(); } } }
using Microsoft.EntityFrameworkCore; namespace Im.Access.GraphPortal.Data { public class IdentityDbContext : DbContext { public IdentityDbContext(DbContextOptions<IdentityDbContext> options) : base(options) { } public virtual DbSet<DbUser> Users { get; set; } public virtual DbSet<DbUserClaim> UserClaims { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<DbUser>() .ToTable("AspNetUsers", "dbo") .HasKey(e => e.Id); modelBuilder .Entity<DbUser>() .Property(e => e.Id) .HasMaxLength(128) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.TenantId) .HasMaxLength(128) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.FirstName); modelBuilder .Entity<DbUser>() .Property(e => e.LastName); modelBuilder .Entity<DbUser>() .Property(e => e.Email) .HasMaxLength(256); modelBuilder .Entity<DbUser>() .Property(e => e.EmailConfirmed) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.PasswordHash); modelBuilder .Entity<DbUser>() .Property(e => e.SecurityStamp); modelBuilder .Entity<DbUser>() .Property(e => e.PhoneNumber); modelBuilder .Entity<DbUser>() .Property(e => e.PhoneNumberConfirmed) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.TwoFactorEnabled) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.LockoutEndDateUtc); modelBuilder .Entity<DbUser>() .Property(e => e.LockoutEnabled); modelBuilder .Entity<DbUser>() .Property(e => e.AccessFailedCount) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.UserName) .HasMaxLength(256) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.RegistrationDate); modelBuilder .Entity<DbUser>() .Property(e => e.LastLoggedInDate); modelBuilder .Entity<DbUser>() .Property(e => e.RegistrationIPAddress) .HasMaxLength(50); modelBuilder .Entity<DbUser>() .Property(e => e.LastLoggedInIPAddress) .HasMaxLength(50); modelBuilder .Entity<DbUser>() .Property(e => e.ScreenName) .HasMaxLength(100) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.LastUpdatedDate) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.CreateDate) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.UserType) .HasMaxLength(50); modelBuilder .Entity<DbUser>() .Property(e => e.Address1) .HasMaxLength(255); modelBuilder .Entity<DbUser>() .Property(e => e.Address2) .HasMaxLength(255); modelBuilder .Entity<DbUser>() .Property(e => e.City) .HasMaxLength(50); modelBuilder .Entity<DbUser>() .Property(e => e.Country) .HasMaxLength(100); modelBuilder .Entity<DbUser>() .Property(e => e.Postcode) .HasMaxLength(20); modelBuilder .Entity<DbUser>() .Property(e => e.UserBiography) .HasMaxLength(4000); modelBuilder .Entity<DbUser>() .Property(e => e.FirstPartyIM) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.County) .HasMaxLength(50); modelBuilder .Entity<DbUser>() .Property(e => e.FirstPartyImUpdatedDate) .IsRequired(); modelBuilder .Entity<DbUser>() .Property(e => e.AuthenticationType) .HasMaxLength(20); modelBuilder .Entity<DbUser>() .HasMany(e => e.Claims) .WithOne() .HasForeignKey(e => e.UserId) .OnDelete(DeleteBehavior.Cascade); modelBuilder .Entity<DbUserClaim>() .ToTable("AspNetUserClaims", "dbo") .HasKey(e => e.Id) .IsClustered(); modelBuilder .Entity<DbUserClaim>() .Property(e => e.Id) .ValueGeneratedOnAdd(); modelBuilder .Entity<DbUserClaim>() .Property(e => e.UserId) .IsRequired(); modelBuilder .Entity<DbUserClaim>() .Property(e => e.ClaimType); modelBuilder .Entity<DbUserClaim>() .Property(e => e.ClaimValue); modelBuilder .Entity<DbUserClaim>() .Property(e => e.ClaimUpdatedDate) .IsRequired(); } } }
// (C) 2012 Christian Schladetsch. See http://www.schladetsch.net/flow/license.txt for Licensing information. using System; using System.Collections.Generic; namespace Flow { /// <summary> /// Creates Flow instances that reside within an Kernel. /// </summary> public interface IFactory { /// <summary> /// Gets the kernel. /// </summary> /// <value> /// The kernel. /// </value> IKernel Kernel { get; } /// <summary> /// News the timer. /// </summary> /// <returns> /// The timer. /// </returns> /// <param name='interval'> /// Interval. /// </param> ITimer NewTimer(TimeSpan interval); /// <summary> /// News the periodic timer. /// </summary> /// <returns> /// The periodic timer. /// </returns> /// <param name='interval'> /// Interval. /// </param> IPeriodic NewPeriodicTimer(TimeSpan interval); /// <summary> /// News the barrier. /// </summary> /// <returns> /// The barrier. /// </returns> IBarrier NewBarrier(); /// <summary> /// Make a new trigger. /// </summary> /// <returns> /// The trigger. /// </returns> ITrigger NewTrigger(); /// <summary> /// Make a new timed trigger. /// </summary> /// <returns> /// The timed trigger. /// </returns> /// <param name='span'> /// The trigger will be deleted after this time internal. /// </param> ITimedTrigger NewTimedTrigger(TimeSpan span); /// <summary> /// News the future. /// </summary> /// <returns> /// The future. /// </returns> /// <typeparam name='T'> /// The 1st type parameter. /// </typeparam> IFuture<T> NewFuture<T>(); /// <summary> /// Make a new timed future. /// </summary> /// <returns> /// The timed future. /// </returns> /// <param name='timeOut'> /// Time out. /// </param> /// <typeparam name='T'> /// The 1st type parameter. /// </typeparam> ITimedFuture<T> NewTimedFuture<T>(TimeSpan timeOut); /// <summary> /// News the coroutine. /// </summary> /// <returns> /// The coroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> ICoroutine<TR> NewCoroutine<TR>(Func<IGenerator, IEnumerator<TR>> fun); /// <summary> /// News the coroutine. /// </summary> /// <returns> /// The coroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <param name='t0'> /// T0. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> /// <typeparam name='T0'> /// The 2nd type parameter. /// </typeparam> ICoroutine<TR> NewCoroutine<TR, T0>(Func<IGenerator, T0, IEnumerator<TR>> fun, T0 t0); /// <summary> /// News the coroutine. /// </summary> /// <returns> /// The coroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <param name='t0'> /// T0. /// </param> /// <param name='t1'> /// T1. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> /// <typeparam name='T0'> /// The 2nd type parameter. /// </typeparam> /// <typeparam name='T1'> /// The 3rd type parameter. /// </typeparam> ICoroutine<TR> NewCoroutine<TR, T0, T1>(Func<IGenerator, T0, T1, IEnumerator<TR>> fun, T0 t0, T1 t1); ICoroutine<TR> NewCoroutine<TR, T0, T1, T2>(Func<IGenerator, T0, T1, T2, IEnumerator<TR>> fun, T0 t0, T1 t1, T2 t2); /// <summary> /// News the subroutine. /// </summary> /// <returns> /// The subroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> ISubroutine<TR> NewSubroutine<TR> (Func<IGenerator, TR> fun); /// <summary> /// News the subroutine. /// </summary> /// <returns> /// The subroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <param name='t0'> /// T0. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> /// <typeparam name='T0'> /// The 2nd type parameter. /// </typeparam> ISubroutine<TR> NewSubroutine<TR, T0> (Func<IGenerator, T0, TR> fun, T0 t0); /// <summary> /// News the subroutine. /// </summary> /// <returns> /// The subroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <param name='t0'> /// T0. /// </param> /// <param name='t1'> /// T1. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> /// <typeparam name='T0'> /// The 2nd type parameter. /// </typeparam> /// <typeparam name='T1'> /// The 3rd type parameter. /// </typeparam> ISubroutine<TR> NewSubroutine<TR, T0, T1> (Func<IGenerator, T0, T1, TR> fun, T0 t0, T1 t1); /// <summary> /// News the subroutine. /// </summary> /// <returns> /// The subroutine. /// </returns> /// <param name='fun'> /// Fun. /// </param> /// <param name='t0'> /// T0. /// </param> /// <param name='t1'> /// T1. /// </param> /// <param name='t2'> /// T2. /// </param> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> /// <typeparam name='T0'> /// The 2nd type parameter. /// </typeparam> /// <typeparam name='T1'> /// The 3rd type parameter. /// </typeparam> /// <typeparam name='T2'> /// The 4th type parameter. /// </typeparam> ISubroutine<TR> NewSubroutine<TR, T0, T1, T2> (Func<IGenerator, T0, T1, T2, TR> fun, T0 t0, T1 t1, T2 t2); /// <summary> /// News the channel. /// </summary> /// <returns> /// The channel. /// </returns> /// <param name='gen'> /// Gen. /// </param> IChannel<TR> NewChannel<TR>(ITypedGenerator<TR> gen); /// <summary> /// News the channel. /// </summary> /// <returns> /// The channel. /// </returns> /// <typeparam name='TR'> /// The 1st type parameter. /// </typeparam> IChannel<TR> NewChannel<TR>(); /// <summary> /// Prepare the specified transient for use with the kernel associated with this factory. /// <para>This can be used to prepare custom implementations of objects used by the flow library</para> /// </summary> /// <param name='obj'> /// The transient object to prepare /// </param> /// <typeparam name='T'> /// The 1st type parameter. /// </typeparam> T Prepare<T>(T obj) where T : ITransient; } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using Newtonsoft.Json; using StackExchange.Redis; using System.Net; using System.IO; using log4net; using System.Reflection; namespace OfficeService { /// <summary> /// Redis业务类 /// </summary> public class Main { /// 实例化 public static readonly Main Instance = new Main(); public static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly string url = ConfigurationManager.AppSettings["YuanXinApiUrl"]?.ToString(); protected const string redisKey = "Seagull2.YuanXin.WebApi.TaskManage"; public static readonly RedisManager Rm = new RedisManager("ClientRedisHost"); /// <summary> /// 查询Redis数据,对符合条件的数据进行过滤消息提醒 /// </summary> public void OperationRedis() { try { var arr = Rm.SetCombine(SetOperation.Union, redisKey, redisKey);//查询redis所有集合 List<RedisViewModel> list = new List<RedisViewModel>(); if (arr.Length > 0) { for (int i = 0; i < arr.Length; i++) { list.Add(JsonConvert.DeserializeObject<RedisViewModel>(arr[i])); } } if (list.Count > 0) { list.OrderByDescending(o => o.RemindTime).ToList().ForEach(m => { var state = DateCheck(DateTime.Parse(m.RemindTime)); if (state == EnumRemindTimeStatus.Valid) { return; } if (state == EnumRemindTimeStatus.Push) { //执行推送 HttpApi("API地址", JsonConvert.SerializeObject(m), "post"); //从redis删除元素 log.Info($"开始删除Redis"); Rm.SetRemove(redisKey, JsonConvert.SerializeObject(m)); log.Info($"推送成功,推送参数{m.Code}"); return; } if (state == EnumRemindTimeStatus.Expire) { //从redis删除元素 Rm.SetRemove(redisKey, JsonConvert.SerializeObject(m)); log.Info($"删除过期redis,数据{m.Code}"); return; } }); } } catch (Exception ex) { log.Error($"OfficeService服务异常," + ex.ToString()); } } /// <summary> /// 日期校验 /// </summary> /// <param name="remindTime"></param> /// <returns></returns> private EnumRemindTimeStatus DateCheck(DateTime remindTime) { if (DateTime.Now > remindTime) return EnumRemindTimeStatus.Expire; var nowTime = DateTime.Now; TimeSpan ts = remindTime - nowTime; return ts.TotalMinutes <= 1 ? EnumRemindTimeStatus.Push : EnumRemindTimeStatus.Valid; } /// <summary> /// 调用api返回json /// </summary> /// <param name="url">api地址</param> /// <param name="jsonstr">接收参数</param> /// <param name="type">类型</param> /// <returns></returns> private string HttpApi(string url, string jsonstr, string type) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址 request.Accept = "text/html,application/xhtml+xml,*/*"; request.ContentType = "application/json"; request.Method = type.ToUpper().ToString();//get或者post byte[] buffer = encoding.GetBytes(jsonstr); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } /// <summary> /// 提醒时间状态枚举 /// </summary> private enum EnumRemindTimeStatus { /// <summary> /// 过期 /// </summary> Expire = 0, /// <summary> /// 发送 /// </summary> Push = 1, /// <summary> /// 有效的 /// </summary> Valid = 2 } /// <summary> /// RedisViewModel /// </summary> public class RedisViewModel { /// <summary> /// 任务编码 /// </summary> public string Code { get; set; } /// <summary> /// 提醒时间 /// </summary> public string RemindTime { get; set; } /// <summary> /// 提醒字符串 /// </summary> public string RemindStr { get; set; } } } }
using Boleto2Net; using DevExpress.CodeParser; using DevExpress.CodeParser.Diagnostics; using DevExpress.DataProcessing; using DevExpress.XtraBars.Alerter; using DevExpress.XtraGrid.Views.Grid; using DFe.Classes.Flags; using MetroFramework; using NFe.Classes.Informacoes.Emitente; using PDV.CONTROLER.Funcoes; using PDV.CONTROLLER.NFE.Transmissao; using PDV.CONTROLLER.NFE.Util; using PDV.DAO.Custom; using PDV.DAO.DB.Utils; using PDV.DAO.Entidades; using PDV.DAO.Entidades.Estoque.Movimento; using PDV.DAO.Entidades.Financeiro; using PDV.DAO.Entidades.NFe; using PDV.DAO.Entidades.PDV; using PDV.DAO.Enum; using PDV.UTIL; using PDV.UTIL.Components; using PDV.VIEW.App_Context; using PDV.VIEW.BOLETO.Classes; using PDV.VIEW.Forms.Util; using PDV.VIEW.Forms.Vendas.Manifesto; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace PDV.VIEW.Forms.Vendas.NFe { public partial class GVEN_NFe : DevExpress.XtraEditors.XtraForm { private string NOME_TELA = "Emissão de NF-e"; /* Seletores */ private List<Cfop> CFOPS = null; private List<Finalidade> FINALIDADES = null; private List<TipoAtendimento> TIPOSATENDIMENTO = null; private List<DocumentoReferenciado> TIPOS_DOC_REF = null; private List<UnidadeFederativa> UF_REF = null; private List<FormaDePagamento> FORMASPAGAMENTO = null; /* Cliente */ private Cliente Cliente { get; set; } = null; private DAO.Entidades.Endereco EnderecoCliente { get; set; } = null; private Contato ContatoCliente { get; set; } = null; private UnidadeFederativa UFCliente { get; set; } = null; private Municipio MunicipioCliente { get; set; } = null; /* Transportadora */ private Transportadora Transportadora { get; set; } = null; private DAO.Entidades.Endereco EnderecoTransportadora { get; set; } = null; /* Grids */ private DataTable DOCS_REFERENCIADOS = null; private DataTable PRODUTOS = null; private DataTable Duplicatas { get; set; } = null; /* Variaveis de Controle */ private DAO.Entidades.NFe.NFe NFe = null; private VolumeNFe Volume = null; //private bool EDITANDO = false; public DataTable ProdutosNFeICMS = null; public DataTable ProdutosNFePIS = null; public DataTable ProdutosNFeCOFINS = null; public DataTable ProdutosNFePARTILHA = null; private decimal? IDMovimentoFiscal = null; string UfCliente, UfEmitente; public GVEN_NFe(DAO.Entidades.NFe.NFe _NFe, bool Editando = false, decimal? _IDMovimentoFiscal = null) { InitializeComponent(); NFe = _NFe; IDMovimentoFiscal = _IDMovimentoFiscal; Preencher(); if (NFe.IDNFe != -1) simpleButtonCarregarVenda.Enabled = false; } private void Preencher() { ovTXT_PesoBruto.AplicaAlteracoes(); ovTXT_PesoLiquido.AplicaAlteracoes(); ovTXT_QuantidadeParcela.AplicaAlteracoes(); ovTXT_Frete.AplicaAlteracoes(); ovTXT_Despesas.AplicaAlteracoes(); ovTXT_Desconto.AplicaAlteracoes(); ovTXT_Seguro.AplicaAlteracoes(); IniciaSeletores(); ProdutosNFeICMS = FuncoesProdutoNFeICMS.GetProdutoICMS(NFe.IDNFe); ProdutosNFePIS = FuncoesProdutoNFePIS.GetProdutoPIS(NFe.IDNFe); ProdutosNFeCOFINS = FuncoesProdutoNFeCOFINS.GetProdutoCOFINS(NFe.IDNFe); ProdutosNFePARTILHA = FuncoesProdutoNFePartilhaICMS.GetPartilhas(NFe.IDNFe); GetDadosCliente(); GetDadosTransportadora(); } private void IniciaSeletores() { CFOPS = FuncoesCFOP.GetCFOPSAtivos(); ovCMB_NaturezaOperacao.DataSource = CFOPS; ovCMB_NaturezaOperacao.DisplayMember = "codigodescricao"; ovCMB_NaturezaOperacao.ValueMember = "idcfop"; ovCMB_NaturezaOperacao.SelectedItem = null; FINALIDADES = FuncoesFinalidade.GetFinalidades(); ovCMB_Finalidade.DisplayMember = "descricao"; ovCMB_Finalidade.ValueMember = "idfinalidade"; ovCMB_Finalidade.DataSource = FINALIDADES; TIPOSATENDIMENTO = FuncoesTipoAtendimento.GetTiposAtendimento(); ovCMB_TipoAtendimento.DisplayMember = "descricao"; ovCMB_TipoAtendimento.ValueMember = "idtipoatendimento"; ovCMB_TipoAtendimento.DataSource = TIPOSATENDIMENTO; ovTXT_Vendedor.Text = Contexto.USUARIOLOGADO.Nome; TIPOS_DOC_REF = FuncoesDocumentoReferenciadoNFe.GetTiposDocumentoReferenciado(); ovCMB_ModeloDocRef.DataSource = TIPOS_DOC_REF; ovCMB_ModeloDocRef.DisplayMember = "descricao"; ovCMB_ModeloDocRef.ValueMember = "codigo"; UF_REF = FuncoesUF.GetUnidadesFederativaNFe(); ovCMB_UFDocRef.DataSource = UF_REF; ovCMB_UFDocRef.DisplayMember = "sigla"; ovCMB_UFDocRef.ValueMember = "idunidadefederativa"; FORMASPAGAMENTO = FuncoesFormaDePagamento.GetFormasPagamento(); ovCMB_FormaPagamento.DataSource = FORMASPAGAMENTO; ovCMB_FormaPagamento.ValueMember = "idformadepagamento"; ovCMB_FormaPagamento.DisplayMember = "identificacaodescricaoformabandeira"; ovCMB_FormaPagamento.SelectedItem = FORMASPAGAMENTO.AsEnumerable().Where(o => o.IDFormaDePagamento == NFe.IDFormaDePagamento).FirstOrDefault(); ovCMB_FormaPagamento.Select(); textBoxNoDaVenda.Text = NFe.IDVenda.ToString(); metroTabControl2.SelectedTab = metroTabPage5; } private void metroButton2_Click(object sender, EventArgs e) { AdicionarProduto(); } private void AdicionarProduto(ItemVenda itemVenda = null) { if (Cliente == null) { MessageBox.Show(this, "Selecione o Cliente.", NOME_TELA); return; } Emitente Emit = FuncoesEmitente.GetEmitente(); DAO.Entidades.Endereco Ender = FuncoesEndereco.GetEndereco(Emit.IDEndereco); decimal idUFEmitente = FuncoesUF.GetUnidadeFederativa(Ender.IDUnidadeFederativa.Value).IDUnidadeFederativa; using (GVEN_ItemNFe FormAdicionaItem = new GVEN_ItemNFe((CRT)Enum.Parse(typeof(CRT), Emit.CRT.ToString()), FuncoesUF.GetUnidadeFederativa(EnderecoCliente.IDUnidadeFederativa.Value), ProdutosNFeICMS.NewRow(), ProdutosNFePIS.NewRow(), ProdutosNFeCOFINS.NewRow(), ProdutosNFePARTILHA.NewRow())) { bool adcionadoManualmente = false; if (itemVenda != null) FormAdicionaItem.EscolherProduto(itemVenda); else { FormAdicionaItem.ShowDialog(this); adcionadoManualmente = true; } if (FormAdicionaItem.Prod != null && FormAdicionaItem.ProdutoNFe != null && FormAdicionaItem.ProdutoNFe.IDProdutoNFe != -1) { var ValorTotalProduto = itemVenda != null ? ItemVendaUtil.GetTotalItem(itemVenda) : GetValorTotalProduto(FormAdicionaItem); DataRow drProduto = PRODUTOS.NewRow(); drProduto["IDPRODUTO"] = FormAdicionaItem.Prod.IDProduto; drProduto["IDUNIDADEDEMEDIDA"] = FormAdicionaItem.Prod.IDUnidadeDeMedida; drProduto["PRODUTO"] = FormAdicionaItem.Prod.Descricao; drProduto["CODIGO"] = FormAdicionaItem.Prod.Codigo; drProduto["CSTCSOSN"] = FuncoesCst.GetCSTIcmsPorID(FormAdicionaItem.Integ.IDCSTIcms).CSTCSOSN; string SCfop = FuncoesCFOP.GetCFOP(FormAdicionaItem.ProdutoNFe.IDCFOP).Codigo; if (idUFEmitente != UFCliente.IDUnidadeFederativa) drProduto["IDCFOP"] = drProduto["CFOP"] = ConverterCFOParaForaDoEstado(FormAdicionaItem.ProdutoNFe.IDCFOP, SCfop); else drProduto["IDCFOP"] = drProduto["CFOP"] = FuncoesCFOP.GetCFOP(FormAdicionaItem.ProdutoNFe.IDCFOP).Codigo; SCfop = drProduto["CFOP"].ToString(); Cfop cfop = FuncoesCFOP.GetCFOPPorCodigo(SCfop); drProduto["QUANTIDADE"] = FormAdicionaItem.ProdutoNFe.Quantidade; drProduto["VALORUNITARIO"] = FormAdicionaItem.ProdutoNFe.ValorUnitario; drProduto["DESCONTO"] = FormAdicionaItem.ProdutoNFe.Desconto; drProduto["VALORTOTAL"] = ValorTotalProduto; drProduto["TOTALFINANCEIRO"] = ValorTotalProduto; drProduto["IDPRODUTONFE"] = FormAdicionaItem.ProdutoNFe.IDProdutoNFe; drProduto["IDPRODUTO"] = FormAdicionaItem.ProdutoNFe.IDProduto; drProduto["IDNFE"] = NFe.IDNFe; drProduto["FRETE"] = FormAdicionaItem.ProdutoNFe.Frete; drProduto["OUTRASDESPESAS"] = FormAdicionaItem.ProdutoNFe.OutrasDespesas; drProduto["IDINTEGRACAOFISCAL"] = FormAdicionaItem.ProdutoNFe.IDIntegracaoFiscal; drProduto["SEGURO"] = FormAdicionaItem.ProdutoNFe.Seguro; drProduto["MANUALMENTE"] = adcionadoManualmente; PRODUTOS.Rows.Add(drProduto); ProdutosNFeICMS.Rows.Add(FormAdicionaItem.DrProdutosNFeICMS); ProdutosNFePIS.Rows.Add(FormAdicionaItem.DrProdutosNFePIS); ProdutosNFeCOFINS.Rows.Add(FormAdicionaItem.DrProdutosNFeCOFINS); ProdutosNFePARTILHA.Rows.Add(FormAdicionaItem.DrProdutosNFePARTILHA); CarregarProdutos(false); CalculaTotalNFe(); if (FormAdicionaItem.Integ.IDPortaria.HasValue && string.IsNullOrEmpty(ovTXT_InformacoesComplementares.Text)) ovTXT_InformacoesComplementares.Text = FuncoesPortaria.GetPortaria(FormAdicionaItem.Integ.IDPortaria.Value).Descricao; LimparDuplicatas(); } } } private static string ConverterCFOParaForaDoEstado(decimal defaultIdCfop, string SCfop) { switch (SCfop) { case "5101": return "6101"; case "5102": return "6102"; case "5103": return "6103"; case "5104": return "6104"; case "5105": return "6105"; case "5403": return "6403"; case "5405": return "6405"; default: return FuncoesCFOP.GetCFOP(defaultIdCfop).Codigo; } } private static decimal GetValorTotalProduto(GVEN_ItemNFe FormAdicionaItem) { return (((FormAdicionaItem.ProdutoNFe.ValorUnitario + FormAdicionaItem.ProdutoNFe.Frete + FormAdicionaItem.ProdutoNFe.OutrasDespesas + FormAdicionaItem.ProdutoNFe.Seguro) * FormAdicionaItem.ProdutoNFe.Quantidade) + FormAdicionaItem.ovTXT_ValorIcmsST.Value) - FormAdicionaItem.ProdutoNFe.Desconto; } private void ovTXT_CodNatOp_KeyUp(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: ovCMB_NaturezaOperacao.SelectedItem = CFOPS.Where(o => o.Codigo == ZeusUtil.SomenteNumeros(ovTXT_CodNatOp.Text)).FirstOrDefault(); if (ovCMB_NaturezaOperacao.SelectedItem == null) { MessageBox.Show(this, "CFOP não encontrado."); ovCMB_NaturezaOperacao.Select(); ovCMB_NaturezaOperacao.SelectAll(); } break; } } private void PreencheCliente() { ovTXT_CodCliente.Text = Cliente.IDCliente.ToString(); ovTXT_Cliente.Text = Cliente.TipoDocumento == 0 ? Cliente.NomeFantasia : Cliente.Nome; ovTXT_ClienteCNPJCPF.Text = Cliente.TipoDocumento == 0 ? Cliente.CNPJ : Cliente.CPF; ovTXT_ClienteCep.Text = string.IsNullOrEmpty(EnderecoCliente.Cep.ToString()) ? "<Não Informado>" : EnderecoCliente.Cep.ToString(); ovTXT_ClienteUF.Text = UFCliente == null ? "" : UFCliente.Sigla; ovTXT_ClienteBairro.Text = EnderecoCliente.Bairro; ovTXT_ClienteInscEstadual.Text = Cliente.InscricaoEstadual == null ? string.Empty : (string.IsNullOrEmpty(Cliente.InscricaoEstadual.ToString()) ? "<Não Informado>" : Cliente.InscricaoEstadual.ToString()); ovTXT_ClienteLogradouro.Text = EnderecoCliente.Logradouro; ovTXT_ClienteNumero.Text = EnderecoCliente.Numero.ToString(); ovTXT_ClienteComplemento.Text = string.IsNullOrEmpty(EnderecoCliente.Complemento) ? "<Não Informado>" : EnderecoCliente.Complemento; ovTXT_ClienteCidade.Text = MunicipioCliente == null ?"": MunicipioCliente.Descricao; ovTXT_ClienteEmail.Text = string.IsNullOrEmpty(ContatoCliente.Email) ? "<Não Informado>" : ContatoCliente.Email; } public void GetDadosCliente() { if (FuncoesCliente.GetCliente(NFe.IDCliente) != null) { ovBTN_SalvarETransmitir.Enabled = false; Cliente = FuncoesCliente.GetCliente(NFe.IDCliente); EnderecoCliente = FuncoesEndereco.GetEndereco(Cliente.IDEndereco.Value); if (Cliente.IDContato.HasValue) ContatoCliente = FuncoesContato.GetContato(Cliente.IDContato.Value); decimal? idUf = EnderecoCliente.IDUnidadeFederativa, idMunicipio = EnderecoCliente.IDMunicipio; if (!idUf.HasValue || !idMunicipio.HasValue) throw new Exception("Informe o endereço do cliente para emitir uma NF-e"); UFCliente = FuncoesUF.GetUnidadeFederativa(idUf.Value); MunicipioCliente = FuncoesMunicipio.GetMunicipio(idMunicipio.Value); } } private void GetDadosTransportadora() { } private void button1_Click(object sender, EventArgs e) { GVEN_SeletorTransportadora SeletorTransportadora = new GVEN_SeletorTransportadora(); SeletorTransportadora.ShowDialog(this); if (SeletorTransportadora.DRTransportadora == null) return; DataRow DrSelecionada = DrSelecionada = SeletorTransportadora.DRTransportadora; Transportadora = FuncoesTransportadora.GetTransportadora(Convert.ToDecimal(DrSelecionada["IDTRANSPORTADORA"])); EnderecoTransportadora = FuncoesEndereco.GetEndereco(Convert.ToDecimal(DrSelecionada["IDENDERECO"])); // Verificar Aqui.. ovTXT_UFTransportadora.Text = EnderecoTransportadora.IDUnidadeFederativa.HasValue ? FuncoesUF.GetUnidadeFederativa(EnderecoTransportadora.IDUnidadeFederativa.Value).Sigla : string.Empty; ovTXT_Codtransportadora.Text = Transportadora.IDTransportadora.ToString(); ovTXT_Transportadora.Text = Transportadora.TipoDocumento == 0 ? Transportadora.RazaoSocial : Transportadora.Nome; ovTXT_TransportadoraCNPJCPF.Text = Transportadora.TipoDocumento == 0 ? Transportadora.CNPJ : Transportadora.CPF; } private void GVEN_NFe_Load(object sender, EventArgs e) { PreencherTela(); } private void CarregarNotasReferenciadas(bool BuscaBanco) { if (BuscaBanco) DOCS_REFERENCIADOS = FuncoesDocumentoReferenciadoNFe.GetDocumentosReferenciadosNFe(NFe.IDNFe); gridControlDocumentoRefenciados.DataSource = DOCS_REFERENCIADOS; AjustaHeaderNotasRef(); gridViewDocumentosReferenciados.BestFitColumns(); } private void AjustaHeaderNotasRef() { for (int i = 0; i < gridViewDocumentosReferenciados.Columns.Count; i++) { switch (gridViewDocumentosReferenciados.Columns[i].AbsoluteIndex) { case 6: gridViewDocumentosReferenciados.Columns[i].Caption = "TIPO"; break; case 3: gridViewDocumentosReferenciados.Columns[i].Caption = "UF"; break; case 4: gridViewDocumentosReferenciados.Columns[i].Caption = "CHAVE"; break; default: gridViewDocumentosReferenciados.Columns[i].Visible = false; break; } } } private void AjustarCabecalhosProdutos() { Grids.FormatGrid(ref gridViewProdutos); Grids.FormatColumnType(ref gridViewProdutos, new List<string> { "manualmente", "idunidadedemedida", "idintegracaofiscal", "seguro", "sequencia", "outrasdespesas", "idnfe", "idprodutonfe1", "totalfinanceiro", "cstcsosn", "frete", "idproduto" }, GridFormats.VisibleFalse); Grids.FormatColumnType(ref gridViewProdutos, new List<string> { "valortotal", "desconto", "valorunitario" }, GridFormats.Finance); Grids.FormatColumnType(ref gridViewProdutos, new List<string> { "valortotal", "desconto", "valorunitario" }, GridFormats.SumFinance); } private void PreencherTela() { try { Cursor.Current = Cursors.WaitCursor; /* Cabecalho */ var venda = FuncoesVenda.GetVenda(NFe.IDVenda); ovTXT_Emissao.Text = NFe.Emissao.ToString(); ovTXT_Saida.Text = NFe.Saida.ToString(); ovCMB_Finalidade.SelectedItem = FINALIDADES.Where(o => o.IDFinalidade == NFe.IDFinalidade).FirstOrDefault(); ovCMB_TipoAtendimento.SelectedItem = TIPOSATENDIMENTO.Where(o => o.IDTipoAtendimento == NFe.IDTipoAtendimento).FirstOrDefault(); textBoxNoDaVenda.Text = NFe.IDVenda != -1 ? NFe.IDVenda.ToString() : ""; if (venda != null) { Usuario vendedor = FuncoesUsuario.GetUsuario(Convert.ToDecimal(venda.IDVendedor)); ovTXT_Vendedor.Text = vendedor != null ? vendedor.Nome : ""; } ovTXT_Serie.Text = Contexto.CONFIGURACAO_SERIE.SerieNFe.ToString(); switch (Convert.ToInt32(NFe.INDPagamento)) { case 0: ovCKB_Avista.Checked = true; break; case 1: ovCKB_Aprazo.Checked = true; break; case 2: ovCKB_Outros.Checked = true; break; } /* Cliente */ GetDadosCliente(); if (Cliente != null) PreencheCliente(); if (UFCliente != null) { if (venda != null) { var tipoDeOperacao = FuncoesTipoDeOperacao.GetTipoDeOperacao(venda.IDTipoDeOperacao); decimal idCfop = ProcessarCFOP(tipoDeOperacao.IDOperacaoFiscal); ovCMB_NaturezaOperacao.SelectedItem = CFOPS.Where(o => o.IDCfop == idCfop).FirstOrDefault(); } else { decimal idCfop = ProcessarCFOP(NFe.IDCFOP); ovCMB_NaturezaOperacao.SelectedItem = CFOPS.Where(o => o.IDCfop == idCfop).FirstOrDefault(); } } /* Transportadora */ if (NFe.IDTransportadora != 0 && NFe.IDTransportadora != null) { Transportadora = FuncoesTransportadora.GetTransportadora(NFe.IDTransportadora.Value); if (Transportadora != null) { EnderecoTransportadora = FuncoesEndereco.GetEndereco(Transportadora.IDEndereco); ovTXT_UFTransportadora.Text = EnderecoTransportadora.IDUnidadeFederativa.HasValue ? FuncoesUF.GetUnidadeFederativa(EnderecoTransportadora.IDUnidadeFederativa.Value).Sigla : string.Empty; ovTXT_Codtransportadora.Text = Transportadora.IDTransportadora.ToString(); ovTXT_Transportadora.Text = Transportadora.TipoDocumento == 0 ? Transportadora.RazaoSocial : Transportadora.Nome; ovTXT_TransportadoraCNPJCPF.Text = Transportadora.TipoDocumento == 0 ? Transportadora.CNPJ : Transportadora.CPF; ovTXT_TransportadoraPlaca.Text = NFe.Placa; ovTXT_TransportadoraVeiculo.Text = NFe.Veiculo; ovTXT_TransportadoraANTT.Text = NFe.ANTT; } } switch (Convert.ToInt32(NFe.FretePor)) { case 0: ovCKB_FreteEmitente.Checked = true; break; case 1: ovCKB_FreteDestinatario.Checked = true; break; case 2: ovCKB_FreteTerceiros.Checked = true; break; case 9: ovCKB_FreteSemFrete.Checked = true; break; } /* Volumes e Informações Adicionais */ ovTXT_InformacoesComplementares.Text = NFe.InformacoesComplementares; Volume = FuncoesVolume.GetVolume(NFe.IDNFe); if (Volume == null) Volume = new VolumeNFe(); ovTXT_Volume.Text = Volume.Volume; ovTXT_NumeroVolume.Text = Volume.Numero; ovTXT_PesoLiquido.Value = Volume.PesoLiquido; ovTXT_PesoBruto.Value = Volume.PesoBruto; ovTXT_Marca.Text = Volume.Marca; ovTXT_Especie.Text = Volume.Especie; CarregarNotasReferenciadas(true); CarregarProdutos(true); CarregarFinanceiro(true); ovTXT_Frete.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["FRETE"])); ovTXT_Despesas.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["OUTRASDESPESAS"])); ovTXT_Desconto.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["DESCONTO"])); ovTXT_Seguro.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["SEGURO"])); RateioDeValores(ovTXT_Frete.Value, ovTXT_Despesas.Value, ovTXT_Desconto.Value, ovTXT_Seguro.Value); CalculaTotalNFe(); /*Lista de produtos*/ if (NFe.IDNFe == -1) { var listaProdutosNFe = new List<ProdutoNFe>(); var listaItensVenda = FuncoesItemVenda.GetItensVenda(NFe.IDVenda); listaItensVenda.ForEach(i => AdicionarProduto(i)); } /*Forma de Pagamento*/ GerarParcelas(duplicataNFCe); Cursor.Current = Cursors.WaitCursor; } catch (Exception ex) { Cursor.Current = Cursors.Default; MessageBox.Show(this,ex.Message,"Erro ao carregar NOTA",MessageBoxButtons.OK,MessageBoxIcon.Error); } } private decimal ProcessarCFOP(decimal _idCFOP) { var emitente = FuncoesEmitente.GetEmitente(); var endereco = FuncoesEndereco.GetEndereco(emitente.IDEndereco); var idUFEmitente = FuncoesUF.GetUnidadeFederativa(endereco.IDUnidadeFederativa.Value).IDUnidadeFederativa; decimal idCFOP; if (idUFEmitente != UFCliente.IDUnidadeFederativa) idCFOP = Convert.ToDecimal(ConverterCFOParaForaDoEstado( _idCFOP, _idCFOP.ToString())); else idCFOP = _idCFOP; return idCFOP; } private void CarregarProdutos(bool BuscarBanco) { if (BuscarBanco) { PRODUTOS = FuncoesProdutoNFe.GetProdutos(NFe.IDNFe); PRODUTOS.Columns.Add("MANUALMENTE", typeof(bool)); } gridControl1.DataSource = PRODUTOS; AjustarCabecalhosProdutos(); CalculaTotalNFe(); } private void CarregarFinanceiro(bool BuscarBanco) { if (BuscarBanco) Duplicatas = FuncoesDuplicataNFe.GetDuplicatas(NFe.IDNFe); gridControlFinanceiro.DataSource = Duplicatas; AjustaHeaderFinanceiro(); gridViewFinanceiro.BestFitColumns(); } private void AjustaHeaderFinanceiro() { for (int i = 0; i < gridViewFinanceiro.Columns.Count; i++) { switch (gridViewFinanceiro.Columns[i].AbsoluteIndex) { case 2: gridViewFinanceiro.Columns[i].Caption = "NÚMERO DO DOCUMENTO"; break; case 3: gridViewFinanceiro.Columns[i].Caption = "VENCIMENTO"; break; case 4: gridViewFinanceiro.Columns[i].Caption = "VALOR"; gridViewFinanceiro.Columns[i].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; gridViewFinanceiro.Columns[i].DisplayFormat.FormatString = "c2"; break; default: gridViewFinanceiro.Columns[i].Visible = false; break; } } } private void metroButton10_Click(object sender, EventArgs e) { if (ovCMB_ModeloDocRef.SelectedItem == null) { MessageBox.Show(this, "Selecione o Tipo de Documento."); return; } if (ovCMB_UFDocRef.SelectedItem == null) { MessageBox.Show(this, "Selecione a UF."); return; } if (string.IsNullOrEmpty(ovTXT_ChaveDoc.Text)) { MessageBox.Show(this, "Informe a Chave."); return; } DataRow drDoc = DOCS_REFERENCIADOS.NewRow(); drDoc["IDDOCUMENTOREFERENCIADONFE"] = Sequence.GetNextID("DOCUMENTOREFERENCIADONFE", "IDDOCUMENTOREFERENCIADONFE"); drDoc["IDNFE"] = NFe.IDNFe; drDoc["IDUNIDADEFEDERATIVA"] = (ovCMB_UFDocRef.SelectedItem as UnidadeFederativa).IDUnidadeFederativa; drDoc["UNIDADEFEDERATIVA"] = (ovCMB_UFDocRef.SelectedItem as UnidadeFederativa).Sigla; drDoc["CHAVE"] = ovTXT_ChaveDoc.Text; drDoc["CODIGODOCUMENTOREFERENCIADO"] = (ovCMB_ModeloDocRef.SelectedItem as DocumentoReferenciado).Codigo; drDoc["DOCUMENTOREFERENCIADO"] = (ovCMB_ModeloDocRef.SelectedItem as DocumentoReferenciado).Descricao; DOCS_REFERENCIADOS.Rows.Add(drDoc); CarregarNotasReferenciadas(false); CalculaTotalNFe(); } private void metroButton8_Click(object sender, EventArgs e) { int rowHandle = gridViewDocumentosReferenciados.FocusedRowHandle; string fieldName = gridViewDocumentosReferenciados.Columns[0].FieldName; decimal id = Convert.ToDecimal(gridViewDocumentosReferenciados.GetRowCellValue(rowHandle, fieldName)); if (MessageBox.Show(this, "Deseja remover o registro selecionado?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { DOCS_REFERENCIADOS.DefaultView.RowFilter = "[IDDOCUMENTOREFERENCIADONFE] = " + id.ToString(); foreach (DataRowView drv in DOCS_REFERENCIADOS.DefaultView) drv.Delete(); DOCS_REFERENCIADOS.DefaultView.RowFilter = string.Empty; CarregarNotasReferenciadas(false); } } private void metroButton6_Click(object sender, EventArgs e) { if (gridViewProdutos.GetSelectedRows().Length > 1 ) { MessageBox.Show(this, "Selecione um registro para remover."); return; } int rowHanddle = gridViewProdutos.FocusedRowHandle; string fieldName = gridViewProdutos.Columns[0].FieldName ; decimal IDProdutoNFe = -1; if (rowHanddle > 1) { MessageBox.Show(this, "Selecione um registro para remover."); return; } else { IDProdutoNFe = Convert.ToDecimal(gridViewProdutos.GetRowCellValue(rowHanddle, fieldName)); } if (MessageBox.Show(this, "Deseja remover o registro selecionado?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { PRODUTOS.DefaultView.RowFilter = "[IDPRODUTONFE] = " + IDProdutoNFe; if (PRODUTOS.DefaultView.Count > 0) PRODUTOS.DefaultView[0].Delete(); ProdutosNFeICMS.DefaultView.RowFilter = "[IDPRODUTONFE] = " + IDProdutoNFe; if (ProdutosNFeICMS.DefaultView.Count > 0) ProdutosNFeICMS.DefaultView[0].Delete(); ProdutosNFePIS.DefaultView.RowFilter = "[IDPRODUTONFE] = " + IDProdutoNFe; if (ProdutosNFePIS.DefaultView.Count > 0) ProdutosNFePIS.DefaultView[0].Delete(); ProdutosNFeCOFINS.DefaultView.RowFilter = "[IDPRODUTONFE] = " + IDProdutoNFe; if (ProdutosNFeCOFINS.DefaultView.Count > 0) ProdutosNFeCOFINS.DefaultView[0].Delete(); ProdutosNFePARTILHA.DefaultView.RowFilter = "[IDPRODUTONFE] = " + IDProdutoNFe; if (ProdutosNFePARTILHA.DefaultView.Count > 0) ProdutosNFePARTILHA.DefaultView[0].Delete(); PRODUTOS.DefaultView.RowFilter = string.Empty; ProdutosNFeICMS.DefaultView.RowFilter = string.Empty; ProdutosNFePIS.DefaultView.RowFilter = string.Empty; ProdutosNFeCOFINS.DefaultView.RowFilter = string.Empty; ProdutosNFePARTILHA.DefaultView.RowFilter = string.Empty; CarregarProdutos(false); } CalculaTotalNFe(); LimparDuplicatas(); } private void CalculaTotalNFe() { ovTXT_Frete.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["FRETE"])); ovTXT_Despesas.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["OUTRASDESPESAS"])); ovTXT_Desconto.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["DESCONTO"])); ovTXT_Seguro.Value = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["SEGURO"])); ovTXT_TotalNFe.Text = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["VALORTOTAL"])).ToString("c2"); ovTXT_TotalFinanceiro.Text = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["TOTALFINANCEIRO"])).ToString("c2"); } private void metroButton9_Click(object sender, EventArgs e) { LimparDuplicatas(); } private void metroButton11_Click(object sender, EventArgs e) { GerarParcelas(); } private void GerarParcelas(List<DuplicataNFCe> duplicataNFCes = null) { // Gerar Parcelas. if (duplicataNFCes != null) { LimparDuplicatas(); double TotalNFe = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDouble(o["TOTALFINANCEIRO"])); InserirDuplicatas(duplicataNFCes); decimal ValorFalta = Convert.ToDecimal(TotalNFe) - Duplicatas.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["VALOR"])); foreach (DataRow dr in Duplicatas.Rows) { if (dr.RowState == DataRowState.Deleted) continue; dr["VALOR"] = Convert.ToDecimal(dr["VALOR"]) + ValorFalta; break; } CarregarFinanceiro(false); } } private void InserirDuplicatas(List<DuplicataNFCe> duplicataNFCes) { var vencimento = ovTXT_PrimeiraParcela.Value; foreach (var item in duplicataNFCes) { var formaDePagamento = FuncoesFormaDePagamento.GetFormaDePagamento(item.IDFormaDePagamento); double valorParcela = ZeusUtil.Arredondar((double)item.Valor, 2); vencimento = item.DataVencimento; DataRow dr = Duplicatas.NewRow(); dr["IDDUPLICATANFE"] = Sequence.GetNextID("DUPLICATANFE", "IDDUPLICATANFE"); dr["IDNFE"] = NFe.IDNFe; dr["NUMERODOCUMENTO"] = formaDePagamento.Identificacao; dr["DATAVENCIMENTO"] = vencimento.Date; dr["VALOR"] = valorParcela; dr["IDFORMADEPAGAMENTO"] = item.IDFormaDePagamento; Duplicatas.Rows.Add(dr); } } private void metroButton1_Click(object sender, EventArgs e) { if (MessageBox.Show(this, "Deseja cancelar o preenchimento da NF-e?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Close(); } private void metroButton4_Click(object sender, EventArgs e) { if (!ValidarNFe()) return; // salvarnfe SalvarNFe(); } private void metroButton5_Click(object sender, EventArgs e) { if (!ValidarNFe()) return; // salvarnfe SalvarNFe(true); } private void TransmitirNFe() { MovimentoFiscal Movimento = null; if (IDMovimentoFiscal.HasValue) Movimento = FuncoesMovimentoFiscal.GetMovimento(IDMovimentoFiscal.Value); EventosNFe Ev = new EventosNFe(NFe, Contexto.CONFIGURACAO_SERIE.SerieNFe, Movimento != null ? Convert.ToInt32(Movimento.Numero) : Sequence.GetNextID(Contexto.CONFIGURACAO_SERIE.NomeSequenceNFe)); Ev.CaminhoSolution = Contexto.CaminhoSolution; RetornoTransmissaoNFe Retorno = Ev.TransmitirNFe(); if (Retorno.isAutorizada) { ZeusUtil.GerarFinanceiro(Retorno.IDMovimentoFiscal, ModeloDocumento.NFe, Contexto.USUARIOLOGADO); if (Retorno.isVisualizar) Retorno.danfe.Visualizar(); else Retorno.danfe.Imprimir(Retorno.isCaixaDialogo, Retorno.NomeImpressora); var lQueryPrimeiroProduto = PRODUTOS.AsEnumerable().FirstOrDefault(); if (lQueryPrimeiroProduto != null) { IntegracaoFiscal Integ = FuncoesIntegracaoFiscal.GetIntegracao(FuncoesProduto.GetProduto(Convert.ToDecimal(lQueryPrimeiroProduto["IDPRODUTO"])).IDIntegracaoFiscalNFe.Value); if (Integ.Financeiro == 1) GerarDuplicatas(Retorno.IDMovimentoFiscal, (decimal)Movimento.IDVenda); } } else MessageBox.Show(this, Retorno.MotivoErro, NOME_TELA); Close(); } private bool ValidarNFe() { /* Validação da Primeira Aba */ if (ovCMB_NaturezaOperacao.SelectedItem == null) { MessageBox.Show(this, "Selecione a Natureza da Operação.", NOME_TELA); return false; } if (ovCMB_Finalidade.SelectedItem == null) { MessageBox.Show(this, "Selecione a Finalidade.", NOME_TELA); return false; } if (ovCMB_TipoAtendimento.SelectedItem == null) { MessageBox.Show(this, "Selecione o Tipo de Atendimento.", NOME_TELA); return false; } if (Cliente == null) { MessageBox.Show(this, "Selecione o Cliente.", NOME_TELA); return false; } if ((ovCKB_FreteDestinatario.Checked || ovCKB_FreteEmitente.Checked || ovCKB_FreteTerceiros.Checked) && Transportadora == null) { //MessageBox.Show(this, "Selecione a Transportadora.", NOME_TELA); //return false; } var lQueryProdutos = PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Count(); if (lQueryProdutos == 0) { MessageBox.Show(this, "Informe os Produtos.", NOME_TELA); return false; } var CountDuplic = Duplicatas.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Count(); if (CountDuplic == 0) { MessageBox.Show(this, "Informe as Duplciatas do Financeiro.", NOME_TELA); return false; } return true; } private void SalvarNFe(bool Transmitir = false) { try { PDVControlador.BeginTransaction(); /* NF-e */ TipoOperacao Op = TipoOperacao.UPDATE; if (NFe.IDNFe == -1) { NFe.IDNFe = Sequence.GetNextID("NFE", "IDNFE"); Op = TipoOperacao.INSERT; } decimal IDVENDA = 0; if (!string.IsNullOrEmpty(textBoxNoDaVenda.Text)) { IDVENDA = decimal.Parse(textBoxNoDaVenda.Text); } NFe.IDVenda = IDVENDA; ValidarSaldoEstoqueProdutos(); duplicataNFCe = FuncoesItemDuplicataNFCe.GetPagamentosPorVenda(IDVENDA); NFe.IDCFOP = (ovCMB_NaturezaOperacao.SelectedItem as Cfop).IDCfop; NFe.IDUsuario = Contexto.USUARIOLOGADO.IDUsuario; NFe.IDFinalidade = (ovCMB_Finalidade.SelectedItem as Finalidade).IDFinalidade; NFe.IDTipoAtendimento = (ovCMB_TipoAtendimento.SelectedItem as TipoAtendimento).IDTipoAtendimento; NFe.Modelo = Convert.ToInt32(ModeloDocumento.NFe); NFe.Serie = Contexto.CONFIGURACAO_SERIE.SerieNFe; NFe.IDCliente = Cliente.IDCliente; NFe.IDTransportadora = Transportadora == null ? null : (decimal?)Transportadora.IDTransportadora; NFe.Placa = (ovTXT_TransportadoraPlaca.Text.Trim().Equals("-") ? string.Empty : ovTXT_TransportadoraPlaca.Text.Replace("-", string.Empty)).ToUpper(); NFe.ANTT = ovTXT_TransportadoraANTT.Text; NFe.Veiculo = ovTXT_TransportadoraVeiculo.Text; NFe.FretePor = GetFretePor(); NFe.InformacoesComplementares = ovTXT_InformacoesComplementares.Text; NFe.INDPagamento = ovCKB_Avista.Checked ? 0 : (ovCKB_Aprazo.Checked ? 1 : 2); NFe.IDFormaDePagamento = duplicataNFCe[0].IDFormaDePagamento;//(ovCMB_FormaPagamento.SelectedItem as FormaDePagamento).IDFormaDePagamento; if (!FuncoesNFe.Salvar(NFe, Op)) throw new Exception("Não foi possível salvar a NF-e."); /* Documentos Referenciados */ DataTable dt = ZeusUtil.GetChanges(DOCS_REFERENCIADOS, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) { dr["IDNFE"] = NFe.IDNFe; if (!FuncoesDocumentoReferenciadoNFe.Salvar(EntityUtil<DocumentoReferenciadoNFe>.ParseDataRow(dr))) throw new Exception("Não foi possível salvar os Documentos Referenciados da NF-e."); } dt = ZeusUtil.GetChanges(DOCS_REFERENCIADOS, TipoOperacao.DELETE); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesDocumentoReferenciadoNFe.Remover(Convert.ToDecimal(dr["IDDOCUMENTOREFERENCIADONFE"]))) throw new Exception("Não foi possível salvar os Documentos Referenciados da NF-e."); /* Volumes */ Volume.Volume = ovTXT_Volume.Text; Volume.Marca = ovTXT_Marca.Text; Volume.Especie = ovTXT_Especie.Text; Volume.PesoLiquido = ovTXT_PesoLiquido.Value; Volume.PesoBruto = ovTXT_PesoBruto.Value; Volume.Numero = ovTXT_NumeroVolume.Text; if (Volume.IDVolumeNFe == -1) { Op = TipoOperacao.INSERT; Volume.IDVolumeNFe = Sequence.GetNextID("VOLUMENFE", "IDVOLUMENFE"); } Volume.IDNFe = NFe.IDNFe; if (!FuncoesVolume.Salvar(Volume, Op)) throw new Exception("Não foi possível salvar o Volume da NF-e."); /* Produtos */ int SequenciaProduto = 0; dt = ZeusUtil.GetChanges(PRODUTOS, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) { dr["IDNFE"] = NFe.IDNFe; dr["SEQUENCIA"] = SequenciaProduto++; ProdutoNFe _ProdutoNFe = EntityUtil<ProdutoNFe>.ParseDataRow(dr); if (!FuncoesProdutoNFe.Salvar(_ProdutoNFe, TipoOperacao.INSERT)) throw new Exception("Não foi possível salvar os Produtos da NF-e."); } dt = ZeusUtil.GetChanges(PRODUTOS, TipoOperacao.UPDATE); if (dt != null) foreach (DataRow dr in dt.Rows) { dr["IDNFE"] = NFe.IDNFe; dr["SEQUENCIA"] = SequenciaProduto++; if (!FuncoesProdutoNFe.Salvar(EntityUtil<ProdutoNFe>.ParseDataRow(dr), TipoOperacao.UPDATE)) throw new Exception("Não foi possível salvar os Produtos da NF-e."); } dt = ZeusUtil.GetChanges(PRODUTOS, TipoOperacao.DELETE); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesProdutoNFe.Remover(Convert.ToDecimal(dr["IDPRODUTONFE"]))) throw new Exception("Não foi possível salvar os Produtos da NF-e."); /* Financeiro */ dt = ZeusUtil.GetChanges(Duplicatas, TipoOperacao.DELETE); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesDuplicataNFe.Excluir(Convert.ToDecimal(dr["IDDUPLICATANFE"]))) throw new Exception("Não foi possível salvar a Duplicada da NF-e"); dt = ZeusUtil.GetChanges(Duplicatas, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) { dr["IDNFE"] = NFe.IDNFe; if (!FuncoesDuplicataNFe.Salvar(EntityUtil<DuplicataNFe>.ParseDataRow(dr))) throw new Exception("Não foi possível salvar a Duplicada da NF-e"); } /* Alíquotas */ SalvarAliquotas(); PDVControlador.Commit(); MessageBox.Show(this, "NF-e Salva com Sucesso.", NOME_TELA); if (Transmitir) TransmitirNFe(); else Close(); } catch (Exception Ex) { MessageBox.Show(this, Ex.Message, NOME_TELA); if (PDVControlador.CONTROLADOR.InTransaction(Contexto.IDCONEXAO_PRIMARIA)) PDVControlador.Rollback(); } } private void ValidarSaldoEstoqueProdutos() { //if (!FuncoesPerfilAcesso.ISEstoqueLiberado()) // return; //DataTable dt = ZeusUtil.GetChanges(PRODUTOS, TipoOperacao.INSERT); //if (dt == null) // return; //foreach (decimal IDProduto in dt.AsEnumerable().Select(o => Convert.ToDecimal(o["IDPRODUTO"]))) //{ // decimal QuantidadeVenda = dt.AsEnumerable().Where(o => Convert.ToDecimal(o["IDPRODUTO"]) == IDProduto).Sum(o => Convert.ToDecimal(o["QUANTIDADE"])); // Produto _Produto = FuncoesProduto.GetProduto(IDProduto); // if (_Produto.VenderSemSaldo == 0) // { // DataRow dr = FuncoesItemTransferenciaEstoque.GetProdutosComSaldoEmAlmoxarifado(_Produto.IDAlmoxarifadoSaida.Value, _Produto.IDProduto); // if (dr == null) // throw new Exception($"O Saldo do Item {_Produto.Descricao} não encontrado no almoxarifado de saida. Verifique!"); // var teste = Convert.ToDecimal(dr["SALDO"]); // if (QuantidadeVenda > Convert.ToDecimal(dr["SALDO"])) // throw new Exception($"O Saldo do Item {_Produto.Descricao} é menor que a quantidade de venda. Saldo: {QuantidadeVenda.ToString("n4")}."); // } //} } private void SalvarAliquotas() { /* ICMS */ DataTable dt = ZeusUtil.GetChanges(ProdutosNFeICMS, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesProdutoNFeICMS.Salvar(EntityUtil<ProdutoNFeICMS>.ParseDataRow(dr), TipoOperacao.INSERT)) throw new Exception("Não foi possivel Produtos os itens da NFe."); /* PIS */ dt = ZeusUtil.GetChanges(ProdutosNFePIS, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesProdutoNFePIS.Salvar(EntityUtil<ProdutoNFePIS>.ParseDataRow(dr), TipoOperacao.INSERT)) throw new Exception("Não foi possivel Produtos os itens da NFe."); /* COFINS */ dt = ZeusUtil.GetChanges(ProdutosNFeCOFINS, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesProdutoNFeCOFINS.Salvar(EntityUtil<ProdutoNFeCOFINS>.ParseDataRow(dr), TipoOperacao.INSERT)) throw new Exception("Não foi possivel Produtos os itens da NFe."); /* Partilha */ dt = ZeusUtil.GetChanges(ProdutosNFePARTILHA, TipoOperacao.INSERT); if (dt != null) foreach (DataRow dr in dt.Rows) if (!FuncoesProdutoNFePartilhaICMS.Salvar(EntityUtil<ProdutoNFePartilhaICMS>.ParseDataRow(dr), TipoOperacao.INSERT)) throw new Exception("Não foi possivel Produtos os itens da NFe."); } private void ovCMB_NaturezaOperacao_SelectedIndexChanged(object sender, EventArgs e) { ovTXT_Tipo.Text = ovCMB_NaturezaOperacao.SelectedItem == null ? "SAIDA" : (ovCMB_NaturezaOperacao.SelectedItem as Cfop).Tipo.Equals("1") ? "ENTRADA" : "SAIDA"; ovTXT_DataEntradaSaida.Text = ovCMB_NaturezaOperacao.SelectedItem == null ? "Saida:" : (ovCMB_NaturezaOperacao.SelectedItem as Cfop).Tipo.Equals("1") ? "Entrada:" : "Saida:"; } private int GetFretePor() { if (ovCKB_FreteEmitente.Checked) return 0; if (ovCKB_FreteDestinatario.Checked) return 1; if (ovCKB_FreteTerceiros.Checked) return 2; if (ovCKB_FreteSemFrete.Checked) return 9; throw new Exception("Selecione o Frete Por Conta."); } private void metroButton7_Click(object sender, EventArgs e) { if (PRODUTOS.DefaultView.Count == 0) { MessageBox.Show(this, "Adicione os Produtos para efetuar o Rateio.", NOME_TELA); return; } RateioDeValores(ovTXT_Frete.Value, ovTXT_Despesas.Value, ovTXT_Desconto.Value, ovTXT_Seguro.Value); CarregarProdutos(false); CalculaTotalNFe(); LimparDuplicatas(); } public void RateioDeValores(decimal ValorFrete, decimal ValorDespesas, decimal ValorDesconto, decimal ValorSeruro) { double ValorRateioFrete = 0; double ValorRateioDespesas = 0; double ValorRateioDesconto = 0; double ValorRateioSeguro = 0; if (PRODUTOS.DefaultView.Count != 0) { ValorRateioFrete = ZeusUtil.Arredondar((double)(ValorFrete / PRODUTOS.DefaultView.Count), 2); ValorRateioDespesas = ZeusUtil.Arredondar((double)(ValorDespesas / PRODUTOS.DefaultView.Count), 2); ValorRateioDesconto = ZeusUtil.Arredondar((double)(ValorDesconto / PRODUTOS.DefaultView.Count), 2); ValorRateioSeguro = ZeusUtil.Arredondar((double)(ValorSeruro / PRODUTOS.DefaultView.Count), 2); } foreach (DataRow dr in PRODUTOS.Rows) { if (dr.RowState == DataRowState.Deleted) continue; dr["DESCONTO"] = Convert.ToDecimal(ValorRateioDesconto); dr["FRETE"] = Convert.ToDecimal(ValorRateioFrete); dr["OUTRASDESPESAS"] = Convert.ToDecimal(ValorRateioDespesas); dr["SEGURO"] = Convert.ToDecimal(ValorRateioSeguro); } decimal ValorDescontoFaltando = ValorDesconto - PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["DESCONTO"])); decimal ValorFreteFaltando = ValorFrete - PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["FRETE"])); decimal ValorDespesaFaltando = ValorDespesas - PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["OUTRASDESPESAS"])); decimal ValorSeguroFaltando = ValorSeruro - PRODUTOS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["SEGURO"])); if (ValorDespesaFaltando > 0 || ValorFreteFaltando > 0) { foreach (DataRow dr in PRODUTOS.Rows) { if (dr.RowState == DataRowState.Deleted) continue; IntegracaoFiscal Integ = FuncoesIntegracaoFiscal.GetIntegracao(Convert.ToDecimal(dr["IDINTEGRACAOFISCAL"])); if (ValorDespesaFaltando == 0 && ValorFreteFaltando == 0 && ValorSeguroFaltando == 0) break; if (ValorDespesaFaltando != 0) { dr["OUTRASDESPESAS"] = Convert.ToDecimal(dr["OUTRASDESPESAS"]) + ValorDespesaFaltando; ValorDespesaFaltando = 0; } if (ValorFreteFaltando != 0) { dr["FRETE"] = Convert.ToDecimal(dr["FRETE"]) + ValorFreteFaltando; ValorFreteFaltando = 0; } if (ValorSeguroFaltando != 0) { dr["SEGURO"] = Convert.ToDecimal(dr["SEGURO"]) + ValorSeguroFaltando; ValorSeguroFaltando = 0; } decimal ValorST = ProdutosNFeICMS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted && Convert.ToDecimal(dr["IDPRODUTONFE"]) == Convert.ToDecimal(o["IDPRODUTONFE"])).Sum(o => Convert.ToDecimal(o["VICMSST"])); dr["VALORTOTAL"] = (((Convert.ToDecimal(dr["OUTRASDESPESAS"]) + Convert.ToDecimal(dr["FRETE"]) + Convert.ToDecimal(dr["VALORUNITARIO"]) + Convert.ToDecimal(dr["SEGURO"])) * Convert.ToDecimal(dr["QUANTIDADE"])) + ValorST) - Convert.ToDecimal(dr["DESCONTO"]); //if (Integ.Financeiro == 1) dr["TOTALFINANCEIRO"] = dr["VALORTOTAL"]; } } foreach (DataRow dr in PRODUTOS.Rows) { if (dr.RowState == DataRowState.Deleted) continue; IntegracaoFiscal Integ = FuncoesIntegracaoFiscal.GetIntegracao(Convert.ToDecimal(dr["IDINTEGRACAOFISCAL"])); if (ValorDescontoFaltando != 0 && Convert.ToDecimal(dr["VALORTOTAL"]) + ValorDescontoFaltando < Convert.ToDecimal(dr["VALORTOTAL"]) || (Convert.ToDecimal(dr["DESCONTO"]) - ValorDescontoFaltando >= 0)) { dr["DESCONTO"] = Convert.ToDecimal(dr["DESCONTO"]) + ValorDescontoFaltando; ValorDescontoFaltando = 0; } decimal ValorST = ProdutosNFeICMS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted && Convert.ToDecimal(dr["IDPRODUTONFE"]) == Convert.ToDecimal(o["IDPRODUTONFE"])).Sum(o => Convert.ToDecimal(o["VICMSST"])); dr["VALORTOTAL"] = (((Convert.ToDecimal(dr["OUTRASDESPESAS"]) + Convert.ToDecimal(dr["FRETE"]) + Convert.ToDecimal(dr["VALORUNITARIO"]) + Convert.ToDecimal(dr["SEGURO"])) * Convert.ToDecimal(dr["QUANTIDADE"])) + ValorST) - Convert.ToDecimal(dr["DESCONTO"]); //if (Integ.Financeiro == 1) dr["TOTALFINANCEIRO"] = dr["VALORTOTAL"]; } } private void LimparDuplicatas() { foreach (DataRowView dr in Duplicatas.DefaultView) dr.Delete(); gridControlFinanceiro.DataSource = Duplicatas; AjustaHeaderFinanceiro(); } private void ovCKB_FreteSemFrete_CheckedChanged(object sender, EventArgs e) { if (ovCKB_FreteSemFrete.Checked) { Transportadora = null; EnderecoTransportadora = null; NFe.IDTransportadora = null; ovTXT_UFTransportadora.Text = string.Empty; ovTXT_Codtransportadora.Text = string.Empty; ovTXT_Transportadora.Text = string.Empty; ovTXT_TransportadoraCNPJCPF.Text = string.Empty; ovTXT_TransportadoraPlaca.Text = string.Empty; ovTXT_TransportadoraVeiculo.Text = string.Empty; ovTXT_TransportadoraANTT.Text = string.Empty; } button1.Enabled = !ovCKB_FreteSemFrete.Checked; ovTXT_TransportadoraPlaca.Enabled = !ovCKB_FreteSemFrete.Checked; ovTXT_TransportadoraVeiculo.Enabled = !ovCKB_FreteSemFrete.Checked; ovTXT_TransportadoraANTT.Enabled = !ovCKB_FreteSemFrete.Checked; } private void GerarDuplicatas(decimal IDMovimentoFiscal, decimal idVenda) { Venda venda = FuncoesVenda.GetVenda(idVenda); TipoDeOperacao tipoDeOperacao = FuncoesTipoDeOperacao.GetTipoDeOperacao(venda.IDTipoDeOperacao); ContaCobranca ContaCob = FuncoesContaCobranca.GetContaCobranca(tipoDeOperacao.IDContaBancaria); if (ContaCob != null & (ContaCob.IDFormaDePagamento == (ovCMB_FormaPagamento.SelectedItem as FormaDePagamento).IDFormaDePagamento)) if (MessageBox.Show(this, "Deseja Gerar e Imprimir as Duplicatas?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) GerarDuplicatasNFe(IDMovimentoFiscal, ContaCob); } private void GerarDuplicatasNFe(decimal IDMovimentoFiscal, ContaCobranca ContaCob) { try { PDVControlador.BeginTransaction(); /* Inicio da geração de duplicatas */ List<ContaReceber> Titulos = FuncoesContaReceber.GetContasReceberPorMovimentoFiscal(IDMovimentoFiscal); List<BoletoBancario> Boletos = BoletoUtil.GerarBoleto(Titulos, ContaCob); byte[] ArrBoletos = BoletoUtil.GeraLayoutPDF(Boletos); SaveFileDialog SaveFile = new SaveFileDialog(); SaveFile.Filter = "PDF|*.pdf"; SaveFile.Title = "Duplicatas"; SaveFile.ShowDialog(this); SaveFile.ShowHelp = false; if (string.IsNullOrEmpty(SaveFile.FileName)) throw new Exception("Nome do arquivo não pode ser vazio."); File.WriteAllBytes(SaveFile.FileName, ArrBoletos); System.Diagnostics.Process.Start(SaveFile.FileName); PDVControlador.Commit(); } catch (Exception Ex) { PDVControlador.Rollback(); MessageBox.Show(this, Ex.Message, NOME_TELA); } } private void simpleButton1_Click(object sender, EventArgs e) { GVEN_ListaDeDAVs gVEN_ListaDeDAVs = new GVEN_ListaDeDAVs(); gVEN_ListaDeDAVs.ShowDialog(); if (gVEN_ListaDeDAVs.Venda != null) CarregarPedido(gVEN_ListaDeDAVs.Venda); PreencherTela(); } public List<DuplicataNFCe> duplicataNFCe; private void simpleButton1_Click_1(object sender, EventArgs e) { try { if (gridViewProdutos.FocusedRowHandle < 0) throw new Exception("Nenhum produto foi selecionado"); var idProdutoNFe = Grids.GetValorDec(gridViewProdutos, "idprodutonfe"); var seletorCFOP = new GVEN_SeletorCFOP(); seletorCFOP.ShowDialog(); var idCfop = UFCliente != null ? ProcessarCFOP(seletorCFOP.IdCFOP) : seletorCFOP.IdCFOP; var rowProduto = PRODUTOS .AsEnumerable() .Where(p => Convert.ToDecimal(p["idprodutonfe"]) == idProdutoNFe) .FirstOrDefault(); rowProduto["IDCFOP"] = rowProduto["CFOP"] = idCfop; } catch (Exception ex) { Alert(ex.Message); } } private void Alert(string message) { MessageBox.Show(message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error); } public void CarregarPedido(Venda venda) { try { TipoDeOperacao tipoDeOperacao = FuncoesTipoDeOperacao.GetTipoDeOperacao(venda.IDTipoDeOperacao); duplicataNFCe = FuncoesItemDuplicataNFCe.GetPagamentosPorVenda(venda.IDVenda); NFe.IDCliente = decimal.Parse(venda.IDCliente.ToString()); NFe.IDFormaDePagamento = venda.IDFormaPagamento; NFe.IDUsuario = venda.IDUsuario; NFe.INDPagamento = duplicataNFCe.Count == 1 ? 0 : 1; //NFe.IDFormaDePagamento = formaDePagamento.IDFormaDePagamento; NFe.IDTipoAtendimento = tipoDeOperacao.IDTipoAtendimento; NFe.IDFinalidade = tipoDeOperacao.IDFinalidade; NFe.FretePor = tipoDeOperacao.TipoDeFrete; NFe.IDCFOP = tipoDeOperacao.IDOperacaoFiscal; NFe.IDTransportadora = tipoDeOperacao.IDTransportadora; NFe.Serie = tipoDeOperacao.Serie; NFe.Modelo = tipoDeOperacao.ModeloDocumento; NFe.InformacoesComplementares = tipoDeOperacao.InformacoesComplementares; ovTXT_Modelo.Text = tipoDeOperacao.ModeloDocumento.ToString(); ovTXT_Serie.Text = tipoDeOperacao.Serie.ToString() ; NFe.IDVenda = venda.IDVenda; } catch (Exception ex) { MessageBox.Show(this, ex.Message, NOME_TELA,MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
/* * Copyright (c) 2019, TopCoder, Inc. All rights reserved. */ using CarInventory.Common; using CarInventory.Data.Entities; using CarInventory.Models; using Microsoft.EntityFrameworkCore; using System.Linq; namespace CarInventory.Data.Repositories.Impl { /// <summary> /// This repository class provides operations for managing Center entities. /// </summary> public class CenterRepository : BaseGenericRepository<RefCenter, CenterSearchCriteria>, ICenterRepository { /// <summary> /// Initializes a new instance of the <see cref="CenterRepository"/> class. /// </summary> /// <param name="dbContext">The database context.</param> public CenterRepository(AppDbContext dbContext) : base(dbContext) { } /// <summary> /// Gets center by specified PGEO. /// </summary> /// <param name="pgeo">The PGEO.</param> /// <returns> /// The Center. /// </returns> public RefCenter Get(string pgeo) { Util.ValidateArgumentNotNull(pgeo, nameof(pgeo)); IQueryable<RefCenter> query = Query(); query = IncludeNavigationProperties(query); RefCenter entity = query.FirstOrDefault(e => e.PGEO == pgeo); Util.CheckFoundEntity(entity, pgeo); PopulateAdditionalFields(entity); return entity; } /// <summary> /// Gets the Center by Id. /// </summary> /// <param name="query">The query.</param> /// <param name="id">The center Id.</param> /// <returns></returns> protected override RefCenter GetById(IQueryable<RefCenter> query, object id) { string pgeo = id.ToString(); return query.FirstOrDefault(x => x.PGEO == pgeo); } /// <summary> /// Applies filters to the given query. /// </summary> /// <param name="query">The query.</param> /// <param name="criteria">The search criteria.</param> /// <returns>The updated query with applied filters.</returns> protected override IQueryable<RefCenter> ConstructQueryConditions( IQueryable<RefCenter> query, CenterSearchCriteria criteria) { if (criteria.RegionId != null) { query = query.Where(x => x.Country.IdGeoPole == criteria.RegionId); } if (criteria.PGEO != null) { query = query.Where(x => x.PGEO == criteria.PGEO); } if (criteria.Status != null) { query = query.Where(x => x.Status == criteria.Status); } if (criteria.ExcludedStatus != null) { query = query.Where(x => x.Status != criteria.ExcludedStatus); } if (criteria.Name != null && criteria.Name.Trim().Length > 0) { string name = criteria.Name.ToLower(); query = query.Where(x => x.Name.ToLower().Contains(name) || x.PGEO.ToLower().Contains(name)); } return query; } /// <summary> /// Applies ordering to the given query. /// </summary> /// <param name="query">The query.</param> /// <param name="criteria">The search criteria.</param> /// <returns> /// The updated query with applied ordering. /// </returns> protected override IQueryable<RefCenter> AddSortingCondition(IQueryable<RefCenter> query, CenterSearchCriteria criteria) { if ("IsAssociated".IsCaseInsensitiveEqual(criteria.SortBy) && criteria.AssociatedCenters != null) { return criteria.SortType == SortType.ASC ? query.OrderBy(x => criteria.AssociatedCenters.Contains(x.PGEO) ? 0 : 1).ThenBy(x => x.PGEO) : query.OrderBy(x => criteria.AssociatedCenters.Contains(x.PGEO) ? 1 : 0).ThenBy(x => x.PGEO); } return base.AddSortingCondition(query, criteria); } /// <summary> /// Includes the navigation properties loading for the entity. /// </summary> /// <param name="query">The query.</param> /// <returns>The updated query.</returns> protected override IQueryable<RefCenter> IncludeNavigationProperties(IQueryable<RefCenter> query) { return query .Include(x => x.Country); } /// <summary> /// Includes the navigation properties loading for the entity during Search operation. /// </summary> /// <param name="query">The query.</param> /// <returns> /// The updated query. /// </returns> protected override IQueryable<RefCenter> IncludeSearchItemNavigationProperties(IQueryable<RefCenter> query) { return query .Include(x => x.Country); } /// <summary> /// Updates the child entities by loading them from the database context. /// </summary> /// /// <remarks> /// All thrown exceptions will be propagated to caller method. /// </remarks> /// /// <param name="entity">The entity to resolve.</param> protected override void ResolveChildEntities(RefCenter entity) { entity.Country = ResolveChildEntity(entity.Country, entity.IdCountry); } /// <summary> /// Updates the <paramref name="existing"/> entity according to <paramref name="newEntity"/> entity. /// </summary> /// <remarks>Override in child services to update navigation properties.</remarks> /// <param name="existing">The existing entity.</param> /// <param name="newEntity">The new entity.</param> protected override void UpdateEntityFields(RefCenter existing, RefCenter newEntity) { existing.Country = newEntity.Country; base.UpdateEntityFields(existing, newEntity); } /// <summary> /// Deletes the associated entities from the database context. /// </summary> /// /// <remarks> /// All thrown exceptions will be propagated to caller method. /// </remarks> /// /// <param name="entity">The entity to delete associated entities for.</param> protected override void DeleteAssociatedEntities(RefCenter entity) { } } }
using DevExpress.XtraEditors; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using DAL; using BUS; using System.Data.Sql; using ControlLocalizer; using System.Xml; namespace GUI { public partial class f_connectDB : XtraForm { KetNoiDBDataContext db = new KetNoiDBDataContext(); public f_connectDB() { InitializeComponent(); } public bool KiemTraKetNoi() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("appconn.xml");//mở file.xml lên var s = xmlDoc.DocumentElement["conn"].InnerText; if (s == string.Empty) return false; // giải mã var conn = md5.Decrypt(s); var b = new SqlConnectionStringBuilder(); b.ConnectionString = conn; Biencucbo.DbName = b.InitialCatalog; Biencucbo.ServerName = b.DataSource; var sqlCon = new SqlConnection(conn); // gán cho DAL tren bo nhớ DAL.Settings.Default.ConnectionString = conn; try { sqlCon.Open(); db = new KetNoiDBDataContext(sqlCon); return true; } catch (Exception ex) { } return false; } private void btnOK_Click(object sender, EventArgs e) { if (txtDbName.Text == "") { XtraMessageBox.Show("Database name is not be empty", "Warning"); return; } var thatluangplazaConnectionString_new = ""; thatluangplazaConnectionString_new = "Data Source = " + txtServer.Text + "; Initial Catalog = " + txtDbName.Text + "; Persist Security Info = True; User ID = " + txtTen.Text + "; Password = " + txtPass.Text + ""; var sqlCon = new SqlConnection(thatluangplazaConnectionString_new); try { sqlCon.Open(); db = new KetNoiDBDataContext(sqlCon); XtraMessageBox.Show("Connection succeeded"); Biencucbo.DbName = txtDbName.Text; Biencucbo.ServerName = txtServer.Text; thoat_luon = true; // luu connstring mã hóa vào setting XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("appconn.xml");//mở file.xml lên xmlDoc.DocumentElement["conn"].InnerText = md5.Encrypt(thatluangplazaConnectionString_new); xmlDoc.Save("appconn.xml"); DAL.Settings.Default.ConnectionString = thatluangplazaConnectionString_new; //Settings.Default.Save(); DialogResult = DialogResult.OK; } catch { XtraMessageBox.Show("Connection failed, please check again or contact Admin"); sqlCon.Close(); } } private void f_connectDB_Load(object sender, EventArgs e) { LanguageHelper.Translate(this); this.Text = LanguageHelper.TranslateMsgString("." + Name + "_title", "CẬP NHẬT KẾT NỐI CƠ SỞ DỮ LIỆU").ToString(); changeFont.Translate(this); txtDbName.Text = Biencucbo.DbName; if (Biencucbo.ServerName == "192.168.0.9") { rlan.Checked = true; } else if(Biencucbo.ServerName == "192.168.2.10") { rlan2.Checked = true; } else { rnet.Checked = true; } } private void btnExit_Click(object sender, EventArgs e) { Close(); } bool thoat_luon = false; private void rlan_CheckedChanged(object sender, EventArgs e) { txtTen.ReadOnly = true; txtServer.Enabled = false; txtPass.ReadOnly = true; if (rlan.Checked == true) { rnet.Checked = false; rlan2.Checked = false; txtServer.Text = "192.168.0.9,1433"; txtDbName.Text = "TLS_2017"; txtTen.Text = "sa"; txtPass.Text = "2267562676a@#$%"; } } private void rnet_CheckedChanged(object sender, EventArgs e) { txtTen.ReadOnly = true; txtServer.Enabled = false; txtPass.ReadOnly = true; if (rnet.Checked == true) { rlan.Checked = false; rlan2.Checked = false; //txtServer.Text = "183.182.109.4,1433"; txtServer.Text = "183.182.109.4,1433"; txtDbName.Text = "TLS_2017"; txtTen.Text = "sa"; txtPass.Text = "2267562676a@#$%"; } } //hàm mã hoá public static string EncryptString(string Message, string Passphrase) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); System.Security.Cryptography.MD5CryptoServiceProvider HashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); System.Security.Cryptography.TripleDESCryptoServiceProvider TDESAlgorithm = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = System.Security.Cryptography.CipherMode.ECB; TDESAlgorithm.Padding = System.Security.Cryptography.PaddingMode.PKCS7; byte[] DataToEncrypt = UTF8.GetBytes(Message); try { System.Security.Cryptography.ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor(); Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length); } finally { TDESAlgorithm.Clear(); HashProvider.Clear(); } return Convert.ToBase64String(Results); } //hàm giải mã public static string DecryptString(string Message, string Passphrase) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); System.Security.Cryptography.MD5CryptoServiceProvider HashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); System.Security.Cryptography.TripleDESCryptoServiceProvider TDESAlgorithm = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = System.Security.Cryptography.CipherMode.ECB; TDESAlgorithm.Padding = System.Security.Cryptography.PaddingMode.PKCS7; try { byte[] DataToDecrypt = Convert.FromBase64String(Message); System.Security.Cryptography.ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } catch { return string.Empty; } finally { TDESAlgorithm.Clear(); HashProvider.Clear(); } return UTF8.GetString(Results); } private void rlan2_CheckedChanged(object sender, EventArgs e) { txtTen.ReadOnly = true; txtServer.Enabled = false; txtPass.ReadOnly = true; if (rlan2.Checked == true) { rnet.Checked = false; rlan.Checked = false; txtServer.Text = "192.168.2.10,1433"; txtDbName.Text = "TLS_2017"; txtTen.Text = "sa"; txtPass.Text = "2267562676a@#$%"; } } private void btntest_Click(object sender, EventArgs e) { if (txtDbName.Text == "") { XtraMessageBox.Show("Database name is not be empty", "Warning"); return; } var thatluangplazaConnectionString_new = ""; thatluangplazaConnectionString_new = "Data Source = " + txtServer.Text + "; Initial Catalog = " + txtDbName.Text + "; Persist Security Info = True; User ID = " + txtTen.Text + "; Password = " + txtPass.Text + ""; var sqlCon = new SqlConnection(thatluangplazaConnectionString_new); try { sqlCon.Open(); //db = new KetNoiDBDataContext(sqlCon); XtraMessageBox.Show("Connection succeeded"); //Settings.Default.Save(); } catch { XtraMessageBox.Show("Connection failed, please check again or contact Admin"); sqlCon.Close(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace LateOS.Models { [MetadataType(typeof(cListadoPrecio))] public partial class tbListadoPrecio { } public class cListadoPrecio { [Display(Name = "ID Listado Precio")] public int lip_Id { get; set; } [Display(Name = "Descripción")] [Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} es requerido.")] [MaxLength(100, ErrorMessage = "Excedió el máximo de caracteres permitidos.")] public string lip_Descripcion { get; set; } [Display(Name = "Prioridad")] [Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} es requerido.")] public int lip_Prioridad { get; set; } [Display(Name = "Activo")] public bool lip_EsActivo { get; set; } [Display(Name = "Fecha de Inicio")] [Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} de requerido.")] public System.DateTime lip_FechaInicio { get; set; } [Display(Name = "Fecha de Finalización")] [Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} de requerido.")] public System.DateTime lip_FechaFin { get; set; } [Display(Name = "Creado por")] public int lip_UsuarioCrea { get; set; } [Display(Name = "Fecha de Creación")] public System.DateTime lip_FechaCrea { get; set; } [Display(Name = "Modificado por")] public Nullable<int> lip_UsuarioModifica { get; set; } [Display(Name = "Fecha de Modificación")] public Nullable<System.DateTime> lip_FechaModifica { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.ContactsNs.ContactsMenu { /** * @since 13.0.0 */ public interface IContactsStore { /** * @param IUser user * @param filter * @return IEntry[] * @since 13.0.0 */ IList<IEntry> getContacts(IUser user, string filter); /** * @brief finds a contact by specifying the property to search on (shareType) and the value (shareWith) * @param IUser user * @param integer shareType * @param string shareWith * @return IEntry|null * @since 13.0.0 */ IEntry findOne(IUser user, int shareType, string shareWith); } }
using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using StudyEspanol.Data; using StudyEspanol.Data.Managers; using StudyEspanol.Data.Models; using StudyEspanol.Droid; namespace StudyEspanol.UI.Screens { [Activity(WindowSoftInputMode = SoftInput.StateAlwaysHidden|SoftInput.AdjustPan)] public partial class VocabQuizScreen : Screen { #region Const Fields private const string QUIZ_WORDS = "quiz_words"; #endregion #region Fields private GridView wordList; private VocabQuizAdapter quizAdapter; private ProgressBar progressBar; private TextView textView; #endregion #region Initialization protected override void OnCreate(Bundle bundle) { //Android Initialization Methods base.OnCreate(bundle); SetContentView(Resource.Layout.screen_vocab_quiz); SetTitle(Resource.String.vocab_quiz); //Study Espanol Initialization Methods if (bundle == null) { Initialization(); } if (Intent.Extras != null) { translationDirection = (TranslateDirection)Intent.Extras.GetInt(SearchScreen.TRANSLATE); Query query = (Query)Intent.Extras.GetParcelable(SearchScreen.QUERY); int maxWords = Intent.Extras.GetInt(SearchScreen.MAX_NUMBER); WordsManager.Instance.SearchFinished += (sender, e) => { progressBar.Visibility = ViewStates.Gone; if (WordsManager.Instance.Objects.Count > 0) { QuizManager.Instance.AddQuizWords(WordsManager.Instance.WordsToQuizWords(translationDirection)); quizAdapter = new VocabQuizAdapter(this, Resource.Layout.cell_vocab_quiz, QuizManager.Instance.Objects); wordList.Adapter = quizAdapter; wordList.ItemClick += ListItemClicked; wordList.Visibility = ViewStates.Visible; } else { textView.Visibility = ViewStates.Visible; } }; WordsManager.Instance.Search(query, maxWords); } progressBar = FindViewById<ProgressBar>(Resource.Id.progress_bar); textView = FindViewById<TextView>(Resource.Id.empty_textview); textView.Visibility = ViewStates.Gone; wordList = FindViewById<GridView>(Resource.Id.list_quiz); wordList.Visibility = ViewStates.Gone; } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.menu_vocab_quiz, menu); return true; } #endregion #region Interactive Methods public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.action_finish: QuizManager.Instance.GradeQuiz(); Intent intent = new Intent(this, typeof(QuizCompleteScreen)); StartActivity(intent); break; default: base.OnOptionsItemSelected(item); break; } return true; } private void ListItemClicked(object sender, AdapterView.ItemClickEventArgs e) { } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace StepTracker { public class InfoCard : INotifyPropertyChanged { public int day; public int rank; public string user; public string status; public int steps; public int Day { get { return day; } set { day = value; OnPropertyChanged("Day"); } } public int Rank { get { return rank; } set { rank = value; OnPropertyChanged("Rank"); } } public string User { get { return user; } set { user = value; OnPropertyChanged("User"); } } public string Status { get { return status; } set { status = value; OnPropertyChanged("Status"); } } public int Steps { get { return steps; } set { steps = value; OnPropertyChanged("Status"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public partial class BiomesViewModel { //public Biome[] biomes; ////public class Biome }
using UnityEngine; using System.Collections; public class AugmentedRealityGyroPanel : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { AugmentedRealityGyro.getInstance ().stepGyro (); } }
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models; using Microsoft.Azure.CognitiveServices.Vision.Face; using Microsoft.Azure.CognitiveServices.Vision.Face.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace Ocularis.Capabilities.Remote.Face { class FaceAnalyzer { private static readonly FaceAttributeType[] _faceAttributes = { FaceAttributeType.Age, FaceAttributeType.Gender, FaceAttributeType.Smile, FaceAttributeType.Emotion }; private string _subscriptionKey; private string _endPoint; public FaceAnalyzer(string subscriptionKey, string endPoint) { _subscriptionKey = subscriptionKey; _endPoint = endPoint; } public async Task FindFaces(StorageFile imageFile) { using (var faceClient = new FaceClient(new ApiKeyServiceClientCredentials(_subscriptionKey), new System.Net.Http.DelegatingHandler[] { })) { faceClient.Endpoint = _endPoint; await DetectLocalAsync(faceClient, imageFile); } } // Detect faces in a local image private static async Task DetectLocalAsync(FaceClient faceClient, StorageFile imageFile) { try { using (var imageStream = await imageFile.OpenStreamForReadAsync()) { var faceList = await faceClient.Face.DetectWithStreamAsync(imageStream, true, false, _faceAttributes); GetFaceAttributes(faceList); } } catch (APIErrorException e) { } } private static string GetFaceAttributes(IList<DetectedFace> faceList) { string attributes = string.Empty; foreach (DetectedFace face in faceList) { double? age = face.FaceAttributes.Age; string gender = face.FaceAttributes.Gender.ToString(); attributes += gender + " " + age + " "; } return attributes; } } }
using System; namespace Trial1 { class Program { static void Main(string[] args) { //unsigned is always positive //byte x =1; // 0 to 255 (8 byte) // sbyte y =100; // -128 to 127 (8byte) signed byte so divide by 2 //short a = 65335; //(16 byte) is signed data type, (2^16)/2= -32768 to 32767 //ushort b = 65535;//unsigned short // Console.WriteLine("x is " + x); //Console.WriteLine("y is "+ y); // uint x= 4294967295 ; // it is 0 to 2^32 - 1 // Console.WriteLine(x); // int y = 2147483647; // -2^31 to 2^31 - 1 // Console.WriteLine(y); //To convert to byte or anythng use, //convert.byte() but it should be within the range. //float32bits= 4 bytes = 6-9 digits //double 15-17 //decimal 16 bytes = 16*8= 28-29 digits precision float num = 1.5f; // rounds up if its more than 6-9 digits if ita decimal //or else rounds down if its whole number //float use f after decimal //decimale use m after decimal Console.WriteLine(num); //float to int doesnt work // float to double works but douvke adds extra numbers // float to decimal doesnt //concatnating - ading += to string string apple = "hi"; apple += " to"; Console.WriteLine(apple); } } }
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace WebApplicationBasic.Models.Entities { public class ApplicationRole : IdentityRole<Guid> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; using Entidades; namespace Datos { public class Detalle { public void InsertarDetalle(Entidades.Detalle detalle) { Conectividad aux = new Conectividad(); SqlCommand cmd = new SqlCommand(); cmd.Connection = aux.conectar(); SqlParameter parametroNombre = new SqlParameter(); parametroNombre.ParameterName = "@idDetalle"; parametroNombre.Value = detalle.IdDetalle; cmd.Parameters.Add(parametroNombre); cmd.Parameters.Add(new SqlParameter("@precioUnitario", detalle.PrecioUnitario)); cmd.Parameters.Add(new SqlParameter("@subtotal", detalle.Subtotal)); cmd.Parameters.Add(new SqlParameter("@cantidad", detalle.Cantidad)); cmd.Parameters.Add(new SqlParameter("@factura", detalle.IdFactura)); //cmd.Parameters.Add(new SqlParameter("@fechaUsuario", cliente.FechaCliente)); cmd.CommandText = "spr_InsertarDetalle"; cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); aux.conectar(); } //public void BuscarCliente(Entidades.Cliente clienteList) //{ // throw new NotImplementedException(); //} //public IList<Entidades.Cliente> BuscarCliente() //{ // Conectividad aux = new Conectividad(); // SqlCommand cmd = new SqlCommand(); // { // cmd.Connection = aux.conectar(); // cmd.CommandText = "spr_BuscarCliente"; // cmd.CommandType = CommandType.StoredProcedure; // }; // SqlDataReader sqlDataReader = cmd.ExecuteReader(); // IList<Entidades.Cliente> clienteList = new List<Entidades.Cliente>(); // Entidades.Cliente cliente; // while (sqlDataReader.Read()) // { // cliente = new Entidades.Cliente // { // Documento = sqlDataReader["Documento"].ToString().Trim(), // Ciudad = sqlDataReader["Ciudad"].ToString().Trim(), // Nombre = sqlDataReader["Nombre"].ToString().Trim(), // Correo = sqlDataReader["Correo"].ToString().Trim(), // Apellido = sqlDataReader["Apellido"].ToString().Trim(), // Activo = bool.Parse(sqlDataReader["activo"].ToString()) // //SegundoApellido = sqlDataReader[COLUMN_SEGUNDO_APELLIDO].ToString(), // //FechaNacimiento = new DateTime(), // //Direccion = sqlDataReader[COLUMN_TELEFONO].ToString(), // //Telefono = sqlDataReader[COLUMN_DIRECCION].ToString() // }; // clienteList.Add(cliente); // } // aux.conectar(); // return clienteList; //} public void EliminarDetalle(Entidades.Detalle detalle) { Conectividad aux = new Conectividad(); SqlCommand cmd = new SqlCommand(); { cmd.Connection = aux.conectar(); cmd.Parameters.Add(new SqlParameter("@idDetalle", detalle.IdDetalle)); cmd.CommandText = "spr_EliminarDetalle"; cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); }; cmd.Connection = aux.conectar(); //< a href = "javascript:__doPostBack('GridView','Delete$0')" > Delete </ a > } //public void ActualizarDetalle(Entidades.Detalle detalle) //{ // Conectividad aux = new Conectividad(); // SqlCommand cmd = new SqlCommand(); // cmd.Connection = aux.conectar(); // SqlParameter parametroNombre = new SqlParameter(); // parametroNombre.ParameterName = "@nombreUsuario"; // parametroNombre.Value = cliente.NombreCliente; // cmd.Parameters.Add(parametroNombre); // cmd.Parameters.Add(new SqlParameter("@Apellido", cliente.Apellido)); // cmd.Parameters.Add(new SqlParameter("@Ciudad", cliente.Ciudad)); // cmd.Parameters.Add(new SqlParameter("@Correo", cliente.Correo)); // cmd.Parameters.Add(new SqlParameter("@usuario", cliente.Usuario)); // cmd.Parameters.Add(new SqlParameter("@idUsuario", cliente.IdCliente)); // cmd.Parameters.Add(new SqlParameter("@contrasena", cliente.Contrasena)); // cmd.Parameters.Add(new SqlParameter("@direccion", cliente.Direccion)); // cmd.Parameters.Add(new SqlParameter("@activoUsuario", cliente.ActivoCliente)); // cmd.Parameters.Add(new SqlParameter("@telefono", cliente.Telefono)); // cmd.Parameters.Add(new SqlParameter("@fechaUsuario", cliente.FechaCliente)); // cmd.CommandText = "spr_ActualizarCliente"; // cmd.CommandType = CommandType.StoredProcedure; // cmd.ExecuteNonQuery(); // aux.conectar(); //} } } // public Entidades.Cliente BuscarIdCliente(string Documento) // { // Conectividad aux = new Conectividad(); // SqlCommand cmd = new SqlCommand(); // { // cmd.Connection = aux.conectar(); // cmd.CommandText = "spr_BuscarIdCliente"; // cmd.CommandType = CommandType.StoredProcedure; // }; // cmd.Parameters.Add(new SqlParameter("@Documento", Documento)); // SqlDataReader sqlDataReader = cmd.ExecuteReader(); // sqlDataReader.Read(); // Entidades.Cliente cliente = new Entidades.Cliente // { // Documento = sqlDataReader["Documento"].ToString().Trim(), // Ciudad = sqlDataReader["Ciudad"].ToString().Trim(), // Nombre = sqlDataReader["Nombre"].ToString().Trim(), // Correo = sqlDataReader["Correo"].ToString().Trim(), // Apellido = sqlDataReader["Apellido"].ToString().Trim(), // Activo = bool.Parse(sqlDataReader["activo"].ToString()) // //SegundoApellido = sqlDataReader[COLUMN_SEGUNDO_APELLIDO].ToString(), // //FechaNacimiento = new DateTime(), // //Direccion = sqlDataReader[COLUMN_TELEFONO].ToString(), // //Telefono = sqlDataReader[COLUMN_DIRECCION].ToString() // }; // sqlDataReader.Close(); // aux.conectar(); // return cliente; // } // } //}
// ----------------------------------------------------------------------- // <copyright file="HashFunctionBenchmarks.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root // for license information. // </copyright> // ----------------------------------------------------------------------- using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using Mlos.Core.Collections; [SimpleJob(RuntimeMoniker.NetCoreApp31)] [PlainExporter] [HtmlExporter] [MarkdownExporter] [MemoryDiagnoser] public class HashFunctionBenchmarks { public static string SequenceString; [Params(20000000)] public int N; [GlobalSetup] public void Setup() { SequenceString = string.Join('-', Enumerable.Range(1, 1024 * 1024)); } [Benchmark] public ulong NVMULongHashInt() { ulong sum = 0; for (int i = 0; i < N; i++) { sum += default(FNVHash<ulong>).GetHashValue(i); } return sum; } [Benchmark(Baseline =true)] public ulong NVMULongHashSpecializedInt() { ulong sum = 0; for (int i = 0; i < N; i++) { sum += FNVHash<ulong>.GetHashValueULong(i); } return sum; } [Benchmark] public ulong NVMIntHashGenericInt() { uint sum = 0; for (int i = 0; i < N; i++) { sum += default(FNVHash<uint>).GetHashValue(i); } return sum; } [Benchmark] public ulong NVMStringHash() { ulong sum = 0; sum += default(FNVHash<ulong>).GetHashValue(SequenceString); return sum; } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FileUploadNetCore.Models { public class FileOnDatabaseModel : FileModel { public byte[] Data { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace NorthCoast { public partial class AccommodationEdit : Form { //Delcare Variables SqlDataAdapter daAccommodationType, daAccommodation; DataSet dsNorthCoast = new DataSet(); SqlCommandBuilder cmdBAccommodationType, cmdBAccommodation; DataRow drAccommodation; String cnstr, sqlAccommodationType, sqlAccommodation, sqlDataGrid, originalKey; public AccommodationEdit() { InitializeComponent(); } #region MenuStripEvents //Menu Strip events for all pages private void mainMenuToolStripMenuItem1_Click(object sender, EventArgs e) { Form frMainMenu = new MainMenu(); frMainMenu.Show(); this.Hide(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { Application.Exit(); } private void addCustomerToolStripMenuItem_Click(object sender, EventArgs e) { Form frmCustomerAdd = new CustomerAdd(); frmCustomerAdd.Show(); this.Hide(); } private void deleteCustomerToolStripMenuItem_Click(object sender, EventArgs e) { Form frmCustomerDelete = new CustomerDelete(); frmCustomerDelete.Show(); this.Hide(); } private void updateCustomerToolStripMenuItem_Click(object sender, EventArgs e) { Form frmCustomerUpdate = new CustomerUpdate(); frmCustomerUpdate.Show(); this.Hide(); } private void addBookingToolStripMenuItem_Click(object sender, EventArgs e) { Form frmBookingAdd = new BookingAdd(); frmBookingAdd.Show(); this.Hide(); } private void editBookingsToolStripMenuItem_Click(object sender, EventArgs e) { Form frmBookingEdit = new BookingEdit(); frmBookingEdit.Show(); this.Hide(); } private void addAccommodationToolStripMenuItem_Click(object sender, EventArgs e) { Form frmAccommodationAdd = new AccommodationAdd(); frmAccommodationAdd.Show(); this.Hide(); } private void editAccommodationsToolStripMenuItem_Click(object sender, EventArgs e) { Form frmAccommodationEdit = new AccommodationEdit(); frmAccommodationEdit.Show(); this.Hide(); } private void addLocationToolStripMenuItem_Click(object sender, EventArgs e) { Form frmLocationAdd = new LocationAdd(); frmLocationAdd.Show(); this.Hide(); } private void editLocationsToolStripMenuItem_Click(object sender, EventArgs e) { Form frmLocationEdit = new LocationEdit(); frmLocationEdit.Show(); this.Hide(); } private void addTypeToolStripMenuItem_Click(object sender, EventArgs e) { Form frmAccommodationTypeAdd = new AccommodationTypeAdd(); frmAccommodationTypeAdd.Show(); this.Hide(); } private void editTypesToolStripMenuItem_Click(object sender, EventArgs e) { Form frmAccommodationTypeEdit = new AccommodationTypeEdit(); frmAccommodationTypeEdit.Show(); this.Hide(); } private void reportToolStripMenuItem_Click(object sender, EventArgs e) { Form frmReport = new Report(); frmReport.Show(); this.Hide(); } private void helpToolStripMenuItem_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(@"K:\A2\NorthCoast\NorthCoast\Resources\UserManual.pdf"); } #endregion private void AccommodationDelete_Load(object sender, EventArgs e) { SetupDataset(); } private void SetupDataset() { // connect to database and create dataset and table to hold customer details // Use Properties to hold value for maintenance cnstr = Properties.Resources.connectStr; //Select all from the table Accomodation sqlAccommodation = @"select * from Accommodation"; daAccommodation = new SqlDataAdapter(sqlAccommodation, cnstr); cmdBAccommodation = new SqlCommandBuilder(daAccommodation); daAccommodation.FillSchema(dsNorthCoast, SchemaType.Source, "Accommodation"); daAccommodation.Fill(dsNorthCoast, "Accommodation"); //Select all Accommodation Type's from table AccommodationType and add them to a combobox SqlConnection conn = new SqlConnection(cnstr); SqlDataAdapter ada = new SqlDataAdapter("select Accommodation_Type from AccommodationType", conn); DataTable dt = new DataTable(); ada.Fill(dt); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; cbbAccommodationType.Items.Add(dr["Accommodation_Type"].ToString()); } //Select all from the table AccommodationType sqlAccommodationType = @"select * from AccommodationType"; daAccommodationType = new SqlDataAdapter(sqlAccommodationType, cnstr); cmdBAccommodationType = new SqlCommandBuilder(daAccommodationType); daAccommodationType.FillSchema(dsNorthCoast, SchemaType.Source, "AccommodationType"); daAccommodationType.Fill(dsNorthCoast, "AccommodationType"); FillDataGrid("SELECT * from Accommodation"); //AutoSize all columns dgvAccommodation.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; dgvAccommodation.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; dgvAccommodation.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; dgvAccommodation.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } private void FillDataGrid(String sqlStatement) { //Selecting and outputting selected Accommodation Types to user SqlConnection sqlConnection = new SqlConnection(cnstr); SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlStatement, sqlConnection); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); DataSet ds = new DataSet(); dataAdapter.Fill(ds); dgvAccommodation.ReadOnly = true; dgvAccommodation.DataSource = ds.Tables[0]; } private string SearchDataGridStatement(String column, String search) { //Selecting sql to display in the datagrid sqlDataGrid = @"SELECT * from Accommodation WHERE " + column + " LIKE'%" + search + "%'"; return sqlDataGrid; } private void dgvAccommodation_CellClick(object sender, DataGridViewCellEventArgs e) { try { if (e.RowIndex >= 0) { DataGridViewRow row = this.dgvAccommodation.Rows[e.RowIndex]; txtAccommodationID.Text = row.Cells["AccommodationID"].Value.ToString(); originalKey = row.Cells["AccommodationID"].Value.ToString(); cbbAccommodationType.SelectedItem = row.Cells["Accommodation_Type"].Value.ToString(); cbxNeedsServiced.Checked = Convert.ToBoolean(row.Cells["Needs_Serviced"].Value.ToString()); txtNotes.Text = row.Cells["Notes"].Value.ToString(); pnlButtons.Enabled = true; } } catch { MessageBox.Show("Please Select an Accommodation Type"); } } private void btnDelete_Click(object sender, EventArgs e) { try { drAccommodation = dsNorthCoast.Tables["Accommodation"].Rows.Find(originalKey); drAccommodation.Delete(); daAccommodation.Update(dsNorthCoast, "Accommodation"); MessageBox.Show("Accommodation Deleted"); FillDataGrid("SELECT * from Accommodation"); pnlAccommodaitonEdit.Enabled = false; pnlButtons.Enabled = false; } catch (SqlException) { MessageBox.Show("This accommodation is on a location currently, please update location accommodation to 0000 before trying to delete this accommodation."); SetupDataset(); } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void btnUpdate_Click(object sender, EventArgs e) { btnDelete.Visible = false; btnUpdate.Visible = false; btnBack.Visible = true; btnConfirm.Visible = true; dgvAccommodation.Enabled = false; pnlAccommodaitonEdit.Enabled = true; } private void btnBack_Click(object sender, EventArgs e) { btnDelete.Visible = true; btnUpdate.Visible = true; btnBack.Visible = false; btnConfirm.Visible = false; dgvAccommodation.Enabled = true; pnlAccommodaitonEdit.Enabled = false; } private void btnConfirm_Click(object sender, EventArgs e) { // simple add using validation method checking existence and min/max length // of a string ( used for surname, forename and street) // sets error provider against invalid field //Create varbles and errP message icon for validation errP.Clear(); Boolean ok = true; try { if (!txtAccommodationID.MaskCompleted) { throw new CustomerException("Please enter a valid Accommodation ID e.g. CL08"); } } catch (CustomerException ex) { ok = false; errP.SetError(txtAccommodationID, ex.Message); } try { if (String.IsNullOrEmpty(cbbAccommodationType.Text.Trim())) { throw new CustomerException("This is a required field - Select an Accommodation Type"); } } catch (CustomerException ex) { ok = false; errP.SetError(cbbAccommodationType, ex.Message); } if (ok) { try { drAccommodation = dsNorthCoast.Tables["Accommodation"].Rows.Find(originalKey); drAccommodation.BeginEdit(); drAccommodation["AccommodationID"] = txtAccommodationID.Text.Trim(); drAccommodation["Accommodation_Type"] = cbbAccommodationType.SelectedItem.ToString().Trim(); drAccommodation["Needs_Serviced"] = cbxNeedsServiced.CheckState == CheckState.Checked ? 1 : 0; drAccommodation["Notes"] = txtNotes.Text.Trim(); drAccommodation.EndEdit(); SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAccommodation); daAccommodation.Update(dsNorthCoast, "Accommodation"); MessageBox.Show("Accommodation Updated"); FillDataGrid("SELECT * from Accommodation"); btnDelete.Visible = true; btnUpdate.Visible = true; btnBack.Visible = false; btnConfirm.Visible = false; dgvAccommodation.Enabled = true; pnlAccommodaitonEdit.Enabled = false; pnlButtons.Enabled = false; } catch (SqlException sqlEx) { MessageBox.Show(sqlEx.Message); } } } private void btnSearch_Click(object sender, EventArgs e) { switch (cbxSearch.SelectedItem.ToString()) { case "Accommodation ID": //Search the rows in the column Accommodation_Type FillDataGrid(SearchDataGridStatement("AccommodationID", txtSearch.Text)); break; case "Accommodation Type": //Search the rows in the column Accommodation_Desc FillDataGrid(SearchDataGridStatement("Accommodation_Type", txtSearch.Text)); break; case "Needs Serviced": //Search the rows in the column Accommodation_Size FillDataGrid(SearchDataGridStatement("Needs_Serviced", txtSearch.Text)); break; case "Notes": //Search the rows in the column Charge_Per_Day FillDataGrid(SearchDataGridStatement("Notes", txtSearch.Text)); break; default: //Show all rows in the datagrid FillDataGrid(@"SELECT * from Accommodation"); break; } } private void btnAll_Click(object sender, EventArgs e) { FillDataGrid(@"SELECT * from Accommodation"); } } }
using System; using System.Collections.Generic; //using System.Linq; //using System.Threading.Tasks; using System.Windows.Forms; namespace DUTools { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new LuaEditForm()); //frmLuaEditForm luaForm = new frmLuaEditForm(); // luaForm.Show(); // Application.Run(new frmLuaEmulator()); Application.Run(new frmLauncher()); } } }
using Microsoft.EntityFrameworkCore; using ServiceHost.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ServiceHost.Repository { public class EventlogRepository : BaseRepository<Eventlog>, IEventlogRepsoitory { public EventlogRepository(ServiceHostContext context) : base(context) { } public async Task<IEnumerable<Eventlog>> GetEventlogsAsync() { var events = await Task.Run(() => context.Eventlog.Include(x => x.Person).Include(x => x.Action).OrderByDescending(x => x.Date)); return events; } } }
using System.Collections; using DG.Tweening; using Game.Graphics.UI.Menu.Animations; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using Animation = Game.Graphics.UI.Menu.Animations.Animation; namespace Game.Graphics.UI.Buttons.Custom { public class DelayedButton : Button { [SerializeField] private UnityEngine.UI.Text _text; public void Init(float delay, Animation anim, params UnityAction[] actions) { foreach (var action in actions) { onClick.AddListener(() => StartCoroutine(Delayer(delay, anim))); onClick.AddListener(action); } } private IEnumerator Delayer(float time, Animation anim) { var timer = 0f; interactable = false; var textColor = _text.color; anim.Play(0.2f, 6f, AnimationType.Rotating, Ease.Linear); DOTween.To(() => textColor.a, x => textColor.a = x, 0f, 0.5f).SetDelay(time); while (timer < time) { timer += time; yield return new WaitForSeconds(time); } anim.Stop(); DOTween.To(() => textColor.a, x => textColor.a = x, 0f, 0.5f).SetDelay(time); interactable = true; } } }
using WebApplication.Data.Context; using WebApplication.Data.DataModels.Laptops; using WebApplication.Data.Repositories.BaseRepository; namespace WebApplication.Data.Repositories.Laptops { public class BrandRepository : BaseRepository<Brand>, IBrandRepository { public BrandRepository(ApplicationDbContext context) : base(context) { } } }
using FiveOhFirstDataCore.Core.Account; using FiveOhFirstDataCore.Core.Data.Roster; using FiveOhFirstDataCore.Core.Database; using FiveOhFirstDataCore.Core.Extensions; using FiveOhFirstDataCore.Core.Structures; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace FiveOhFirstDataCore.Core.Services { public partial class RosterService : IRosterService { private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory; private readonly UserManager<Trooper> _userManager; private readonly IDiscordService _discord; private readonly ILogger _logger; public RosterService(IDbContextFactory<ApplicationDbContext> dbContextFactory, UserManager<Trooper> userManager, IDiscordService discord, ILogger<RosterService> logger, IServiceProvider provider) { this._dbContextFactory = dbContextFactory; this._userManager = userManager; this._discord = discord; this._logger = logger; } public async Task<List<Trooper>> GetActiveReservesAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); return await _dbContext.Users.AsNoTracking() .Where(x => x.Slot >= Data.Slot.ZetaCompany && x.Slot < Data.Slot.InactiveReserve) .ToListAsync(); } public async Task<List<Trooper>> GetArchivedTroopersAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); return await _dbContext.Users.AsNoTracking() .Where(x => x.Slot == Data.Slot.Archived) .ToListAsync(); } public async Task<List<Trooper>> GetAllTroopersAsync(bool includeAdmin = false) { using var _dbContext = _dbContextFactory.CreateDbContext(); if (includeAdmin) return await _dbContext.Users.AsNoTracking().ToListAsync(); else return await _dbContext.Users.AsNoTracking() .Where(x => x.Id != -1).ToListAsync(); } public async Task<List<Trooper>> GetFullRosterAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); return await _dbContext.Users.AsNoTracking() .Where(x => x.Slot < Data.Slot.Archived).ToListAsync(); } public async Task<List<Trooper>> GetInactiveReservesAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); return await _dbContext.Users.AsNoTracking() .Where(x => x.Slot >= Data.Slot.InactiveReserve && x.Slot < Data.Slot.Archived) .ToListAsync(); } public async Task<(HashSet<int>, HashSet<string>)> GetInUseUserDataAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); HashSet<int> ids = new(); HashSet<string> nicknames = new(); await _dbContext.Users.AsNoTracking().ForEachAsync(x => { ids.Add(x.Id); if (x.Slot < Data.Slot.InactiveReserve) nicknames.Add(x.NickName); }); return (ids, nicknames); } public async Task<OrbatData> GetOrbatDataAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); OrbatData data = new(); await _dbContext.Users.AsNoTracking() .Where(x => x.Slot < Data.Slot.ZetaCompany) .ForEachAsync(x => data.Assign(x)); return data; } public async Task<List<Trooper>> GetPlacedRosterAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); return await _dbContext.Users.AsNoTracking() .Where(x => x.Slot < Data.Slot.ZetaCompany) .ToListAsync(); } public async Task<Trooper?> GetTrooperFromIdAsync(int id) { using var _dbContext = _dbContextFactory.CreateDbContext(); var trooper = await _dbContext.FindAsync<Trooper>(id); return trooper; } public async Task<Trooper?> GetTrooperFromClaimsPrincipalAsync(ClaimsPrincipal claims) { _ = int.TryParse(_userManager.GetUserId(claims), out int id); return await GetTrooperFromIdAsync(id); } public async Task<List<Trooper>> GetUnregisteredTroopersAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); return await _dbContext.Users.AsNoTracking() .Include(x => x.RecruitStatus) .Where(x => !string.IsNullOrEmpty(x.AccessCode)) .ToListAsync(); } public async Task<ZetaOrbatData> GetZetaOrbatDataAsync() { using var _dbContext = _dbContextFactory.CreateDbContext(); ZetaOrbatData data = new(); await _dbContext.Users.AsNoTracking() .Where(x => x.Slot >= Data.Slot.ZetaCompany && x.Slot < Data.Slot.InactiveReserve || x.Slot == Data.Slot.Hailstorm) .ForEachAsync(x => data.Assign(x)); return data; } public async Task<RegisterTrooperResult> RegisterTrooper(NewTrooperData trooperData, ClaimsPrincipal user) { List<string> errors = new(); try { var uniqueSets = await GetInUseUserDataAsync(); if (uniqueSets.Item1.Contains(trooperData.Id)) { errors.Add("This ID is already in use."); } if (uniqueSets.Item2.Contains(trooperData.NickName)) { errors.Add("This Nickname is already in use."); } if (errors.Count > 0) return new(false, null, errors); var token = Guid.NewGuid().ToString(); var time = DateTime.UtcNow.ToEst(); var trooper = new Trooper() { Id = trooperData.Id, NickName = trooperData.NickName, Rank = trooperData.StartingRank, UserName = token, StartOfService = time, LastPromotion = time, AccessCode = token, Slot = Data.Slot.InactiveReserve, }; var recruiter = await GetTrooperFromClaimsPrincipalAsync(user); trooper.RecruitedByData = new() { RecruitedById = recruiter?.Id ?? 0, ChangedOn = time, }; trooper.RecruitStatus = new() { Age = trooperData.Age, ModsInstalled = trooperData.ModsDownloaded, OverSixteen = trooperData.Sixteen, PossibleTroll = trooperData.PossibleTroll, PreferredRole = trooperData.PreferredRole }; var identRes = await _userManager.CreateAsync(trooper, token); if (!identRes.Succeeded) { foreach (var error in identRes.Errors) errors.Add($"[{error.Code}] {error.Description}"); return new(false, null, errors); } identRes = await _userManager.AddToRoleAsync(trooper, "Trooper"); if (!identRes.Succeeded) { foreach (var error in identRes.Errors) errors.Add($"[{error.Code}] {error.Description}"); return new(false, null, errors); } identRes = await _userManager.AddClaimAsync(trooper, new("Training", "BCT")); if (!identRes.Succeeded) { foreach (var error in identRes.Errors) errors.Add($"[{error.Code}] {error.Description}"); return new(false, null, errors); } return new(true, token, null); } catch (Exception ex) { errors.Add(ex.Message); return new(false, null, errors); } } public async Task LoadPublicProfileDataAsync(Trooper trooper) { using var _dbContext = _dbContextFactory.CreateDbContext(); await _dbContext.DisciplinaryActions.Include(e => e.FiledBy) .Where(e => e.FiledAgainstId == trooper.Id) .LoadAsync(); await _dbContext.TrooperFlags.Include(e => e.Author) .Where(e => e.FlagForId == trooper.Id) .LoadAsync(); if(_dbContext.Entry(trooper).State == EntityState.Detached) _dbContext.Attach(trooper); await _dbContext.Entry(trooper) .Collection(e => e.DisciplinaryActions) .LoadAsync(); await _dbContext.Entry(trooper) .Collection(e => e.Flags) .LoadAsync(); } public async Task<List<Trooper>> GetDirectSubordinates(Trooper t) { using var _dbContext = _dbContextFactory.CreateDbContext(); List<Trooper> sub = new(); if (t is null) return sub; await _dbContext.Users .AsNoTracking() .ForEachAsync(x => { if (x.Id == t.Id) return; if (x.AccessCode is null) return; int slot = (int)t.Slot; int thisSlot = (int)x.Slot; if (slot == 0) { if ((slot / 10 % 10) == 0) { sub.Add(x); return; } } // This is a company else if ((slot / 10 % 10) == 0) { if (t.Role == Data.Role.Commander || t.Role == Data.Role.NCOIC || t.Role == Data.Role.XO) { int slotDif = thisSlot - slot; if (slotDif >= 0 && slotDif < 100) { if ((slotDif % 10) == 0) { // In the company staff if (slotDif == 0 || x.Role == Data.Role.Commander || x.Role == Data.Role.SergeantMajor) { sub.Add(x); return; } } else if (x.Role == Data.Role.Lead && x.Team is null && x.Slot >= Data.Slot.Mynock && x.Slot < Data.Slot.Razor) { sub.Add(x); return; } } } } // This is a Plt. if ((slot % 10) == 0) { if (t.Role == Data.Role.Commander || t.Role == Data.Role.SergeantMajor || t.Role == Data.Role.MasterWarden || t.Role == Data.Role.ChiefWarden) { int slotDif = thisSlot - slot; if (slotDif >= 0 && slotDif < 10) { //// In the platoon staff //if (slotDif == 0) // sub.Add(x); //// This is a squad leader //else if (x.Role == Data.Role.Lead && x.Team is null) // sub.Add(x); //else if (x.Role == Data.Role.Pilot || x.Role == Data.Role.Warden) // sub.Add(x); sub.Add(x); } } } // This is a squad else { if(t.Role == Data.Role.Lead) { if (thisSlot == slot) { if (t.Team is null) sub.Add(x); else if (t.Team == x.Team) sub.Add(x); } } } }); return sub; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Observer { class Client { static void Main(string[] args) { ConcreteSubject subject = new ConcreteSubject(); Observer observer1 = new ConcreteObserver(); Observer observer2 = new ConcreteObserver(); Observer observer3 = new ConcreteObserver(); Observer observer4 = new ConcreteObserver(); subject.Attach(observer1); subject.Attach(observer2); subject.Attach(observer3); subject.Attach(observer4); subject.Invoke(); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Text; namespace AdvancedConcepts { class ExtensionMethodDemo { static void Main() { int num1 = 10; Console.WriteLine(num1.IsGreaterThan(5) ? "Current value is Greater than param. value" : "Current value is Smaller than param. value"); Console.ReadLine(); } } static class IntExtension { public static bool IsGreaterThan(this int CurrentInt, int intToCompare) { return CurrentInt > intToCompare; } } }
using System; using MDS; namespace ServerTest { class Program { static void Main(string[] args) { try { var server = new MDSServer(); server.Start(); Console.WriteLine("DotNetMQ server has started."); Console.WriteLine("Press enter to stop..."); Console.ReadLine(); server.Stop(true); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } } } }
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { private AimMouse aim; public bool facingRight = true; // For determining direction player is facing public float speed = 10.0f; // Speed of movement public float jumpForce = 10.0f; // How high player can jump public float knockbackY = 10.0f; public bool grounded; // Check if player is grounded public bool onEnemy; // Check if player is stepping on an enemy public bool onWall; // Check if player is touching wall Animator animator; // Control player animations public LayerMask whatIsGround; // Determine surface layers public LayerMask whatIsEnemy; public LayerMask whatIsWall; private Rigidbody2D myRigidBody; // Control player physics private Collider2D myCollider; // Control collider triggers private Transform myTransform; // Control player transformations public Transform firePoint; // Point of projectile launch public GameObject projectile; // projectile being fired float h; // Controls when player is moving bool horizontalEnable = true; bool doubleJump = true; // Use this for initialization void Start () { myRigidBody = GetComponent<Rigidbody2D> (); myCollider = GetComponent<Collider2D> (); animator = GetComponent<Animator> (); myTransform = GetComponent<Transform> (); aim = FindObjectOfType<AimMouse>(); } void FixedUpdate() { // flip actor if (h < 0 && facingRight) Flip (); else if (h > 0 && !facingRight) Flip (); } // Update is called once per frame void Update () { myRigidBody.rotation = 0.0f; if (horizontalEnable) h = Input.GetAxis ("Horizontal"); myRigidBody.velocity = new Vector2 (h * speed, myRigidBody.velocity.y); // Animate movement if (h != 0) animator.SetBool ("isMoving", true); else animator.SetBool ("isMoving", false); // check if collider is touching ground layer grounded = Physics2D.IsTouchingLayers (myCollider, whatIsGround); onWall = Physics2D.IsTouchingLayers(myCollider, whatIsWall); onEnemy = Physics2D.IsTouchingLayers (myCollider, whatIsEnemy); // Jump if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.W)) { Jump (); } // Crouch the character if (Input.GetKeyDown("s")) { animator.SetBool("inputDown", true); } else { animator.SetBool("inputDown", false); } animator.SetBool ("isGrounded", grounded); /* // Fire projectile towards mouse button if(Input.GetButtonDown("Fire1")) { // Fire shot } */ } void Jump() { if (grounded || onEnemy || doubleJump) { if (Input.GetKeyDown(KeyCode.W)) // If input is W, perform a soft jump { myRigidBody.velocity = new Vector2 (myRigidBody.velocity.x, jumpForce*.75f); doubleJump = false; } else { myRigidBody.velocity = new Vector2 (myRigidBody.velocity.x, jumpForce); doubleJump = false; } } if (grounded) doubleJump = true; // Allow player to dble jump again after touching ground } // switch direction of the player void Flip() { facingRight = !facingRight; Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.Interactive.App.Tests { internal static class Jupyter { private static bool? _defaultKernelPathExists; public static bool DefaultKernelPathExists => _defaultKernelPathExists ??= CheckDefaultKernelPathExists(); private static bool CheckDefaultKernelPathExists() { var expectedPath = new JupyterKernelSpecModule().GetDefaultKernelSpecDirectory(); return expectedPath.Exists; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class test2 : MonoBehaviour { public char toto; public byte tata; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BGMManager : MonoBehaviour { public static BGMManager instance = null; AudioSource audioSource; public List<AudioClip> songs; private void Awake() { if (instance != null) Destroy(gameObject); else instance = this; DontDestroyOnLoad(gameObject); audioSource = GetComponent<AudioSource>(); } public void PlayBGM(string name) { foreach (AudioClip clip in songs) { if (clip.name == name) { audioSource.clip = clip; audioSource.Play(); } } } public IEnumerator FadeOut() { while (audioSource.volume > 0f) { audioSource.volume -= Time.deltaTime / 4f; yield return null; } } public void FadeThisOut() { StartCoroutine(FadeOut()); } public IEnumerator FadeOutFast() { while (audioSource.volume > 0f) { audioSource.volume -= Time.deltaTime / 1f; yield return null; } } public IEnumerator FadeIn() { while (audioSource.volume < 1f) { audioSource.volume += Time.deltaTime / 2f; yield return null; } } public void ToggleLoop() { audioSource.loop = !audioSource.loop; } public void ToggleLoop(bool value) { audioSource.loop = value; } }
using System; using System.Collections.Generic; using System.Text; namespace EjemplosDelegados1 { class Persona { //Creamos las propiedades que tendra nuestro objecto Persona private string _Nombre; private int _Edad; public string Nombre { get { return _Nombre; } set { _Nombre = value; } } public int Edad { get { return _Edad; } set { _Edad = value; } } //Creamos el Delegado con su firma public delegate void Mostrar(string nombre, int edad); //Creamos la variable del tipo del delegado public Mostrar MostrarStatsPersona; //Este metodo se encargara de ejecutar el metodo que le pasemos des de Program public void Ejecutar() { MostrarStatsPersona(Nombre, Edad); } //Con esta manera no nos hace falta crear la variable de tipo delegado public void Ejecutar(Mostrar m, string nombre, int edad) { m(nombre, edad); } //Metodos public void MostrarStatsCompletas(string nombre, int edad) { Console.WriteLine("Nombre: {0} \nEdad: {1}", nombre, edad); } public void MostrarStatsEdad(string nombre, int edad) { Console.WriteLine("Edad: {0}", edad); } public void MostrarStatsNombre(string nombre, int edad) { Console.WriteLine("Nombre: {0}", nombre); } //Metodo que se encarga de meter a los otros metodos dentro de la variable de tip delegado public void AñadirMetodo(Mostrar m) { MostrarStatsPersona += m; } } }
using Accounts.Service.Contract.DTOs; using Accounts.Service.Contract.Queries; using Accounts.Service.Contract.Repository.Interfaces; using CORE2; using Models.Accounts; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Accounts.Service.QueryHandlers { public class GetGroupQueryHandler : IQueryHandler<GetGroupSmallDetailDTOQuery, GroupSmallDetailDTO> { IGroupRepository _groupRepository; public GetGroupQueryHandler(IGroupRepository groupRepository) { _groupRepository = groupRepository; } public async Task<GroupSmallDetailDTO> HandleAsync(GetGroupSmallDetailDTOQuery query) { Group group = await _groupRepository.GetByIdAsync(query.Id); GroupSmallDetailDTO groupDto = new GroupSmallDetailDTO(group); return groupDto; } } }
using Assets.Scripts.RobinsonCrusoe_Game.RoundSystem; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Actionphase : MonoBehaviour { public GameObject actionphase_Prefab; private PhaseView myView; // Start is called before the first frame update void Start() { myView = GetComponent<PhaseView>(); myView.currentPhaseChanged += OnPhaseChange; } private void OnPhaseChange(object sender, EventArgs e) { if (myView.currentPhase == E_Phase.Action) { Debug.Log("Entered Phase: Action"); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace To_Do { public class PaginatedList<T> : List<T> { public int PageNumber { get; private set; } public int TotalPages { get; private set; } public PaginatedList(List<T> items, int count, int pageNumber, int pageSize) { PageNumber = pageNumber; TotalPages = count / pageSize; //Account for a partial page if we have it if (count % pageSize > 0) { TotalPages++; } AddRange(items); } public bool HasPreviousPage => PageNumber > 1; public bool HasNextPage => PageNumber < TotalPages; public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageNumber, int pageSize) { var count = await source.CountAsync(); var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync(); return new PaginatedList<T>(items, count, pageNumber, pageSize); } } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades.Estoque.Suprimentos; using PDV.DAO.Enum; using System.Data; using System; using System.Collections.Generic; namespace PDV.CONTROLER.Funcoes { public class FuncoesAlmoxarifado { public static bool Salvar(Almoxarifado Almoxarifado, TipoOperacao Op) { using (SQLQuery oSQL = new SQLQuery()) { switch (Op) { case TipoOperacao.INSERT: oSQL.SQL = @"INSERT INTO ALMOXARIFADO (IDALMOXARIFADO, DESCRICAO, TIPO) VALUES (@IDALMOXARIFADO, @DESCRICAO, @TIPO)"; break; case TipoOperacao.UPDATE: oSQL.SQL = @"UPDATE ALMOXARIFADO SET DESCRICAO = @DESCRICAO, TIPO = @TIPO WHERE IDALMOXARIFADO = @IDALMOXARIFADO"; break; } oSQL.ParamByName["IDALMOXARIFADO"] = Almoxarifado.IDAlmoxarifado; oSQL.ParamByName["DESCRICAO"] = Almoxarifado.Descricao; oSQL.ParamByName["TIPO"] = Almoxarifado.Tipo; return oSQL.ExecSQL() == 1; } } public static bool Remover(decimal IDAlmoxarifado) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"DELETE FROM ALMOXARIFADO WHERE IDALMOXARIFADO = @IDALMOXARIFADO"; oSQL.ParamByName["IDALMOXARIFADO"] = IDAlmoxarifado; return oSQL.ExecSQL() == 1; } } public static bool Existe(decimal IDAlmoxarifado) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM ALMOXARIFADO WHERE IDALMOXARIFADO = @IDALMOXARIFADO"; oSQL.ParamByName["IDALMOXARIFADO"] = IDAlmoxarifado; oSQL.Open(); return !oSQL.IsEmpty; } } public static DataTable GetAlmoxarifados(string Descricao) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = $@"SELECT ALMOXARIFADO.DESCRICAO, CASE WHEN ALMOXARIFADO.TIPO = 1 THEN 'Estoque' WHEN ALMOXARIFADO.TIPO = 2 THEN 'Produção' WHEN ALMOXARIFADO.TIPO = 3 THEN 'Quarentena' END AS DESCRICAOTIPO, ALMOXARIFADO.IDALMOXARIFADO, ALMOXARIFADO.TIPO FROM ALMOXARIFADO WHERE UPPER(DESCRICAO) LIKE UPPER('%{Descricao}%')"; oSQL.Open(); return oSQL.dtDados; } } public static Almoxarifado GetAlmoxarifado(decimal IDAlmoxarifado) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT * FROM ALMOXARIFADO WHERE IDALMOXARIFADO = @IDALMOXARIFADO"; oSQL.ParamByName["IDALMOXARIFADO"] = IDAlmoxarifado; oSQL.Open(); return EntityUtil<Almoxarifado>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static Almoxarifado GetAlmoxarifado() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT * FROM ALMOXARIFADO LIMIT 1"; oSQL.Open(); return EntityUtil<Almoxarifado>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static List<Almoxarifado> GetAlmoxarifados() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT IDALMOXARIFADO, DESCRICAO, TIPO FROM ALMOXARIFADO ORDER BY DESCRICAO, TIPO"; oSQL.Open(); return new DataTableParser<Almoxarifado>().ParseDataTable(oSQL.dtDados); } } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("CardBackReward")] public class CardBackReward : Reward { public CardBackReward(IntPtr address) : this(address, "CardBackReward") { } public CardBackReward(IntPtr address, string className) : base(address, className) { } public void HideReward() { base.method_8("HideReward", Array.Empty<object>()); } public void InitData() { base.method_8("InitData", Array.Empty<object>()); } public void OnBackCardBackLoaded(CardBackManager.LoadCardBackData cardbackData) { object[] objArray1 = new object[] { cardbackData }; base.method_8("OnBackCardBackLoaded", objArray1); } public void OnDataSet(bool updateVisuals) { object[] objArray1 = new object[] { updateVisuals }; base.method_8("OnDataSet", objArray1); } public void OnFrontCardBackLoaded(CardBackManager.LoadCardBackData cardbackData) { object[] objArray1 = new object[] { cardbackData }; base.method_8("OnFrontCardBackLoaded", objArray1); } public void ShowReward(bool updateCacheValues) { object[] objArray1 = new object[] { updateCacheValues }; base.method_8("ShowReward", objArray1); } public GameObject m_cardbackBone { get { return base.method_3<GameObject>("m_cardbackBone"); } } public int m_numCardBacksLoaded { get { return base.method_2<int>("m_numCardBacksLoaded"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ToolGood.Algorithm; namespace ToolGood.Algorithm.Test { class Program { static void Main(string[] args) { PetaTest.Runner.RunMain(args); //RPN rpn = new RPN(); //rpn.Parse("tan(1)+2+333"); //AlgorithmEngine engine = new AlgorithmEngine(); //if (engine.Parse("countif({0,1,2,3,-1},'>1')")) { // var t = engine.Evaluate(); //} //if (engine.Parse("min(1,{0,1,2,3,-1})")) { // var t = engine.Evaluate(); //} //if (engine.Parse("NORMINV(0.369441340181764,5,3)")) { // var t = engine.Evaluate(); //} //if (engine.Parse("NORMDIST(4,5,3,0)")) { // var t = engine.Evaluate(); //} //if (engine.Parse("'2016-1-1'+'12:22'")) { // var t = engine.Evaluate(); //} //if (engine.Parse("'sss'+'bbb'")) { // var t = engine.Evaluate(); //} //if (engine.Parse("acosh(2)")) { // var t = engine.Evaluate(); //} //if (engine.Parse("1+sum(1,2,3)")) { // var t = engine.Evaluate(); //} //if (engine.Parse("1+2-3+4*5+5/(9-8)+sum(1,2,3)")) { // var t = engine.Evaluate(); //} //var t = engine.Parse("[11]* (1+(1*2+[112]))+ld(11)+'\"222'"); //var count = t.Count; } } }
using System; using System.Linq; namespace KT.DB.CRUD { public class TestRepository : ICrud<Test> { public Test Create(Test entity) { using (var db = new KTEntities()) { db.Tests.AddObject(entity); db.SaveChanges(); return entity; } } public Test Read(Predicate<Test> predicate, string[] relatedObjects = null) { using (var db = new KTEntities()) { var test = db.Tests.Include(relatedObjects).AsEnumerable().DefaultIfEmpty(null).FirstOrDefault(a => predicate(a)); return test; } } public Test[] ReadArray(Predicate<Test> predicate, string[] relatedObjects = null) { using (var db = new KTEntities()) { var test = db.Tests.Include(relatedObjects).AsEnumerable().Where(a => predicate(a)); return test.ToArray(); } } public Test Update(Test entity) { using (var db = new KTEntities()) { var test = db.Tests.DefaultIfEmpty(null).FirstOrDefault(a => a.Id == entity.Id); if (test != null) { test.Name = entity.Name; test.QuestionCount = entity.QuestionCount; test.SubcategoryId = entity.SubcategoryId; test.EndDate = entity.EndDate; test.MinutesDuration = entity.MinutesDuration; test.StartDate = entity.StartDate; db.SaveChanges(); } return test; } } public void Delete(Predicate<Test> predicate) { using (var db = new KTEntities()) { var tests = db.Tests.AsEnumerable().Where(a => predicate(a)); foreach (var test in tests) { db.Tests.DeleteObject(test); } db.SaveChanges(); } } } }
 using API.Omorfias.Data.Models; using API.Omorfias.DataAgent.Interfaces; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace API.Omorfias.DataAgent.Services { public class DataAgentService : IDataAgentService { private readonly string _accessToken = "SECRETSECRETSECRETSECRETSECRETSECRETSECRET"; public string GenerateToken(User user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_accessToken); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("id", user.Id.ToString()), new Claim("name", user.Name), new Claim("lastName", user.LastName), new Claim("email", user.Email), }), Expires = DateTime.UtcNow.AddHours(72), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } }
using Microsoft.Extensions.Options; using Publicon.Infrastructure.Managers.Abstract; using Publicon.Infrastructure.Settings; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace Publicon.Infrastructure.Managers.Concrete { public class MailManager : IMailManager { private readonly MailSettings _mailSettings; private SmtpClient _client; public MailManager(IOptions<MailSettings> mailOptions) { _mailSettings = mailOptions.Value; InitializeSmtpClient(); } public async Task SendMailAsync(string receiver, string subject, string message) { using (var emailMessage = new MailMessage()) { emailMessage.To.Add(new MailAddress(receiver)); emailMessage.From = new MailAddress(_mailSettings.Email); emailMessage.Subject = subject; emailMessage.Body = message; _client.Send(emailMessage); } await Task.CompletedTask; } private void InitializeSmtpClient() { _client = new SmtpClient { Credentials = GetCredentials(), Host = _mailSettings.Host, Port = _mailSettings.Port, EnableSsl = true }; } private NetworkCredential GetCredentials() { return new NetworkCredential { UserName = _mailSettings.Email, Password = _mailSettings.Password }; } } }
namespace TridevLoader.Mod.API.Item { /// <summary> /// Used in place of direct references to the real game item tiers. /// </summary> public enum ModItemTier { Tier1, Tier2, Tier3, Lunar, Boss, NoTier } }
using EntidadesCompartidas; using Logica; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; // NOTA: puede usar el comando "Rename" del menú "Refactorizar" para cambiar el nombre de clase "Service1" en el código, en svc y en el archivo de configuración. public class Service : IService { #region LogicaUsuario void IService.AltaUsuario(Usuario usuario, Empleado usLog) { FabricaLogica.GetLogicaUsuario().AltaUsuario(usuario, usLog); } void IService.BajaUsuario(Usuario usuario, Empleado usLog) { FabricaLogica.GetLogicaUsuario().BajaUsuario(usuario, usLog); } Usuario IService.BuscarUsuario(string logueo, Empleado usLog) { return FabricaLogica.GetLogicaUsuario().BuscarUsuario(logueo, usLog); } Usuario IService.LogueoUsuario(string logueo, string contraseana) { return FabricaLogica.GetLogicaUsuario().LogueoUsuario(logueo, contraseana); } void IService.ModificarUsuario(Usuario usuario, Empleado usLog) { FabricaLogica.GetLogicaUsuario().ModificarUsuario(usuario, usLog); } void IService.ModificarContrasenaUsuario(Usuario usuario, Usuario usLog) { FabricaLogica.GetLogicaUsuario().ModificarContrasenaUsuario(usuario, usLog); } List<Empresa> IService.ListarEmpresas(Empleado usuarioLogueado) { return FabricaLogica.GetLogicaUsuario().ListarEmpresas(usuarioLogueado); } #endregion #region LogicaPaquete void IService.AltaPaquete(Paquete paquete, Empleado usLog) { FabricaLogica.GetLogicaPaquete().AltaPaquete(paquete, usLog); } Paquete IService.BuscarPaquete(int codigo, Empleado usLog) { return FabricaLogica.GetLogicaPaquete().BuscarPaquete(codigo, usLog); } List<Paquete> IService.ListadoPaquetesSinSolicitud(Empleado usLog) { return FabricaLogica.GetLogicaPaquete().ListadoPaquetesSinSolicitud(usLog); } #endregion #region LogicaSolicitud int IService.AltaSolicitud(Solicitud solicitud, Empleado usLog) { return FabricaLogica.GetLogicaSolicitud().AltaSolicitud(solicitud, usLog); } void IService.ModificarEstadoSolicitud(Solicitud solicitud, Empleado usLog) { FabricaLogica.GetLogicaSolicitud().ModificarEstadoSolicitud(solicitud, usLog); } string IService.listadoSolicitudesEnCamino() { return FabricaLogica.GetLogicaSolicitud().listadoSolicitudesEnCamino(); } List<Solicitud> IService.listadoSolicitudesEmpresa(Empresa usLog) { return FabricaLogica.GetLogicaSolicitud().listadoSolicitudesEmpresa(usLog); } public List<Solicitud> listadoSolicitudes(Empleado usLog) { return FabricaLogica.GetLogicaSolicitud().listadoSolicitudes(usLog); } #endregion }
using server.Utilities; namespace server.Dtos { public class BusinessAboutUpdateDto { public BAbout BAbout{get;set;} public string BName{get; set;} } }
using System; using System.Collections.Generic; using System.Text; namespace Hybrid.EntityFramework { class DbContextBase { } }
using System; namespace LeeConlin.ExtensionMethods { public static class DoubleExtensions { public static bool IsTruthy(this double i) { // This will work in most cases. A simple == or != would fall // afoul of precision issues return i > 0.0000000001 || i < -0.0000000001; } } }
using MobileFPS.PlayerHealth; using MobileFPS.PlayerUI; using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { [SerializeField] Text _ammo_Text; [SerializeField] Text _health_Text; [SerializeField] Text _FPS; [SerializeField] GameObject MainCamera; [SerializeField] PlayerUIManager _playerUIManager; [SerializeField] GameObject _crossHair; [SerializeField] Image _healhBar; public GameObject _canvas; public GameObject _deadUI, _aliveUI; public GameObject Camera => MainCamera; public Text Ammo => _ammo_Text; public Text Health => _health_Text; public GameObject CrossHair => _crossHair; public Image HealthBar => _healhBar; void Awake() { MainCamera.SetActive( true ); _deadUI.SetActive( false ); _aliveUI.SetActive( false ); Application.targetFrameRate = 144; } void Update() { float fps = 1 / Time.deltaTime; _FPS.text = fps.ToString(); } }
using Microsoft.EntityFrameworkCore.Migrations; namespace eForm.Migrations { public partial class CreateNewTempFile : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateIndex( name: "IX_TestUpload_TenantId", table: "TestUpload", column: "TenantId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_TestUpload_TenantId", table: "TestUpload"); } } }
namespace Domain { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Zebble; partial class Api { #region Dummy API Response static Contact[] DummyApiContactsResponse; static Random Random = new Random(); static string[] FakeFirstNames = "Nicola,Gabriel,Leroy,Shaw,Tad,Miriam,Melita,Quiana,Felicia,Lindsay,Rae,Signe".Split(',').ToArray(); static string[] FakeLastNames = "Pickford,Gabel,Benes,Roosevelt,Colegrove,Heitman,Fritsche,Roberds,Flury,Vail,Kendra,Arens,Carbone".Split(',').ToArray(); static IEnumerable<Contact> CreateDummyApiContactsResponse() { for (var i = 0; i < 100; i++) { var randomName = FakeFirstNames.PickRandom(); yield return new Contact { Id = Guid.NewGuid(), Name = randomName + " " + FakeLastNames.PickRandom(), DateOfBirth = LocalTime.Today.AddDays(-Random.Next(10000, 20000)), Email = randomName + Random.Next(100, 999) + "@" + new[] { "gmail", "yahoo", "hotmail" }.PickRandom() + ".com", Tel = "0" + Random.Next(100000000, 900000000), Type = new ContactType { Name = DummyContactTypes.PickRandom() } }; } } #endregion public static Task<Contact[]> GetContacts() { // TODO: return Get<Contact[]>("api/v1/contacts"); if (DummyApiContactsResponse == null) DummyApiContactsResponse = CreateDummyApiContactsResponse().ToArray(); return Task.FromResult(DummyApiContactsResponse); } internal static Task<bool> Save(Contact item) => Post("api/v1/contacts/save", item); public static Task Delete(Contact contact) => Delete("api/v1/contacts/delete", new { Id = contact.Id }); } } namespace Zebble.Data { }
using async_inn.Data; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace async_inn.Models { public class RoleIntiliazer { // creates list of identity roles private static List<IdentityRole> Roles = new List<IdentityRole>() { new IdentityRole { Name = ApplicationRoles.DistrictManager, NormalizedName = ApplicationRoles.DistrictManager.ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString() }, new IdentityRole { Name = ApplicationRoles.PropertyManager, NormalizedName = ApplicationRoles.PropertyManager.ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString() }, new IdentityRole { Name = ApplicationRoles.Agent, NormalizedName = ApplicationRoles.Agent.ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString() }, }; public static void SeedData(IServiceProvider serviceProvider) { using (var dbContext = new AsyncInnDbContext(serviceProvider.GetRequiredService<DbContextOptions<AsyncInnDbContext>>())) { dbContext.Database.EnsureCreated(); AddRoles(dbContext); } } private static void SeedUsers(UserManager<ApplicationUser> userManager, IConfiguration _config) { if (userManager.FindByEmailAsync(_config["AdminEmail"]).Result == null) { ApplicationUser user = new ApplicationUser(); user.UserName = _config["AdminEmail"]; user.Email = _config["AdminEmail"]; user.FirstName = "Yasir"; user.LastName = "Mohamud"; IdentityResult result = userManager.CreateAsync(user, _config["AdminPassword"]).Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, ApplicationRoles.DistrictManager).Wait(); } } } private static void AddRoles(AsyncInnDbContext context) { if (context.Roles.Any()) return; foreach (var role in Roles) { context.Roles.Add(role); context.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Domain.Entity; using FluentNHibernate.Mapping; namespace PropertyManagement.Domain.Mapping.FluentHibernate { public class RefundMap : ClassMap<Refund> { public RefundMap() { Table("Refund"); Id(x => x.ID).Column("ID").GeneratedBy.Identity(); //References(x => x.JobBooking).Column("JobBookingID").Cascade.All(); Map(x => x.RefundAmount).Column("RefundAmount"); //Map(x => x.CreatedBy).Column("CreatedBy"); Map(x => x.CreatedDate).Column("CreatedDate"); //Map(x => x.UpdatedBy).Column("UpdatedBy"); Map(x => x.UpdatedDate).Column("UpdatedDate"); } } }
using Domain.Interfaces.Generics; using Entities.Entities; using Entities.Entities.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.Interfaces.InterfaceCompra { public interface ICompra : IGeneric<Compra> { public Task<Compra> CompraPorEstado(string userId, EnumEstadoCompra estado); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CoordControl.Core.Domains; namespace CoordControl.Core { public sealed class PlanCalculatorWithoutShifts : PlanCalculator { protected override void CalcPhaseShifts(Plan p) { foreach (CrossPlan crP in p.CrossPlans) { crP.PhaseOffset = 0; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; // Librerias usadas using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using System.Xml.Serialization; using SiscomSoft.Models; using SiscomSoft.Controller; using System.Security.Cryptography.X509Certificates; namespace SiscomSoft_Desktop.Views { public partial class FrmMenuFacturacion : Form { #region VARIABLES int pkCliente = 0; string Sello = string.Empty; string NameFile = string.Empty; string NameFileXML = string.Empty; string NameFilePDF = string.Empty; string FechaFactura = string.Empty; Boolean Dolar = false; decimal DESCUENTO = 0; decimal DESCUENTOEXTRA = 0; decimal TIVA16 = 0; decimal TIVA11 = 0; decimal TIVA4 = 0; decimal TIEPS53 = 0; decimal TIEPS30 = 0; decimal TIEPS26 = 0; decimal RIVA16 = 0; decimal RIVA1067 = 0; decimal RIVA733 = 0; decimal RIVA4 = 0; decimal RISR10 = 0; decimal TOTALTIVA16; decimal TOTALTIVA11; decimal TOTALTIVA4; decimal TOTALTIEPS53; decimal TOTALTIEPS30; decimal TOTALTIEPS26; decimal TOTALRIVA16; decimal TOTALRIVA1067; decimal TOTALRIVA733; decimal TOTALRIVA4; decimal TOTALRISR10; #endregion #region MAIN public FrmMenuFacturacion() { InitializeComponent(); this.dgvProductos.AutoGenerateColumns = false; } /// <summary> /// Se inicializa el timer. /// se manda llamar la funcion cargarSucursales(). /// se carga el numero de folio mediante la funcion Folio() que se encuentra en la clase ManejoFacturacion. /// se se les da el valor de 0 por defecto a los comboboxs. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmMenuFacturacion_Load(object sender, EventArgs e) { timer1.Start(); cargarSucursales(); txtFolio.Text = ManejoFacturacion.Folio(); cmbFormaDePago.SelectedIndex = 0; cmbMetodoDePago.SelectedIndex = 0; cmbMoneda.SelectedIndex = 0; cmbTipoDeComprobante.SelectedIndex = 0; cmbUsoCFDI.SelectedIndex = 0; } /// <summary> /// Con este timer se actualiza la hora que aparece en el lblFecha /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { lblFecha.Text = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString(); } /// <summary> /// Boton que utiliza para mandar llamar el menu principal y cierrar la ventana actual /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnMenuPrincipal_Click(object sender, EventArgs e) { this.Close(); FrmMenuMain v = new FrmMenuMain(); v.ShowDialog(); } #endregion #region FUNCTION /// <summary> /// Funcion encargada de llenar el combobox con las ids y los nombres de todas las sucursales activas que se encuentran en la base de datos. /// </summary> public void cargarSucursales() { cmbSucursal.DataSource = ManejoSucursal.getAll(1); cmbSucursal.DisplayMember = "sNombre"; cmbSucursal.ValueMember = "idSucursal"; } /// <summary> /// Funcion encargada de validar la existencia y la creacion de las carpetas necesarias para guardar los documentos relacionados con la facturación. /// </summary> public void CrearCarpetas() { try { string path = @"C:\SiscomSoft"; string FACTURA = @"C:\SiscomSoft\Facturas"; string XML = @"C:\SiscomSoft\Facturas\XML"; string PDF = @"C:\SiscomSoft\Facturas\PDF"; string ERROR = @"C:\SiscomSoft\Facturas\Errors"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!Directory.Exists(FACTURA)) { Directory.CreateDirectory(FACTURA); } if (!Directory.Exists(XML)) { Directory.CreateDirectory(XML); } if (!Directory.Exists(PDF)) { Directory.CreateDirectory(PDF); } if (!Directory.Exists(ERROR)) { Directory.CreateDirectory(ERROR); } } catch (Exception e) { MessageBox.Show("Error: " + e.ToString()); throw; } } /// <summary> /// Funcion encargada de llenar el DataGridView con los productos seleccionados mediante la id de los mismos. /// </summary> /// <param name="id">variable tipo entera</param> public void cargarDetalleFactura(int id) { #region VARIABLES decimal Total = 0; decimal Subtotal = 0; decimal TotalDolar = 0; decimal TipoCambio = 0; decimal TTasaImpuestoIVA16 = 0; decimal TTasaImpuestoIVA11 = 0; decimal TTasaImpuestoIVA4 = 0; decimal TTasaImpuestoIEPS53 = 0; decimal TTasaImpuestoIEPS26 = 0; decimal TTasaImpuestoIEPS30 = 0; decimal RTasaImpuestoIVA16 = 0; decimal RTasaImpuestoIVA1067 = 0; decimal RTasaImpuestoIVA733 = 0; decimal RTasaImpuestoIVA4 = 0; decimal RTasaImpuestoISR10 = 0; decimal TasaDescuento = 0; decimal TasaDescuentoExtra = 0; decimal Importe = 0; decimal ImporteWithoutExtras = 0; decimal ImporteWithTImpuestoIVA16 = 0; decimal ImporteWithTImpuestoIVA11 = 0; decimal ImporteWithTImpuestoIVA4 = 0; decimal ImporteWithTImpuestosIEPS53 = 0; decimal ImporteWithTImpuestosIEPS30 = 0; decimal ImporteWithTImpuestosIEPS26 = 0; decimal ImporteWithRImpuestoIVA16 = 0; decimal ImporteWithRImpuestoIVA1067 = 0; decimal ImporteWithRImpuestoIVA733 = 0; decimal ImporteWithRImpuestosIVA4 = 0; decimal ImporteWithRImpuestosISR10 = 0; decimal PreUnitarioWithDescuento = 0; decimal PriceForLot = 0; decimal Descuento = 0; decimal DescuentoExtra = 0; decimal PrecioUnitario = 0; decimal Cantidad = 0; #endregion Producto mProducto = ManejoProducto.getById(id); // Se busca el producto mediante la id y se guarda en un modelo tipo producto Catalogo mCatalogo = ManejoCatalogo.getById(mProducto.catalogo_id); // Se busca el catalogo mediante la llave foranea y se guarda en un modelo de tipo catalogo if (mProducto != null) // Se valida que el modelo no este vacio { DataGridViewRow row = (DataGridViewRow)dgvProductos.Rows[0].Clone(); // Se clona la primera fila del DataGridView // Se llenan las columnas de la fila clonada del DataGridView mediante los datos que se encuentran en el modelo producto row.Cells[0].Value = mProducto.idProducto; row.Cells[1].Value = mProducto.sClaveProd; row.Cells[2].Value = mProducto.sDescripcion; row.Cells[3].Value = mProducto.sMarca; row.Cells[4].Value = mCatalogo.sUDM; row.Cells[5].Value = mProducto.dCosto; row.Cells[6].Value = 1; PrecioUnitario = mProducto.dCosto; // Se le da el valor a la variabe PrecioUnitario segun los datos del modelo producto Cantidad = Convert.ToDecimal(row.Cells[6].Value); // Se le da el valor a la variable Cantidad segun el dato que se encuentre en la columna 6 del DataGridView #region Impuestos List<ImpuestoProducto> mImpuesto = ManejoImpuestoProducto.getById(Convert.ToInt32(mProducto.idProducto)); // Se buscan todos los impuestos que tiene el producto mediante la id del producto y se guardan en una ista // Se leen los impuestos que tiene guardada la lista foreach (ImpuestoProducto rImpuesto in mImpuesto) { var impuesto = ManejoImpuesto.getById(rImpuesto.impuesto_id); // Se busca el impuesto mediante el id que esta guardado en la lista #region TRASLADO // Se valida que el tipo de impuesto sea "TRASLADO" if (impuesto.sTipoImpuesto == "TRASLADO") { // Se valida que el impuesto sea "IVA" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(16.00)) { TTasaImpuestoIVA16 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(11.00)) { TTasaImpuestoIVA11 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(4.00)) { TTasaImpuestoIVA4 += impuesto.dTasaImpuesto; } // Se valida que el impuesto sea "IEPS" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(53.00)) { TTasaImpuestoIEPS53 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(30.00)) { TTasaImpuestoIEPS30 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(26.50)) { TTasaImpuestoIEPS26 += impuesto.dTasaImpuesto; } } #endregion #region RETENIDO // Se valida que el tipo de impuesto sea "RETENIDO" if (impuesto.sTipoImpuesto == "RETENIDO") { // Se valida que el impuesto sea "IVA" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(16.00)) { RTasaImpuestoIVA16 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(10.67)) { RTasaImpuestoIVA1067 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(7.33)) { RTasaImpuestoIVA733 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(4.00)) { RTasaImpuestoIVA4 += impuesto.dTasaImpuesto; } // Se valida que el impuesto sea "ISR" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables else if (impuesto.sImpuesto == "ISR" && impuesto.dTasaImpuesto == Convert.ToDecimal(10.00)) { RTasaImpuestoISR10 += impuesto.dTasaImpuesto; } } #endregion } #endregion #region Descuentos List<DescuentoProducto> mDescuento = ManejoDescuentoProducto.getById(Convert.ToInt32(mProducto.idProducto)); // Se buscan todos los descuentos que tiene el producto mediante la id del producto y se guardan en una ista // Se leen los descuentos que tiene guardada la lista foreach (DescuentoProducto rDescuento in mDescuento) { var descuento = ManejoDescuento.getById(rDescuento.descuento_id); // Se busca el descuento mediante el id que esta guardado en la lista TasaDescuento = descuento.dTasaDesc; // Se le da el valor a la variabe TasaDescuento segun los datos del modelo DescuentoProducto TasaDescuentoExtra = descuento.dTasaDescEx; // Se le da el valor a la variabe TasaDescuentoExtra segun los datos del modelo DescuentoProducto } #endregion #region CALCULOS // Se valida que la TasaDescuento no sea 0 para poder hacer el calculo correspondiente if (TasaDescuento != 0) { Descuento = PrecioUnitario * (TasaDescuento / 100); // Se le da el valor a la variabe Descuento segun el resultado del calculo } // Se valida que la TasaDescuentoExtra no sea 0 para poder hacer el calculo correspondiente if (TasaDescuentoExtra != 0) { DescuentoExtra = PrecioUnitario * (TasaDescuentoExtra / 100); // Se le da el valor a la variabe DescuentoExtra segun el resultado del calculo } ImporteWithoutExtras += Cantidad * PrecioUnitario; // Se le da el valor a la variabe ImporteWithoutExtras segun el resultado del calculo PreUnitarioWithDescuento = PrecioUnitario - Descuento - DescuentoExtra; // Se le da el valor a la variabe PreUnitarioWithDescuento segun el resultado del calculo PriceForLot = Cantidad * PreUnitarioWithDescuento; // Se le da el valor a la variabe PriceForLot segun el resultado del calculo #region TRASLADO ImporteWithTImpuestoIVA16 = PriceForLot * (TTasaImpuestoIVA16 / 100); // Se le da el valor a la variabe ImporteWithTImpuestoIVA16 segun el resultado del calculo TIVA16 = ImporteWithTImpuestoIVA16; // Se le da el valor a la variabe global TIVA16 segun el valor de la variable ImporteWithTImpuestoIVA16 row.Cells[8].Value = TIVA16; // Se le da el valor de la variable gloval TIVA16 a la columna 8 de la fila clonada del DataGridView ImporteWithTImpuestoIVA11 = PriceForLot * (TTasaImpuestoIVA11 / 100); // Se le da el valor a la variabe ImporteWithTImpuestoIVA11 segun el resultado del calculo TIVA11 = ImporteWithTImpuestoIVA11; // Se le da el valor a la variabe global TIVA11 segun el valor de la variable ImporteWithTImpuestoIVA11 row.Cells[9].Value = TIVA11; // Se le da el valor de la variable gloval TIVA11 a la columna 9 de la fila clonada del DataGridView ImporteWithTImpuestoIVA4 = PriceForLot * (TTasaImpuestoIVA4 / 100); // Se le da el valor a la variabe ImporteWithTImpuestoIVA4 segun el resultado del calculo TIVA4 = ImporteWithTImpuestoIVA4; // Se le da el valor a la variabe global TIVA4 segun el valor de la variable ImporteWithTImpuestoIVA row.Cells[10].Value = TIVA4; // Se le da el valor de la variable gloval TIVA4 a la columna 10 de la fila clonada del DataGridView ImporteWithTImpuestosIEPS53 = PriceForLot * (TTasaImpuestoIEPS53 / 100); // Se le da el valor a la variabe ImporteWithTImpuestosIEPS53 segun el resultado del calculo TIEPS53 = ImporteWithTImpuestosIEPS53; // Se le da el valor a la variabe global TIEPS53 segun el valor de la variable ImporteWithTImpuestoIEPS53 row.Cells[11].Value = TIEPS53; // Se le da el valor de la variable gloval TEPS53 a la columna 11 de la fila clonada del DataGridView ImporteWithTImpuestosIEPS30 = PriceForLot * (TTasaImpuestoIEPS30 / 100); // Se le da el valor a la variabe ImporteWithTImpuestosIEPS30 segun el resultado del calculo TIEPS30 = ImporteWithTImpuestosIEPS30; // Se le da el valor a la variabe global TIEPS30 segun el valor de la variable ImporteWithTImpuestoIEPS30 row.Cells[12].Value = TIEPS30; // Se le da el valor de la variable gloval TEPS30 a la columna 12 de la fila clonada del DataGridView ImporteWithTImpuestosIEPS26 = PriceForLot * (TTasaImpuestoIEPS26 / 100); // Se le da el valor a la variabe ImporteWithTImpuestosIEPS26 segun el resultado del calculo TIEPS26 = ImporteWithTImpuestosIEPS26; // Se le da el valor a la variabe global TIEPS26 segun el valor de la variable ImporteWithTImpuestoIEPS26 row.Cells[13].Value = TIEPS26; // Se le da el valor de la variable gloval TEPS26 a la columna 13 de la fila clonada del DataGridView #endregion #region RETENIDO ImporteWithRImpuestoIVA16 = PriceForLot * (RTasaImpuestoIVA16 / 100); // Se le da el valor a la variabe ImporteWithRImpuestoIVA16 segun el resultado del calculo RIVA16 = ImporteWithRImpuestoIVA16; // Se le da el valor a la variabe global RIVA16 segun el valor de la variable ImporteWithRImpuestoIVA16 row.Cells[14].Value = RIVA16; // Se le da el valor de la variable gloval RIVA16 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestoIVA1067 = PriceForLot * (RTasaImpuestoIVA1067 / 100); // Se le da el valor a la variabe ImporteWithRImpuestoIVA1067 segun el resultado del calculo RIVA1067 = ImporteWithRImpuestoIVA1067; // Se le da el valor a la variabe global RIVA1067 segun el valor de la variable ImporteWithRImpuestoIVA1067 row.Cells[15].Value = RIVA1067; // Se le da el valor de la variable gloval RIVA1067 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestoIVA733 = PriceForLot * (RTasaImpuestoIVA733 / 100); // Se le da el valor a la variabe ImporteWithRImpuestoIVA733 segun el resultado del calculo RIVA733 = ImporteWithRImpuestoIVA733; // Se le da el valor a la variabe global RIVA1067 segun el valor de la variable ImporteWithRImpuestoIVA1067 row.Cells[16].Value = RIVA733; // Se le da el valor de la variable gloval RIVA1067 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestosIVA4 = PriceForLot * (RTasaImpuestoIVA4 / 100); // Se le da el valor a la variabe ImporteWithRImpuestosIVA4 segun el resultado del calculo RIVA4 = ImporteWithRImpuestosIVA4; // Se le da el valor a la variabe global RIVA4 segun el valor de la variable ImporteWithRImpuestosIVA4 row.Cells[17].Value = RIVA4; // Se le da el valor de la variable gloval RIVA4 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestosISR10 = PriceForLot * (RTasaImpuestoISR10 / 100); // Se le da el valor a la variabe ImporteWithRImpuestosISR10 segun el resultado del calculo RISR10 = ImporteWithRImpuestosISR10; // Se le da el valor a la variabe global RISR10 segun el valor de la variable ImporteWithRImpuestosISR10 row.Cells[18].Value = RISR10; // Se le da el valor de la variable gloval RISR10 a la columna 14 de la fila clonada del DataGridView #endregion Importe = PriceForLot + ImporteWithTImpuestoIVA16 + ImporteWithTImpuestoIVA11 + ImporteWithTImpuestoIVA4 + ImporteWithTImpuestosIEPS53 + ImporteWithTImpuestosIEPS30 + ImporteWithTImpuestosIEPS26; // Se le da el valor a la variabe Importe segun el resultado del calculo //TODO: SACAR EL RETENIDO DEL IMPORTE #endregion // Se llenan las columnas de la fila clonada del DataGridView mediante las variables usadas en las cuentas row.Cells[7].Value = Importe.ToString("N"); row.Cells[21].Value = ImporteWithoutExtras.ToString("N"); row.Cells[22].Value = mCatalogo.sClaveUnidad; row.Height = 30; // Se le asigna una altura predeterminada a las filas clonadas dgvProductos.Rows.Add(row); // Se agrega la fila clonada al DataGridView // Se recorren las filas del DataGridView foreach (DataGridViewRow rItem in dgvProductos.Rows) { Total += Convert.ToDecimal(rItem.Cells[7].Value); // Se acomula el valor de la variabe global Total segun se recorre la columna 7 del DataGridView Subtotal += Convert.ToDecimal(rItem.Cells[21].Value); // Se acomula el valor de la variabe global Subtotal segun se recorre la columna 21 del DataGridView } // Se valida que el valor de la variable global dolar sea true para sacar el total en dolares if (Dolar != false) { Sucursal mSucursal = ManejoSucursal.getById(FrmMenuMain.uHelper.usuario.sucursal_id); // se busca la sucursal mediante la llave foranea que tiene el usuario logeado y se guarda en un modelo de tipo sucursal TipoCambio = Convert.ToDecimal(mSucursal.sTipoCambio); // Se le da el valor a la variabe TipoCambio segun los datos del modelo sucursal TotalDolar = (Total * 1) / TipoCambio; // Se le da el valor a la variabe TotalDolar segun el resultado del calculo lblTotalDolar.Text = TotalDolar.ToString("N"); // Se le da el valor al lblTotalDolar segun el valor de la variable TotalDolar } // Se asignan valores a los respectivos labels lblSubTotal.Text = Subtotal.ToString("N"); lblTotal.Text = Total.ToString("N"); lblIVA16.Text = TIVA16.ToString("N"); lblIVA11.Text = TIVA11.ToString("N"); lblIVA4.Text = TIVA4.ToString("N"); lblIEPS53.Text = TIEPS53.ToString("N"); lblIEPS30.Text = TIEPS30.ToString("N"); lblIEPS26.Text = TIEPS26.ToString("N"); lblRIVA16.Text = RIVA16.ToString("N"); lblRIVA1067.Text = RIVA1067.ToString("N"); lblRIVA733.Text = RIVA733.ToString("N"); lblRIVA4.Text = RIVA4.ToString("N"); lblRISR10.Text = RISR10.ToString("N"); } } /// <summary> /// Funcion encargada de llenar los textbox con el cliente selecciondo mediante la id del mismo. /// </summary> /// <param name="id">variable de tipo entera</param> public void cargarCliente(int id) { Cliente nCliente = ManejoCliente.getById(id); // Se busca el cliente mediante la id y se guarda en un modelo tipo cliente // se asigna a los textbox los valores segun los datos del modelo cliente pkCliente = nCliente.idCliente; this.txtRFC.Text = nCliente.sRfc; this.txtNombre.Text = nCliente.sNombre; this.txtDireccion.Text = nCliente.sCalle; this.txtTelefono.Text = nCliente.sTelMovil; this.cmbFormaDePago.SelectedIndex = Convert.ToInt16(nCliente.sTipoPago) - 1; this.txtCondicionesDePago.Text = nCliente.sConPago; } /// <summary> /// Funcion encargada de crear el archivo xml con los datos necesarios para la facturacion. /// </summary> /// public void GenerarFactura() { #region VARIABLES NameFileXML = "ComprobanteSinTimbrar.xml"; string MESPATH = @"C:\SiscomSoft\Facturas\XML\" + DateTime.Now.ToString("MMMM") + "," + DateTime.Now.Year; Sucursal nSucursal = ManejoSucursal.getById(Convert.ToInt32(cmbSucursal.SelectedValue)); Comprobante cfdi = new Comprobante(); Certificado mCertificado = ManejoCertificado.getById(nSucursal.certificado_id); Preferencia mPreferencia = ManejoPreferencia.getById(nSucursal.preferencia_id); Empresa mEmpresa = ManejoEmpresa.getById(nSucursal.empresa_id); X509Certificate2 myCer = new X509Certificate2(mCertificado.sRutaArch + @"\" + mCertificado.sArchCer); if (File.Exists(MESPATH + @"\" + NameFileXML)) { File.Delete(MESPATH + @"\" + NameFileXML); NameFileXML = NameFileXML = txtRFC.Text + "_" + mPreferencia.sNumSerie + "_" + DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + ".xml"; } if (NameFileXML == "ComprobanteSinTimbrar.xml") { FechaFactura = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"); } if (!Directory.Exists(MESPATH)) { Directory.CreateDirectory(MESPATH); } #endregion #region RELACIONADOS //cfdi.CfdiRelacionados = new ComprobanteCfdiRelacionados(); //cfdi.CfdiRelacionados.CfdiRelacionado = new ComprobanteCfdiRelacionadosCfdiRelacionado[1]; //cfdi.CfdiRelacionados.CfdiRelacionado[0].UUID = " "; #region TIPO RELACION //if (cmbFormaDePago.SelectedIndex == 0) //{ // cfdi.CfdiRelacionados.TipoRelacion = c_TipoRelacion.Item02; //} //else if (cmbFormaDePago.SelectedIndex == 3) //{ // cfdi.CfdiRelacionados.TipoRelacion = c_TipoRelacion.Item01; //} #endregion #endregion #region DATOS GENERALES cfdi.Version = "3.3"; cfdi.Serie = mPreferencia.sNumSerie; cfdi.Folio = txtFolio.Text; cfdi.Fecha = FechaFactura; #region SELLO cfdi.Sello = Sello; #endregion #region FORMA DE PAGO if (this.cmbFormaDePago.SelectedIndex == 0) { cfdi.FormaPago = c_FormaPago.Item01; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 1) { cfdi.FormaPago = c_FormaPago.Item02; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 2) { cfdi.FormaPago = c_FormaPago.Item03; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 3) { cfdi.FormaPago = c_FormaPago.Item04; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 4) { cfdi.FormaPago = c_FormaPago.Item05; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 5) { cfdi.FormaPago = c_FormaPago.Item06; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 6) { cfdi.FormaPago = c_FormaPago.Item08; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 7) { cfdi.FormaPago = c_FormaPago.Item12; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 8) { cfdi.FormaPago = c_FormaPago.Item13; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 9) { cfdi.FormaPago = c_FormaPago.Item14; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 10) { cfdi.FormaPago = c_FormaPago.Item15; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 11) { cfdi.FormaPago = c_FormaPago.Item17; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 12) { cfdi.FormaPago = c_FormaPago.Item23; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 13) { cfdi.FormaPago = c_FormaPago.Item24; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 14) { cfdi.FormaPago = c_FormaPago.Item25; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 15) { cfdi.FormaPago = c_FormaPago.Item26; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 16) { cfdi.FormaPago = c_FormaPago.Item27; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 17) { cfdi.FormaPago = c_FormaPago.Item28; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 18) { cfdi.FormaPago = c_FormaPago.Item29; cfdi.FormaPagoSpecified = true; } else if (this.cmbFormaDePago.SelectedIndex == 19) { cfdi.FormaPago = c_FormaPago.Item99; cfdi.FormaPagoSpecified = true; } #endregion #region CERTIFICADO cfdi.NoCertificado = Encoding.Default.GetString(myCer.GetSerialNumber()); cfdi.Certificado = Convert.ToBase64String(myCer.RawData); #endregion #region CONDICIONES DE PAGO cfdi.CondicionesDePago = txtCondicionesDePago.Text; #endregion cfdi.SubTotal = Convert.ToDecimal(lblSubTotal.Text); #region DESCUENTO decimal descuento = 0; decimal descuentoex = 0; decimal TotalDescuento = 0; foreach (DataGridViewRow rDesc in dgvProductos.Rows) { descuento += Convert.ToDecimal(rDesc.Cells[19].Value); descuentoex += Convert.ToDecimal(rDesc.Cells[20].Value); } TotalDescuento = descuento + descuentoex; if (TotalDescuento > 0) { cfdi.Descuento = TotalDescuento; cfdi.DescuentoSpecified = true; } #endregion #region MONEDA Y TIPO DE CAMBIO if (cmbMoneda.SelectedIndex == 0) { cfdi.Moneda = c_Moneda.MXN; cfdi.TipoCambio = 1; cfdi.TipoCambioSpecified = true; } else if (cmbMoneda.SelectedIndex == 1) { cfdi.Moneda = c_Moneda.USD; cfdi.TipoCambio = Convert.ToDecimal(nSucursal.sTipoCambio); cfdi.TipoCambioSpecified = true; } #endregion cfdi.Total = Convert.ToDecimal(lblTotal.Text); #region TIPO DE COMPROBANTE if (cmbTipoDeComprobante.SelectedIndex == 0) { cfdi.TipoDeComprobante = c_TipoDeComprobante.I; } else if (cmbTipoDeComprobante.SelectedIndex == 1) { cfdi.TipoDeComprobante = c_TipoDeComprobante.E; } else if (cmbTipoDeComprobante.SelectedIndex == 2) { cfdi.TipoDeComprobante = c_TipoDeComprobante.N; } else if (cmbTipoDeComprobante.SelectedIndex == 3) { cfdi.TipoDeComprobante = c_TipoDeComprobante.T; } else if (cmbTipoDeComprobante.SelectedIndex == 4) { cfdi.TipoDeComprobante = c_TipoDeComprobante.P; } #endregion #region METODO DE PAGO //TODO: Poner el metodo de pago que el cliente tiene guardado. if (cmbMetodoDePago.SelectedIndex == 0) { cfdi.MetodoPago = c_MetodoPago.PUE; cfdi.MetodoPagoSpecified = true; } else if (cmbMetodoDePago.SelectedIndex == 1) { cfdi.MetodoPago = c_MetodoPago.PPD; cfdi.MetodoPagoSpecified = true; } #endregion #region LUGAR DE EXPEDICION cfdi.LugarExpedicion = nSucursal.iCodPostal.ToString(); #endregion //cfdi.Confirmacion = "ECVH1"; #endregion #region DATOS EMISOR cfdi.Emisor = new ComprobanteEmisor(); cfdi.Emisor.Rfc = FrmMenuMain.uHelper.usuario.sRfc; cfdi.Emisor.Nombre = FrmMenuMain.uHelper.usuario.sNombre; #region REGIMEN FISCAL if (mEmpresa.sRegFiscal == 1.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item601; } else if (mEmpresa.sRegFiscal == 2.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item603; } else if (mEmpresa.sRegFiscal == 3.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item605; } else if (mEmpresa.sRegFiscal == 4.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item606; } else if (mEmpresa.sRegFiscal == 5.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item608; } else if (mEmpresa.sRegFiscal == 6.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item609; } else if (mEmpresa.sRegFiscal == 7.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item610; } else if (mEmpresa.sRegFiscal == 8.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item611; } else if (mEmpresa.sRegFiscal == 9.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item612; } else if (mEmpresa.sRegFiscal == 10.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item614; } else if (mEmpresa.sRegFiscal == 11.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item616; } else if (mEmpresa.sRegFiscal == 12.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item620; } else if (mEmpresa.sRegFiscal == 13.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item621; } else if (mEmpresa.sRegFiscal == 14.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item622; } else if (mEmpresa.sRegFiscal == 15.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item623; } else if (mEmpresa.sRegFiscal == 16.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item624; } else if (mEmpresa.sRegFiscal == 17.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item628; } else if (mEmpresa.sRegFiscal == 18.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item607; } else if (mEmpresa.sRegFiscal == 19.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item629; } else if (mEmpresa.sRegFiscal == 20.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item630; } else if (mEmpresa.sRegFiscal == 21.ToString()) { cfdi.Emisor.RegimenFiscal = c_RegimenFiscal.Item615; } #endregion #endregion #region DATOS RECEPTOR cfdi.Receptor = new ComprobanteReceptor(); cfdi.Receptor.Rfc = txtRFC.Text; cfdi.Receptor.Nombre = txtNombre.Text; #region UsoCFDI if (this.cmbUsoCFDI.SelectedIndex == 0) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.G01; } else if (this.cmbUsoCFDI.SelectedIndex == 1) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.G02; } else if (this.cmbUsoCFDI.SelectedIndex == 2) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.G03; } else if (this.cmbUsoCFDI.SelectedIndex == 3) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I01; } else if (this.cmbUsoCFDI.SelectedIndex == 4) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I02; } else if (this.cmbUsoCFDI.SelectedIndex == 5) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I03; } else if (this.cmbUsoCFDI.SelectedIndex == 6) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I04; } else if (this.cmbUsoCFDI.SelectedIndex == 7) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I05; } else if (this.cmbUsoCFDI.SelectedIndex == 8) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I06; } else if (this.cmbUsoCFDI.SelectedIndex == 9) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I07; } else if (this.cmbUsoCFDI.SelectedIndex == 10) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.I08; } else if (this.cmbUsoCFDI.SelectedIndex == 11) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D01; } else if (this.cmbUsoCFDI.SelectedIndex == 12) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D02; } else if (this.cmbUsoCFDI.SelectedIndex == 13) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D03; } else if (this.cmbUsoCFDI.SelectedIndex == 14) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D04; } else if (this.cmbUsoCFDI.SelectedIndex == 15) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D05; } else if (this.cmbUsoCFDI.SelectedIndex == 16) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D06; } else if (this.cmbUsoCFDI.SelectedIndex == 17) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D07; } else if (this.cmbUsoCFDI.SelectedIndex == 18) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D08; } else if (this.cmbUsoCFDI.SelectedIndex == 19) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D09; } else if (this.cmbUsoCFDI.SelectedIndex == 20) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.D10; } else if (this.cmbUsoCFDI.SelectedIndex == 21) { cfdi.Receptor.UsoCFDI = c_UsoCFDI.P01; } #endregion #endregion #region Conceptos cfdi.Conceptos = new ComprobanteConcepto[dgvProductos.Rows.Count - 1]; int c = 0; int it = 0; int ir = 0; int totalTraslado = 0; int totalRetenido = 0; foreach (DataGridViewRow row in dgvProductos.Rows) { if (!row.IsNewRow) { cfdi.Conceptos[c] = new ComprobanteConcepto(); cfdi.Conceptos[c].ClaveProdServ = row.Cells[1].Value.ToString(); cfdi.Conceptos[c].Cantidad = Convert.ToInt32(row.Cells[6].Value); cfdi.Conceptos[c].ClaveUnidad = row.Cells[22].Value.ToString(); cfdi.Conceptos[c].Unidad = row.Cells[4].Value.ToString(); cfdi.Conceptos[c].Descripcion = row.Cells[2].Value.ToString(); cfdi.Conceptos[c].ValorUnitario = Convert.ToDecimal(row.Cells[5].Value); cfdi.Conceptos[c].Importe = Convert.ToDecimal(row.Cells[7].Value); #region Impuestos List<ImpuestoProducto> mImpuesto = ManejoImpuestoProducto.getById(Convert.ToInt32(row.Cells[0].Value)); if (mImpuesto.Count != 0) { cfdi.Conceptos[c].Impuestos = new ComprobanteConceptoImpuestos(); cfdi.Conceptos[c].Impuestos.Traslados = new ComprobanteConceptoImpuestosTraslado[mImpuesto.Count]; foreach (ImpuestoProducto rImpuesto in mImpuesto) { var impuesto = ManejoImpuesto.getById(rImpuesto.impuesto_id); #region TRASLADO if (impuesto.sTipoImpuesto == "TRASLADO") { // IVA if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(16.00)) { cfdi.Conceptos[c].Impuestos.Traslados[it] = new ComprobanteConceptoImpuestosTraslado(); cfdi.Conceptos[c].Impuestos.Traslados[it].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Traslados[it].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Traslados[it].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuota = tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuotaSpecified = true; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].Importe = importe; cfdi.Conceptos[c].Impuestos.Traslados[it].ImporteSpecified = true; TOTALTIVA16 += importe; totalTraslado += 1; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(11.00)) { cfdi.Conceptos[c].Impuestos.Traslados[it] = new ComprobanteConceptoImpuestosTraslado(); cfdi.Conceptos[c].Impuestos.Traslados[it].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Traslados[it].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Traslados[it].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuota = tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuotaSpecified = true; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].Importe = importe; cfdi.Conceptos[c].Impuestos.Traslados[it].ImporteSpecified = true; TOTALTIVA11 += importe; totalTraslado += 1; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(4.00)) { cfdi.Conceptos[c].Impuestos.Traslados[it] = new ComprobanteConceptoImpuestosTraslado(); cfdi.Conceptos[c].Impuestos.Traslados[it].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Traslados[it].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Traslados[it].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuota = tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuotaSpecified = true; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].Importe = importe; cfdi.Conceptos[c].Impuestos.Traslados[it].ImporteSpecified = true; TOTALTIVA4 += importe; totalTraslado += 1; } //IEPS else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(53.00)) { cfdi.Conceptos[c].Impuestos.Traslados[it] = new ComprobanteConceptoImpuestosTraslado(); cfdi.Conceptos[c].Impuestos.Traslados[it].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Traslados[it].Impuesto = c_Impuesto.Item003; cfdi.Conceptos[c].Impuestos.Traslados[it].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuota = tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuotaSpecified = true; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].Importe = importe; cfdi.Conceptos[c].Impuestos.Traslados[it].ImporteSpecified = true; TOTALTIEPS53 += importe; totalTraslado += 1; } else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(30.00)) { cfdi.Conceptos[c].Impuestos.Traslados[it] = new ComprobanteConceptoImpuestosTraslado(); cfdi.Conceptos[c].Impuestos.Traslados[it].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Traslados[it].Impuesto = c_Impuesto.Item003; cfdi.Conceptos[c].Impuestos.Traslados[it].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuota = tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuotaSpecified = true; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].Importe = importe; cfdi.Conceptos[c].Impuestos.Traslados[it].ImporteSpecified = true; TOTALTIEPS30 += importe; totalTraslado += 1; } else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(26.50)) { cfdi.Conceptos[c].Impuestos.Traslados[it] = new ComprobanteConceptoImpuestosTraslado(); cfdi.Conceptos[c].Impuestos.Traslados[it].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Traslados[it].Impuesto = c_Impuesto.Item003; cfdi.Conceptos[c].Impuestos.Traslados[it].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuota = tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].TasaOCuotaSpecified = true; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Traslados[it].Importe = importe; cfdi.Conceptos[c].Impuestos.Traslados[it].ImporteSpecified = true; TOTALTIEPS26 += importe; totalTraslado += 1; } } #endregion it += 1; } cfdi.Conceptos[c].Impuestos.Retenciones = new ComprobanteConceptoImpuestosRetencion[mImpuesto.Count]; foreach (ImpuestoProducto rImpuesto in mImpuesto) { var impuesto = ManejoImpuesto.getById(rImpuesto.impuesto_id); #region RETENIDO if (impuesto.sTipoImpuesto == "RETENIDO") { // IVA if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(16.00)) { cfdi.Conceptos[c].Impuestos.Retenciones[ir] = new ComprobanteConceptoImpuestosRetencion(); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TasaOCuota = tasa; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Retenciones[ir].Importe = importe; TOTALRIVA16 += importe; totalRetenido += 1; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(10.67)) { cfdi.Conceptos[c].Impuestos.Retenciones[ir] = new ComprobanteConceptoImpuestosRetencion(); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TasaOCuota = tasa; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Retenciones[ir].Importe = importe; TOTALRIVA1067 += importe; totalRetenido += 1; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(7.33)) { cfdi.Conceptos[c].Impuestos.Retenciones[ir] = new ComprobanteConceptoImpuestosRetencion(); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TasaOCuota = tasa; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Retenciones[ir].Importe = importe; TOTALRIVA733 += importe; totalRetenido += 1; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(4.00)) { cfdi.Conceptos[c].Impuestos.Retenciones[ir] = new ComprobanteConceptoImpuestosRetencion(); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Impuesto = c_Impuesto.Item002; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TasaOCuota = tasa; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Retenciones[ir].Importe = importe; TOTALRIVA4 += importe; totalRetenido += 1; } //ISR else if (impuesto.sImpuesto == "ISR" && impuesto.dTasaImpuesto == Convert.ToDecimal(10.00)) { cfdi.Conceptos[c].Impuestos.Retenciones[ir] = new ComprobanteConceptoImpuestosRetencion(); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Base = Convert.ToDecimal(row.Cells[21].Value); cfdi.Conceptos[c].Impuestos.Retenciones[ir].Impuesto = c_Impuesto.Item001; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TipoFactor = c_TipoFactor.Tasa; decimal tasa = impuesto.dTasaImpuesto / 100; cfdi.Conceptos[c].Impuestos.Retenciones[ir].TasaOCuota = tasa; decimal valorUnitario = Convert.ToDecimal(row.Cells[5].Value); decimal importe = valorUnitario * tasa; cfdi.Conceptos[c].Impuestos.Retenciones[ir].Importe = importe; TOTALRISR10 += importe; totalRetenido += 1; } } #endregion ir += 1; } } #endregion c += 1; } } #endregion #region IMPUESTOS TOTALES //cfdi.Impuestos = new ComprobanteImpuestos(); //cfdi.Impuestos.TotalImpuestosTrasladados = TIVA16 + TIVA11 + TIVA4 + TIEPS53 + TIEPS30 + TIEPS26; //cfdi.Impuestos.TotalImpuestosTrasladadosSpecified = true; //cfdi.Impuestos.TotalImpuestosRetenidos = RIVA16 + RIVA1067 + RIVA733 + RIVA4 + RISR10; //cfdi.Impuestos.TotalImpuestosRetenidosSpecified = true; #endregion #region Complemento cfdi.Complemento = new ComprobanteComplemento[1]; #endregion #region NAMESPACES XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces(); xmlNameSpace.Add("cfdi", "http://www.sat.gob.mx/cfd/3"); xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); #endregion #region GUARDAR XML XmlSerializer xmlSerialize = new XmlSerializer(typeof(Comprobante)); XmlTextWriter xmlTextWriter = new XmlTextWriter(MESPATH + @"\" + NameFileXML, Encoding.UTF8); xmlTextWriter.Formatting = Formatting.Indented; xmlSerialize.Serialize(xmlTextWriter, cfdi, xmlNameSpace); xmlTextWriter.Close(); #endregion } /// <summary> /// Funcion encargada de crear la cadena original y el sello necesarios para el archivo xml. /// </summary> /// <param name="NameFileXML">variable tipo string, utilizada para establecer el nombre del archivo xml actual.</param> public void CrearSelloFinkok(string NameFileXML) { Sucursal nSucursal = ManejoSucursal.getById(Convert.ToInt32(cmbSucursal.SelectedValue)); // Se busca la sucursal seleccionada mediante la id de la misma y se guarda en un modelo tipo sucursal. Certificado mCertificado = ManejoCertificado.getById(nSucursal.certificado_id); // Se busca el certificado mediante la llave foranea de la sucursal seleccionada y se guarda en un modelo de tipo certificado. X509Certificate2 m_cer = new X509Certificate2(mCertificado.sRutaArch + @"\" + mCertificado.sArchCer); // Se lee el certificado asignado a la sucursal mediante su ruta y nombre. string rutaXSLT = @"C:\SiscomSoft\cadenaoriginal_3_3.xslt"; // Se asigna el valor a la variable rutaXSLT con la ruta completa del archivo xslt de la cadena original. string MESPATH = @"C:\SiscomSoft\Facturas\XML\" + DateTime.Now.ToString("MMMM") + "," + DateTime.Now.Year; // Se asigna el valor a la variable MESPATH con la ruta de la carpeta del mes en donde se guardo el archivo xml string rutaXML = MESPATH + @"\" + NameFileXML; // Se asigna el valor a la variable rutaXML con la ruta completa del archivo xml String pass = mCertificado.sContrasena; //Contraseña de la llave privada String llave = mCertificado.sRutaArch + @"\" + mCertificado.sArchkey; //Archivo de la llave privada byte[] llave2 = File.ReadAllBytes(llave); // Convertimos el archivo anterior a byte byte[] bytesFirmados; // Cargar XML XPathDocument xml = new XPathDocument(rutaXML); // Cargar XSLT XslCompiledTransform transformador = new XslCompiledTransform(); transformador.Load(rutaXSLT); // Procesamiento StringWriter str = new StringWriter(); XmlTextWriter cad = new XmlTextWriter(str); transformador.Transform(rutaXML, cad); //Resultado string result = str.ToString(); // Se valida el tamaño del certificado asignado a la empresa. if (m_cer.PublicKey.Key.KeySize == 2048) { #region SHA-256 //1) Desencriptar la llave privada, el primer parámetro es la contraseña de llave privada y el segundo es la llave privada en formato binario. Org.BouncyCastle.Crypto.AsymmetricKeyParameter asp = Org.BouncyCastle.Security.PrivateKeyFactory.DecryptKey(pass.ToCharArray(), llave2); //2) Convertir a parámetros de RSA Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters key = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)asp; //3) Crear el firmador con SHA256 Org.BouncyCastle.Crypto.ISigner sig = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA-256withRSA"); //4) Inicializar el firmador con la llave privada sig.Init(true, key); // 5) Pasar la cadena original a formato binario byte[] bytes = Encoding.UTF8.GetBytes(result); // 6) Encriptar sig.BlockUpdate(bytes, 0, bytes.Length); bytesFirmados = sig.GenerateSignature(); // 7) Finalmente obtenemos el sello Sello = Convert.ToBase64String(bytesFirmados); #endregion } else if (m_cer.PublicKey.Key.KeySize == 2048) { #region SHA-1 //1) Desencriptar la llave privada, el primer parámetro es la contraseña de llave privada y el segundo es la llave privada en formato binario. Org.BouncyCastle.Crypto.AsymmetricKeyParameter asp = Org.BouncyCastle.Security.PrivateKeyFactory.DecryptKey(pass.ToCharArray(), llave2); //2) Convertir a parámetros de RSA Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters key = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)asp; //3) Crear el firmador con SHA1 Org.BouncyCastle.Crypto.ISigner sig = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA1withRSA"); //4) Inicializar el firmador con la llave privada sig.Init(true, key); // 5) Pasar la cadena original a formato binario byte[] bytes = Encoding.UTF8.GetBytes(result); // 6) Encriptar sig.BlockUpdate(bytes, 0, bytes.Length); bytesFirmados = sig.GenerateSignature(); // 7) Finalmente obtenemos el sello Sello = Convert.ToBase64String(bytesFirmados); #endregion } } /// <summary> /// Funcion encargada de guardar todos los datos del archivo xml en la tabla factura y detallefactura de la base de datos. /// </summary> public void GuardarFactura() { Factura nFactura = new Factura(); DetalleFactura nDetalleFactura = new DetalleFactura(); // Se le da valor a los parametros del metodo de tipo factura. nFactura.sFolio = txtFolio.Text; nFactura.dtFecha = DateTime.Now; nFactura.usuario_id = pkCliente; nFactura.sUsoCfdi = cmbUsoCFDI.Text; nFactura.sMoneda = cmbMoneda.Text; nFactura.sFormaPago = cmbFormaDePago.Text; nFactura.sMetodoPago = cmbMetodoDePago.Text; nFactura.sTipoCompro = cmbTipoDeComprobante.Text; nFactura.sucursal_id = Convert.ToInt32(cmbSucursal.SelectedValue); nFactura.usuario_id = FrmMenuMain.uHelper.usuario.idUsuario; ManejoFacturacion.Guardar(nFactura); // Se llama a la funcion guardar que esta en ManejoFacturacion y se le pasa una variable de tipo factura. // Se recorren las filas del DataGridView foreach (DataGridViewRow row in dgvProductos.Rows) { if (!row.IsNewRow) // Se valida que la fila no sea para nuevos registros. { // Se le da valor a los parametros del modelo de tipo detalleventas. nDetalleFactura.producto_id = Convert.ToInt32(row.Cells[0].Value); nDetalleFactura.sClave = row.Cells[1].Value.ToString(); nDetalleFactura.sDescripcion = row.Cells[2].Value.ToString(); nDetalleFactura.dPreUnitario = Convert.ToDecimal(row.Cells[5].Value); nDetalleFactura.iCantidad = Convert.ToInt32(row.Cells[6].Value); nDetalleFactura.factura_id = nFactura.idFactura; ManejoDetalleFactura.Guardar(nDetalleFactura); // Se llama a la funcion Guardar que esta en ManejoDetalleFactura y se le pasa una variable de tipo detallefactura. } } } /// <summary> /// Funcion encargada de limpiar los controles de la vista y obtener un nuevo folio. /// </summary> public void Clear() { txtCondicionesDePago.Clear(); txtDireccion.Clear(); txtFolio.Clear(); txtNombre.Clear(); txtRFC.Clear(); txtTelefono.Clear(); txtFolio.Text = ManejoFacturacion.Folio(); dgvProductos.Rows.Clear(); btnBorrar.Visible = false; pkCliente = 0; lblSubTotal.Text = "0"; lblTotal.Text = "0"; TIVA16 = 0; TIVA11 = 0; TIVA4 = 0; TIEPS53 = 0; TIEPS30 = 0; TIEPS26 = 0; RIVA16 = 0; RIVA1067 = 0; RIVA733 = 0; RIVA4 = 0; RISR10 = 0; } #endregion #region PANEL GENERAL private void btnBussines_Click(object sender, EventArgs e) { pnlCreditNotes.Visible = false; pnlFacturacion.Visible = true; } private void btnCustomer_Click(object sender, EventArgs e) { pnlFacturacion.Visible = false; pnlCreditNotes.Visible = true; } private void btnCreateBill_Click(object sender, EventArgs e) { pnlCreateFactura.Visible = true; txtRFC.Focus(); } private void btnCancelarBill_Click(object sender, EventArgs e) { pnlCreateFactura.Visible = false; } #region MOUSE CLICK private void btnCreateBill_MouseClick(object sender, MouseEventArgs e) { btnCancelarBill.BackColor = Color.White; btnCancelarBill.ForeColor = Color.Black; btnCreateBill.BackColor = Color.DarkCyan; btnCreateBill.ForeColor = Color.White; } private void btnCancelarBill_MouseClick(object sender, MouseEventArgs e) { btnCreateBill.BackColor = Color.White; btnCreateBill.ForeColor = Color.Black; btnCancelarBill.BackColor = Color.DarkCyan; btnCancelarBill.ForeColor = Color.White; } #endregion #endregion #region CREATE BILL private void cmbSucursal_SelectedIndexChanged(object sender, EventArgs e) { } /// <summary> /// En este vento se escoje la moneda y el tipo de cambio. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmbMoneda_SelectedIndexChanged(object sender, EventArgs e) { if (cmbMoneda.SelectedIndex == 0) // Se valida si el valor del cmbMoneda es 0 para asignar el tipo de cambio en pesos. { lbltotaldolares.Visible = false; lblTotalDolar.Visible = false; Dolar = false; } else if (cmbMoneda.SelectedIndex == 1) // Se valida si el valor del cmbMoneda es 1 para asignar el tipo de cambio en dolares. { decimal total = 0; decimal TotalDolar = 0; Sucursal mSucursal = ManejoSucursal.getById(FrmMenuMain.uHelper.usuario.sucursal_id); // se busca la sucursal mediante la llave foranea que tiene el usuario logeado y se guarda en un modelo de tipo sucursal if (mSucursal.sTipoCambio != null) // Se valida que el tipo de cambio este vacion en el { foreach (DataGridViewRow row in dgvProductos.Rows) // Se recorren las filas del DataGridView { total += Convert.ToDecimal(row.Cells[7].Value); // Se acomula el valor de la variabe local Total segun se recorre la columna 7 del DataGridView } decimal TipoCambio = Convert.ToDecimal(mSucursal.sTipoCambio); // Se le da el valor a la variabe TipoCambio segun los datos del modelo sucursal TotalDolar = (total * 1) / TipoCambio; // Se le da el valor a la variabe TotalDolar segun el resultado del calculo lbltotaldolares.Visible = true; // Se cambia la propiedad visible del lbltotaldolares para que se muestre en la vista lblTotalDolar.Visible = true; // Se cambia la propiedad visible del lblTotalDolar para que se muestre en la vista lblTotalDolar.Text = TotalDolar.ToString("N"); // Se le da el valor al lblTotalDolar segun el valor de la variable TotalDolar Dolar = true; // Se cambia el valor de la variable global dolar a falso } else { MessageBox.Show("Antes de realizar esta acción tiene que definir el tipo de cambio para su sucursal."); } } } /// <summary> /// Boton que utiliza para mandar llamar la vista de buscar cliente y seleccinar un cliente. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBuscarCliente_Click(object sender, EventArgs e) { FrmBuscarCiente v = new FrmBuscarCiente(this); v.ShowDialog(); } /// <summary> /// Boton que utiliza para mandar llamar la vista de buscar productos y seleccinar un producto. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBuscarProductos_Click(object sender, EventArgs e) { FrmBuscarProductos v = new FrmBuscarProductos(this); v.ShowDialog(); } /// <summary> /// Este evento se utilizo para recalcular el importe de los productos segun la cantidad. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvProductos_CellEndEdit(object sender, DataGridViewCellEventArgs e) { string columna = dgvProductos.Columns[e.ColumnIndex].Name; // Se asigna el nombre de la columna que se modifico a la variable columna. if (columna == "Cantidad") // Se valida que la variable columna sea "Cantidad" { if (dgvProductos.CurrentRow != null) // Se valida que haya una fila seleccionada en el DataGridView { if (!dgvProductos.CurrentRow.IsNewRow) // Se valida que la fila seleccinada no sea para ingresar valores nuevos { decimal Cantidad = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[6].Value); // Se le da valor a la variable Cantidad con el valor que se encuentra en la columna 6 del DataGridView if (Cantidad != 0) // Se valida que el valor de la variable Cantidad no sea 0 { if (dgvProductos.CurrentRow.Cells[0].Value != null) // Se valida que el valor de la columna 0 del DataGridView no este vacio, sino la fila seleccionada sera removida { Producto nProducto = ManejoProducto.getById(Convert.ToInt32(dgvProductos.CurrentRow.Cells[0].Value)); // Se busca el producto segun el valor que tenga la columna 0 del DataGridView { #region VARIABLES decimal Subtotal = 0; decimal Total = 0; decimal TipoCambio = 0; decimal TotalDolar = 0; decimal PrecioUnitario = nProducto.dCosto; decimal TTasaImpuestoIVA16 = 0; decimal TTasaImpuestoIVA11 = 0; decimal TTasaImpuestoIVA4 = 0; decimal TTasaImpuestoIEPS53 = 0; decimal TTasaImpuestoIEPS26 = 0; decimal TTasaImpuestoIEPS30 = 0; decimal RTasaImpuestoIVA16 = 0; decimal RTasaImpuestoIVA1067 = 0; decimal RTasaImpuestoIVA733 = 0; decimal RTasaImpuestoIVA4 = 0; decimal RTasaImpuestoISR10 = 0; decimal TasaDescuento = 0; decimal TasaDescuentoExtra = 0; decimal Importe = 0; decimal ImporteWithoutExtras = 0; decimal ImporteWithTImpuestoIVA16 = 0; decimal ImporteWithTImpuestoIVA11 = 0; decimal ImporteWithTImpuestoIVA4 = 0; decimal ImporteWithTImpuestosIEPS53 = 0; decimal ImporteWithTImpuestosIEPS30 = 0; decimal ImporteWithTImpuestosIEPS26 = 0; decimal ImporteWithRImpuestoIVA16 = 0; decimal ImporteWithRImpuestoIVA1067 = 0; decimal ImporteWithRImpuestoIVA733 = 0; decimal ImporteWithRImpuestosIVA4 = 0; decimal ImporteWithRImpuestosISR10 = 0; decimal PreUnitarioWithDescuento = 0; decimal PriceForLot = 0; decimal Descuento = 0; decimal DescuentoExtra = 0; #endregion #region Impuestos List<ImpuestoProducto> mImpuesto = ManejoImpuestoProducto.getById(Convert.ToInt32(nProducto.idProducto)); // Se buscan todos los impuestos que tiene el producto mediante la id del producto y se guardan en una ista // Se leen los impuestos que tiene guardada la lista foreach (ImpuestoProducto rImpuesto in mImpuesto) { var impuesto = ManejoImpuesto.getById(rImpuesto.impuesto_id); // Se busca el impuesto mediante el id que esta guardado en la lista #region TRASLADO // Se valida que el tipo de impuesto sea "TRASLADO" if (impuesto.sTipoImpuesto == "TRASLADO") { // // Se valida que el impuesto sea "IVA" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(16.00)) { TTasaImpuestoIVA16 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(11.00)) { TTasaImpuestoIVA11 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(4.00)) { TTasaImpuestoIVA4 += impuesto.dTasaImpuesto; } // Se valida que el impuesto sea "IEPS" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(53.00)) { TTasaImpuestoIEPS53 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(30.00)) { TTasaImpuestoIEPS30 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IEPS" && impuesto.dTasaImpuesto == Convert.ToDecimal(26.50)) { TTasaImpuestoIEPS26 += impuesto.dTasaImpuesto; } } #endregion #region RETENIDO // Se valida que el tipo de impuesto sea "RETENIDO" if (impuesto.sTipoImpuesto == "RETENIDO") { // Se valida que el impuesto sea "IVA" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(16.00)) { RTasaImpuestoIVA16 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(10.67)) { RTasaImpuestoIVA1067 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(7.33)) { RTasaImpuestoIVA733 += impuesto.dTasaImpuesto; } else if (impuesto.sImpuesto == "IVA" && impuesto.dTasaImpuesto == Convert.ToDecimal(4.00)) { RTasaImpuestoIVA4 += impuesto.dTasaImpuesto; } // Se valida que el impuesto sea "ISR" y que la tasa de impuesto sea la requerida para poder guardar las cantidades en las variables else if (impuesto.sImpuesto == "ISR" && impuesto.dTasaImpuesto == Convert.ToDecimal(10.00)) { RTasaImpuestoISR10 += impuesto.dTasaImpuesto; } } #endregion } #endregion #region Descuentos List<DescuentoProducto> mDescuento = ManejoDescuentoProducto.getById(Convert.ToInt32(nProducto.idProducto)); // Se buscan todos los descuentos que tiene el producto mediante la id del producto y se guardan en una ista // Se leen los descuentos que tiene guardada la lista foreach (DescuentoProducto rDescuento in mDescuento) { var descuento = ManejoDescuento.getById(rDescuento.descuento_id); // Se busca el descuento mediante el id que esta guardado en la lista TasaDescuento = descuento.dTasaDesc; // Se le da el valor a la variabe TasaDescuento segun los datos del modelo DescuentoProducto TasaDescuentoExtra = descuento.dTasaDescEx; // Se le da el valor a la variabe TasaDescuentoExtra segun los datos del modelo DescuentoProducto } #endregion #region CALCULOS // Se valida que la TasaDescuento no sea 0 para poder hacer el calculo correspondiente if (TasaDescuento != 0) { Descuento = PrecioUnitario * (TasaDescuento / 100); } // Se valida que la TasaDescuentoExtra no sea 0 para poder hacer el calculo correspondiente if (TasaDescuentoExtra != 0) { DescuentoExtra = PrecioUnitario * (TasaDescuentoExtra / 100); } ImporteWithoutExtras += Cantidad * PrecioUnitario; // Se le da el valor a la variabe ImporteWithoutExtras segun el resultado del calculo PreUnitarioWithDescuento = PrecioUnitario - Descuento - DescuentoExtra; // Se le da el valor a la variabe PreUnitarioWithDescuento segun el resultado del calculo PriceForLot = Cantidad * PreUnitarioWithDescuento; // Se le da el valor a la variabe PriceForLot segun el resultado del calculo #region TRASLADO ImporteWithTImpuestoIVA16 = PriceForLot * (TTasaImpuestoIVA16 / 100); // Se le da el valor a la variabe ImporteWithTImpuestoIVA16 segun el resultado del calculo TIVA16 = ImporteWithTImpuestoIVA16; // Se le da el valor a la variabe global TIVA16 segun el valor de la variable ImporteWithTImpuestoIVA16 dgvProductos.CurrentRow.Cells[8].Value = TIVA16; // Se le da el valor de la variable gloval TIVA16 a la columna 8 de la fila clonada del DataGridView ImporteWithTImpuestoIVA11 = PriceForLot * (TTasaImpuestoIVA11 / 100); // Se le da el valor a la variabe ImporteWithTImpuestoIVA11 segun el resultado del calculo TIVA11 = ImporteWithTImpuestoIVA11; // Se le da el valor a la variabe global TIVA11 segun el valor de la variable ImporteWithTImpuestoIVA11 dgvProductos.CurrentRow.Cells[9].Value = TIVA11; // Se le da el valor de la variable gloval TIVA11 a la columna 9 de la fila clonada del DataGridView ImporteWithTImpuestoIVA4 = PriceForLot * (TTasaImpuestoIVA4 / 100); // Se le da el valor a la variabe ImporteWithTImpuestoIVA4 segun el resultado del calculo TIVA4 = ImporteWithTImpuestoIVA4; // Se le da el valor a la variabe global TIVA4 segun el valor de la variable ImporteWithTImpuestoIVA dgvProductos.CurrentRow.Cells[10].Value = TIVA4; // Se le da el valor de la variable gloval TIVA4 a la columna 10 de la fila clonada del DataGridView ImporteWithTImpuestosIEPS53 = PriceForLot * (TTasaImpuestoIEPS53 / 100); // Se le da el valor a la variabe ImporteWithTImpuestosIEPS53 segun el resultado del calculo TIEPS53 = ImporteWithTImpuestosIEPS53; // Se le da el valor a la variabe global TIEPS53 segun el valor de la variable ImporteWithTImpuestoIEPS53 dgvProductos.CurrentRow.Cells[11].Value = TIEPS53; // Se le da el valor de la variable gloval TEPS53 a la columna 11 de la fila clonada del DataGridView ImporteWithTImpuestosIEPS30 = PriceForLot * (TTasaImpuestoIEPS30 / 100); // Se le da el valor a la variabe ImporteWithTImpuestosIEPS30 segun el resultado del calculo TIEPS30 = ImporteWithTImpuestosIEPS30; // Se le da el valor a la variabe global TIEPS30 segun el valor de la variable ImporteWithTImpuestoIEPS30 dgvProductos.CurrentRow.Cells[12].Value = TIEPS30; // Se le da el valor de la variable gloval TEPS30 a la columna 12 de la fila clonada del DataGridView ImporteWithTImpuestosIEPS26 = PriceForLot * (TTasaImpuestoIEPS26 / 100); // Se le da el valor a la variabe ImporteWithTImpuestosIEPS26 segun el resultado del calculo TIEPS26 = ImporteWithTImpuestosIEPS26; // Se le da el valor a la variabe global TIEPS26 segun el valor de la variable ImporteWithTImpuestoIEPS26 dgvProductos.CurrentRow.Cells[13].Value = TIEPS26; // Se le da el valor de la variable gloval TEPS26 a la columna 13 de la fila clonada del DataGridView #endregion #region RETENIDO ImporteWithRImpuestoIVA16 = PriceForLot * (RTasaImpuestoIVA16 / 100); // Se le da el valor a la variabe ImporteWithRImpuestoIVA16 segun el resultado del calculo RIVA16 = ImporteWithRImpuestoIVA16; // Se le da el valor a la variabe global RIVA16 segun el valor de la variable ImporteWithRImpuestoIVA16 dgvProductos.CurrentRow.Cells[14].Value = RIVA16; // Se le da el valor de la variable gloval RIVA16 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestoIVA1067 = PriceForLot * (RTasaImpuestoIVA1067 / 100); // Se le da el valor a la variabe ImporteWithRImpuestoIVA1067 segun el resultado del calculo RIVA1067 = ImporteWithRImpuestoIVA1067; // Se le da el valor a la variabe global RIVA1067 segun el valor de la variable ImporteWithRImpuestoIVA1067 dgvProductos.CurrentRow.Cells[15].Value = RIVA1067; // Se le da el valor de la variable gloval RIVA1067 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestoIVA733 = PriceForLot * (RTasaImpuestoIVA733 / 100); // Se le da el valor a la variabe ImporteWithRImpuestoIVA733 segun el resultado del calculo RIVA733 = ImporteWithRImpuestoIVA733; // Se le da el valor a la variabe global RIVA1067 segun el valor de la variable ImporteWithRImpuestoIVA1067 dgvProductos.CurrentRow.Cells[16].Value = RIVA733; // Se le da el valor de la variable gloval RIVA1067 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestosIVA4 = PriceForLot * (RTasaImpuestoIVA4 / 100); // Se le da el valor a la variabe ImporteWithRImpuestosIVA4 segun el resultado del calculo RIVA4 = ImporteWithRImpuestosIVA4; // Se le da el valor a la variabe global RIVA4 segun el valor de la variable ImporteWithRImpuestosIVA4 dgvProductos.CurrentRow.Cells[17].Value = RIVA4; // Se le da el valor de la variable gloval RIVA4 a la columna 14 de la fila clonada del DataGridView ImporteWithRImpuestosISR10 = PriceForLot * (RTasaImpuestoISR10 / 100); // Se le da el valor a la variabe ImporteWithRImpuestosISR10 segun el resultado del calculo RISR10 = ImporteWithRImpuestosISR10; // Se le da el valor a la variabe global RISR10 segun el valor de la variable ImporteWithRImpuestosISR10 dgvProductos.CurrentRow.Cells[18].Value = RISR10; // Se le da el valor de la variable gloval RISR10 a la columna 14 de la fila clonada del DataGridView #endregion Importe = PriceForLot + ImporteWithTImpuestoIVA16 + ImporteWithTImpuestoIVA11 + ImporteWithTImpuestoIVA4 + ImporteWithTImpuestosIEPS53 + ImporteWithTImpuestosIEPS30 + ImporteWithTImpuestosIEPS26; // Se le da el valor a la variabe Importe segun el resultado del calculo //TODO: SACAR EL RETENIDO DEL IMPORTE #endregion // Se llenan las columnas de la fila clonada del DataGridView mediante las variables usadas en las cuentas dgvProductos.CurrentRow.Cells[7].Value = Importe.ToString("N"); dgvProductos.CurrentRow.Cells[21].Value = ImporteWithoutExtras.ToString("N"); // Se recorren las filas del DataGridView foreach (DataGridViewRow rItem in dgvProductos.Rows) { Total += Convert.ToDecimal(rItem.Cells[7].Value); // Se acomula el valor de la variabe global Total segun se recorre la columna 7 del DataGridView Subtotal += Convert.ToDecimal(rItem.Cells[21].Value); // Se acomula el valor de la variabe global Subtotal segun se recorre la columna 21 del DataGridView } // Se valida que el valor de la variable global dolar sea true para sacar el total en dolares if (Dolar != false) { Sucursal mSucursal = ManejoSucursal.getById(FrmMenuMain.uHelper.usuario.sucursal_id); // se busca la sucursal mediante la llave foranea que tiene el usuario logeado y se guarda en un modelo de tipo sucursal TipoCambio = Convert.ToDecimal(mSucursal.sTipoCambio); // Se le da el valor a la variabe TipoCambio segun los datos del modelo sucursal TotalDolar = (Total * 1) / TipoCambio; // Se le da el valor a la variabe TotalDolar segun el resultado del calculo lblTotalDolar.Text = TotalDolar.ToString("N"); // Se le da el valor al lblTotalDolar segun el valor de la variable TotalDolar } // Se asignan valores a los respectivos labels lblSubTotal.Text = Subtotal.ToString("N"); lblTotal.Text = Total.ToString("N"); lblIVA16.Text = TIVA16.ToString("N"); lblIVA11.Text = TIVA11.ToString("N"); lblIVA4.Text = TIVA4.ToString("N"); lblIEPS53.Text = TIEPS53.ToString("N"); lblIEPS30.Text = TIEPS30.ToString("N"); lblIEPS26.Text = TIEPS26.ToString("N"); lblRIVA16.Text = RIVA16.ToString("N"); lblRIVA1067.Text = RIVA1067.ToString("N"); lblRIVA733.Text = RIVA733.ToString("N"); lblRIVA4.Text = RIVA4.ToString("N"); lblRISR10.Text = RISR10.ToString("N"); } } else { dgvProductos.Rows.RemoveAt(dgvProductos.CurrentRow.Index); } } } } } } /// <summary> /// Este evento se utilizo para saber cuando mostrar el boton de eliminar productos /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvProductos_SelectionChanged(object sender, EventArgs e) { if (!dgvProductos.CurrentRow.IsNewRow) // Se valida que la fila seleccionada no sea para ingresar registros nuevos { btnBorrar.Visible = true; // Se cambia la propiedad visible del btnBorrar para que se muestre en la vista } else { btnBorrar.Visible = false; // Se cambia la propiedad visible del btnBorrar para que no se muestre en la vista } } /// <summary> /// Boton con el cual se elimina el producto seleccionado del DataGridView, asi como todos sus respectivos valores en las variables. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBorrar_Click(object sender, EventArgs e) { if (dgvProductos.RowCount > 1) // Se valida que el DataGridView tenga mas de una fila { #region VARIABLES // Se le da valor a las diferentes variables mediante las columnas de la fila seleccionada decimal PreUnitario = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[5].Value); decimal DgvTIva16 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[8].Value); decimal DgvTIva11 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[9].Value); decimal DgvTIva4 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[10].Value); decimal DgvTIep53 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[11].Value); decimal DgvTIep30 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[12].Value); decimal DgvTIep26 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[13].Value); decimal DgvRIva16 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[14].Value); decimal DgvRIva1067 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[15].Value); decimal DgvRIva733 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[16].Value); decimal DgvRIva4 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[17].Value); decimal DgvRIsr10 = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[18].Value); decimal dgvDescuento = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[19].Value); decimal dgvDescuentoExt = Convert.ToDecimal(dgvProductos.CurrentRow.Cells[20].Value); decimal descuento = 0; decimal descuentoExt = 0; decimal subtotal = 0; decimal total = 0; #endregion #region CALCULOS // Se restan los valores de la fila seleccionada a las variables globales TIVA16 -= DgvTIva16; TIVA11 -= DgvTIva11; TIVA4 -= DgvTIva4; TIEPS53 -= DgvTIep53; TIEPS30 -= DgvTIep30; TIEPS26 -= DgvTIep26; RIVA16 -= DgvRIva16; RIVA1067 -= DgvRIva1067; RIVA733 -= DgvRIva733; RIVA4 -= DgvRIva4; RISR10 -= DgvRIsr10; // Se realiza el calculo para sacar el descuento en porentaje y restarselo a las variables globales descuento = PreUnitario * (dgvDescuento / 100); descuentoExt = PreUnitario * (dgvDescuentoExt / 100); #endregion // Se remueve la fila seleccionada del DataGridView dgvProductos.Rows.RemoveAt(dgvProductos.CurrentRow.Index); // Se recorren las filas del DataGridView foreach (DataGridViewRow rItem in dgvProductos.Rows) { total += Convert.ToDecimal(rItem.Cells[7].Value); // Se acomula el valor de la variabe local total segun se recorre la columna 7 del DataGridView subtotal += Convert.ToDecimal(rItem.Cells[21].Value); // Se acomula el valor de la variabe local subtotal segun se recorre la columna 21 del DataGridView } if (total == 0) // Se valida que el total sea igual a 0 { lblTotal.Text = "0"; // Se asigna el valor de 0 a el lblTotal } else { lblTotal.Text = total.ToString("N"); // Se asigna el valor de la variable local total a el lblTotal } if (subtotal == 0) // Se valida que el subtotal sea igua a 0 { lblSubTotal.Text = "0"; // Se asigna el valor de 0 a el lblSubTotal } else { lblSubTotal.Text = subtotal.ToString("N"); // Se asigna el valor de la variable local subtotal a el lblSubTotal } if (dgvProductos.RowCount == 1) // Se valida que las filas del DataGridView sea 1 para esconder el btnBorrar { btnBorrar.Visible = false; // Se cambia la propiedad visible del boton btnBorrar a false } // Se asignan valores a los respectivos labels lblIVA16.Text = TIVA16.ToString("N"); lblIVA11.Text = TIVA11.ToString("N"); lblIVA4.Text = TIVA4.ToString("N"); lblIEPS53.Text = TIEPS53.ToString("N"); lblIEPS30.Text = TIEPS30.ToString("N"); lblIEPS26.Text = TIEPS26.ToString("N"); lblRIVA16.Text = RIVA16.ToString("N"); lblRIVA1067.Text = RIVA1067.ToString("N"); lblRIVA733.Text = RIVA733.ToString("N"); lblRIVA4.Text = RIVA4.ToString("N"); lblRISR10.Text = RISR10.ToString("N"); } } /// <summary> /// Boton con el cual se valida que los textbox correspondientes al clientes no esten vacios y poder ejecutar diferentes funciones /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnImprimir_Click(object sender, EventArgs e) { if (txtRFC.Text == "") // Se valida que el txtRFC este vacio { this.ErrorProvider.SetIconAlignment(this.txtRFC, ErrorIconAlignment.MiddleRight); // Se asigna el icono del error a el txtRFC this.ErrorProvider.SetError(this.txtRFC, "Campo necesario"); // se asigna el mensaje de error a el txtRFC this.txtRFC.Focus(); // Se asigna la propiedad focus al txtRFC } else if (txtNombre.Text == "") // Se valida que el txtNombre este vacio { this.ErrorProvider.SetIconAlignment(this.txtNombre, ErrorIconAlignment.MiddleRight); this.ErrorProvider.SetError(this.txtNombre, "Campo necesario"); this.txtNombre.Focus(); } else if (txtDireccion.Text == "") // Se valida que el txtDireccion este vacio { this.ErrorProvider.SetIconAlignment(this.txtDireccion, ErrorIconAlignment.MiddleRight); this.ErrorProvider.SetError(this.txtDireccion, "Campo necesario"); this.txtDireccion.Focus(); } else if (txtTelefono.Text == "") // Se valida que el txtTelefono este vacio { this.ErrorProvider.SetIconAlignment(this.txtTelefono, ErrorIconAlignment.MiddleRight); this.ErrorProvider.SetError(this.txtTelefono, "Campo necesario"); this.txtTelefono.Focus(); } else if (txtCondicionesDePago.Text == "") // Se valida que el txtCondicionesDePago este vacio { this.ErrorProvider.SetIconAlignment(this.txtCondicionesDePago, ErrorIconAlignment.MiddleRight); this.ErrorProvider.SetError(this.txtCondicionesDePago, "Campo necesario"); this.txtCondicionesDePago.Focus(); } else { CrearCarpetas(); // Se manda llamar la funcion CrearCarpetas() GenerarFactura(); // Se manda llamar la funcion GenerarFactura() CrearSelloFinkok(NameFileXML); // Se manda llamar la funcion CrearSelloFinkok() y le mamda el nombre del archivo xml actual GenerarFactura(); // Se manda llamar la funcion GenerarFactura() ManejoFacturacion.timbrado(NameFileXML); // Se manda llamar la funcion timbrado() de la clase manejofacturacion y se le manda el nombre del archivo xml actual GuardarFactura(); // Se manda llamar la funcion GuardarFactura() Clear(); // Se manda llamar la funcion Clear() } } private void tbnEnviarCorreo_Click(object sender, EventArgs e) { } #endregion } }
using System.Windows.Controls; namespace QuizBuilderLib { /// <summary> /// Interaction logic for TextQuestionControl.xaml /// </summary> public partial class TextQuestionControl : UserControl { public TextQuestionControl() { InitializeComponent(); } public string GetQuestionText() { return mainQuestion_txBx.Text; } } }
namespace Proyecto_Web.Datos_Reporte { } namespace Proyecto_Web.Datos_Reporte { public partial class Datos_proveedores { } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; using Newtonsoft.Json; namespace ExpVMsape.Controllers { public class EstadisticasController : Controller { // GET: Estadisticas public ActionResult Pedidos() { return View(); } //GET [Authorize(Users = ("rpegoraro@diarionorte.com,gerencia@diarionorte.com,m_benitez@diarionorte.com,ventas@diarionorte.com,admin@diarionorte.com,cac@diarionorte.com"))] public ActionResult DetalleInterior() { return View(); } [HttpPost] public ActionResult _DetalleInterior(DateTime? fecha1, DateTime? fecha2) { fecha1 = fecha1.Value.Date; fecha2 = fecha2.Value.Date; ViewBag.fdesde = fecha1.Value.ToShortDateString(); ViewBag.fhasta = fecha2.Value.ToShortDateString(); DataTable dt = new DataTable(); string sqls = "plandistribu_listarRangoFecha"; SqlConnection conn = new SqlConnection(@"Data Source=ROSA;Initial Catalog=ExpedicionDB;Persist Security Info=True;User ID=sa;Password=Norte1234"); SqlDataAdapter da = new SqlDataAdapter(sqls, conn); conn.Open(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@fecha1", SqlDbType.Date).Value = fecha1; da.SelectCommand.Parameters.Add("@fecha2", SqlDbType.Date).Value = fecha2; da.Fill(dt); if (dt.Rows.Count > 0) { List<string> contenidoTabla = new List<string>(); var localidad = ""; var prov = ""; var cp = ""; var cant_ej = ""; var dist = ""; foreach (DataRow dr in dt.Rows) { // On all tables' columns //foreach (DataColumn dc in dt.Columns) cp = dr["CodigoPostal"].ToString(); localidad = dr["Localidad"].ToString(); prov = dr["Provincia"].ToString(); dist = dr["SubDistribuidor"].ToString(); cant_ej = dr["cant_ejemplares"].ToString(); contenidoTabla.Add(cp); contenidoTabla.Add(localidad); contenidoTabla.Add(prov); contenidoTabla.Add(dist); contenidoTabla.Add(cant_ej); } //ViewBag.detalleinterior = detalleInterior ; ViewBag.contenidoTabla = contenidoTabla; ViewBag.contador = contenidoTabla.Count() - 1; } return View(); } [Authorize(Users = ("rpegoraro@diarionorte.com,gerencia@diarionorte.com,m_benitez@diarionorte.com,ventas@diarionorte.com,admin@diarionorte.com,cac@diarionorte.com"))] public ActionResult DetalleInteriorPorDia() { return View(); } public ActionResult _DetalleInteriorPorDia(DateTime? finicio) { finicio = finicio.Value.Date; ViewBag.fdesde = finicio.Value.ToShortDateString(); int diaFinMes = 0; CultureInfo ci = new CultureInfo("Es-Es"); diaFinMes = DateTime.DaysInMonth(finicio.Value.Year, finicio.Value.Month); var fhasta = new DateTime(finicio.Value.Year, finicio.Value.Month, diaFinMes); List<string> contenidoTabla = new List<string>(); while (finicio <= fhasta) { DataTable dt = new DataTable(); string sqls = "plandistribu_listarRangoFecha"; SqlConnection conn = new SqlConnection(@"Data Source=ROSA;Initial Catalog=ExpedicionDB;Persist Security Info=True;User ID=sa;Password=Norte1234"); SqlDataAdapter da = new SqlDataAdapter(sqls, conn); conn.Open(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@fecha1", SqlDbType.Date).Value = finicio; da.SelectCommand.Parameters.Add("@fecha2", SqlDbType.Date).Value = finicio; da.Fill(dt); if (dt.Rows.Count > 0) { var localidad = ""; var prov = ""; var cp = ""; var cant_ej = ""; var dist = ""; var dia = ""; var nombreDia = ""; foreach (DataRow dr in dt.Rows) { // On all tables' columns //foreach (DataColumn dc in dt.Columns) nombreDia = ci.DateTimeFormat.GetDayName(finicio.Value.DayOfWeek); dia = finicio.Value.Day.ToString(); cp = dr["CodigoPostal"].ToString(); localidad = dr["Localidad"].ToString(); prov = dr["Provincia"].ToString(); dist = dr["SubDistribuidor"].ToString(); cant_ej = dr["cant_ejemplares"].ToString(); contenidoTabla.Add(nombreDia); contenidoTabla.Add(dia); contenidoTabla.Add(cp); contenidoTabla.Add(localidad); contenidoTabla.Add(prov); contenidoTabla.Add(dist); contenidoTabla.Add(cant_ej); } } finicio = finicio.Value.AddDays(1); } var fechaMuestra = finicio.Value.AddDays(-1); ViewBag.mes = ci.DateTimeFormat.GetMonthName(fechaMuestra.Month) + "/"+ fechaMuestra.Year; ViewBag.contenidoTabla = contenidoTabla; ViewBag.contador = contenidoTabla.Count() - 1; return View(); } } }
using System.Collections.ObjectModel; using System.Linq; using System.Windows.Controls; namespace TotalUninstaller { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class InstalledItemsView { public InstalledItemsView() { InitializeComponent(); DataContext = new InstalledItemsViewModel(this); } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { if (DataContext == null) return; var text = ((TextBox)sender).Text; var installedItemsViewModel = ((InstalledItemsViewModel)DataContext); installedItemsViewModel.Items = new ObservableCollection<InstalledItem>(installedItemsViewModel.AllItems.Where(x => x.Product.ToUpper().Contains(text.ToUpper()))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CinemalyticsCSharpSDK.Model { public class FilmingLocation { public String Id { get; set; } public String Name { get; set; } public String State { get; set; } public String Country { get; set; } internal bool IsStudio { get; set; } } }
using System; using System.IO; using System.Web; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string CreateUiXml => SystemDirectories.Umbraco + "/config/create/UI.xml"; public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string DashboardConfig => SystemDirectories.Config + "/dashboard.config"; public static string NotFoundhandlersConfig => SystemDirectories.Config + "/404handlers.config"; public static string FeedProxyConfig => string.Concat(SystemDirectories.Config, "/feedProxy.config"); // fixme - kill public static string GetContentCacheXml(IGlobalSettings globalSettings) { switch (globalSettings.LocalTempStorageLocation) { case LocalTempStorage.AspNetTemp: return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config"); case LocalTempStorage.EnvironmentTemp: var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1(); var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", //include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back // to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not // utilizing an old path appDomainHash); return Path.Combine(cachePath, "umbraco.config"); case LocalTempStorage.Default: return IOHelper.ReturnPath("umbracoContentXML", "~/App_Data/umbraco.config"); default: throw new ArgumentOutOfRangeException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UGCS.Example.Enums { public enum VehicleControlMode { MODE_AUTO = 0, MODE_MANUAL = 1, MODE_JOYSTICK = 2, MODE_UNKOWN = 3, MODE_GUIDED = 4 } }
using Athena.Data.Books; using Athena.Import; using Athena.Windows; using Microsoft.EntityFrameworkCore; using Microsoft.Win32; using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Input; using System.Windows.Controls; using Athena.Data.Categories; using Athena.MessageBoxes; using Athena.Messages; using Hub = MessageHub.MessageHub; namespace Athena { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public ObservableCollection<BookInListView> Books { get; set; } public MainWindow() { InitializeComponent(); this.DataContext = this; Books = Mapper.Instance.Map<ObservableCollection<BookInListView>>(ApplicationDbContext.Instance.Books .Include(b => b.Series) .Include(b => b.PublishingHouse) .Include(b => b.StoragePlace) .Include(b => b.Authors) .Include(b => b.Categories) .Include(b => b.Borrowings.OrderByDescending(b => b.BorrowDate)) .AsNoTracking().ToList() ); ApplicationDbContext.Instance.ChangeTracker.StateChanged += (sender, e) => { if (e.Entry.Entity is Book book && e.NewState == EntityState.Modified) { var bookInList = Books.Single(b => b.Id == book.Id); Mapper.Instance.Map(book, bookInList); } }; ApplicationDbContext.Instance.Books.Local.CollectionChanged += (sender, e) => { if (e.NewItems != null) { foreach (Book item in e?.NewItems) { if (Books.All(b => b.Id != item.Id)) { Application.Current.Dispatcher.Invoke(() => Books.Add(Mapper.Instance.Map<BookInListView>(item))); } } } else if (e.Action == NotifyCollectionChangedAction.Remove) { var book = (Book) e.OldItems[0]; var bookInList = Books.First(b => b.Id == book.Id); Books.Remove(bookInList); } }; ApplicationDbContext.Instance.Books.Local.CollectionChanged += (sender, e) => { if (Books.Count > 0) { Application.Current.Dispatcher.Invoke(() => ImportButton.Visibility = Visibility.Hidden); } else { Application.Current.Dispatcher.Invoke(() => ImportButton.Visibility = Visibility.Visible); } }; this.Closed += (sender, args) => Application.Current.Shutdown(); Hub.Instance.Subscribe<BorrowBookMessage>(RefreshBorrowedBook); } private void RefreshBorrowedBook(BorrowBookMessage e) { var bookInListView = Books.First(a => a.Id == e.Borrowing.Book.Id); bookInListView.Borrowings.Add(e.Borrowing); } public static RoutedUICommand MenuItemBorrow_Click = new RoutedUICommand("MenuItemBorrow_Click", "MenuItemBorrow_Click", typeof(MainWindow)); public void ResizeGridViewColumns(GridView gridView) { foreach (GridViewColumn column in gridView.Columns) { if (double.IsNaN(column.Width)) { column.Width = column.ActualWidth; } column.Width = double.NaN; } } private void MenuItemBorrow_Executed(object sender, RoutedEventArgs e) { Book book = ApplicationDbContext.Instance.Books.Single(b => b.Id == ((BookInListView) BookList.SelectedItem).Id); BorrowForm borrowForm = new BorrowForm(book); borrowForm.Show(); } private void MenuItemBorrow_CanExecute(object sender, CanExecuteRoutedEventArgs e) { if (BookList.SelectedItem == null) { return; } var borrowings = ((BookInListView) BookList.SelectedItem).Borrowings; if (borrowings.Any(b => b.ReturnDate == null)) { e.CanExecute = false; } else { e.CanExecute = true; } } private void MenuItemEdit_Click(object sender, System.Windows.RoutedEventArgs e) { ShowEditBookWindow(); } private void ShowEditBookWindow() { Book book = ApplicationDbContext.Instance.Books .Include(a => a.Categories) .Include(b => b.Series) .Include(b => b.PublishingHouse) .Include(b => b.StoragePlace) .Include(b => b.Authors) .Single(b => b.Id == ((BookInListView) BookList.SelectedItem).Id); book.Authors = book.Authors.Distinct().ToList(); EditBookWindow editBook = new EditBookWindow(book); editBook.BookEdited += (o, e) => { var book = Books.First(a => a.Id == e.Entity.Id); Mapper.Instance.Map(e.Entity, book); }; editBook.Show(); } private void MenuItemDelete_Click(object sender, System.Windows.RoutedEventArgs e) { var messageBoxGenerator = new ConfirmBookDeleteMessageBox(); var decision = messageBoxGenerator.Show(); if (decision) { var book = ApplicationDbContext.Instance.Books .Include(a => a.Borrowings) .Single(b => b.Id == ((BookInListView) BookList.SelectedItem).Id); book.Borrowings = ApplicationDbContext.Instance.Borrowings .Include(a => a.Book) .Where(a => a.Book.Id == book.Id) .ToList(); ApplicationDbContext.Instance.Books.Remove(book); ApplicationDbContext.Instance.SaveChanges(); Hub.Instance.Publish(new RemoveBookMessage() {Book = book}); SearchTextBox.Text = string.Empty; } } private void MenuItem_Click(object sender, RoutedEventArgs e) { this.Close(); } private void OpenBorrowedBookList_Click(object sender, RoutedEventArgs e) { BorrowedBooksListWindow borrowedBooks = new BorrowedBooksListWindow(); borrowedBooks.Show(); } private void AddBook_Click(object sender, System.Windows.RoutedEventArgs e) { AddBookWindow addBook = new AddBookWindow(); addBook.Show(); } private void ImportData(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.ShowDialog(); var fileName = openFileDialog.FileName; if (fileName == "") { return; } MainGrid.Visibility = Visibility.Collapsed; BackgroundWorker worker = new BackgroundWorker {WorkerReportsProgress = true}; ImportButton.Visibility = Visibility.Hidden; ImportGrid.Visibility = Visibility.Visible; worker.DoWork += worker_DoWork; worker.ProgressChanged += worker_ProgressChanged; worker.RunWorkerCompleted += (o, args) => { if (args.Result != null) { if (args.Result.GetType() == typeof(ImportException)) { var messageBox = new RemoveDataBaseMessageBox(); var answer = messageBox.Show(); if (answer) { ResetDatabase(); } ImportButton.Visibility = Visibility.Visible; } } ImportGrid.Visibility = Visibility.Hidden; MainGrid.Visibility = Visibility.Visible; ResizeGridViewColumns(BooksGridView); }; worker.RunWorkerAsync(argument: fileName); } private void ResetDatabase() { ApplicationDbContext.Instance.ChangeTracker.Clear(); ApplicationDbContext.Instance.Database.EnsureDeleted(); ApplicationDbContext.Instance.Database.EnsureCreated(); } private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressBarStatus.Value = e.ProgressPercentage; } private void worker_DoWork(object sender, DoWorkEventArgs e) { var fileName = (string) e.Argument; try { var dataImporter = new DatabaseImporter(); dataImporter.ImportFromSpreadsheet(fileName); } catch (ImportException exception) { e.Result = exception; } } private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e) { var text = SearchTextBox.Text; if (text.Length == 0) BookList.ItemsSource = Books; if (text.Length < 3) return; var fillteredBooks = Books.Where(b => b.Title.Contains(text, StringComparison.CurrentCultureIgnoreCase) || (b.Series?.SeriesName != null && b.Series.SeriesName.Contains(text, StringComparison.CurrentCultureIgnoreCase)) || (b.PublishingHouse?.PublisherName != null && b.PublishingHouse.PublisherName.Contains(text, StringComparison.CurrentCultureIgnoreCase)) || (b.Authors.Any(a => a.ToString().Contains(text, StringComparison.CurrentCultureIgnoreCase))) || (b.Categories.Any(c => c.GetDescription().Contains(text, StringComparison.CurrentCultureIgnoreCase))) ); BookList.ItemsSource = fillteredBooks; } private void BookList_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (BookList.SelectedItem != null) { ShowEditBookWindow(); } } private void RemoveDatabase_OnClick(object sender, RoutedEventArgs e) { var firstWarningMessageBox = new RemoveDataBaseMessageBox(); var decision = firstWarningMessageBox.Show(); if (decision) { var secondWarningMessageBox = new RemoveDatabaseWithBooksMessageBox(); var lastDecision = secondWarningMessageBox.Show(); if (lastDecision) { ResetDatabase(); Books.Clear(); ImportButton.Visibility = Visibility.Visible; } } } } }
using LePapeo.Models; using LePapeoGenNHibernate.CAD.LePapeo; using LePapeoGenNHibernate.CEN.LePapeo; using LePapeoGenNHibernate.EN.LePapeo; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WEBLEPAPEO.Controllers { public class DireccionController : BasicController { // GET: Direccion public ActionResult Index() { DireccionCEN dirCEN = new DireccionCEN(); IList<DireccionEN> listDirEN = dirCEN.ReadAll(0, -1); IEnumerable<DireccionViewModel> listd = new AssemblerDireccion().ConvertListENToModel(listDirEN); return View(listd); } // GET: Direccion/Details/5 public ActionResult Details(int id) { SessionInitialize(); DireccionCAD dircad = new DireccionCAD(session); DireccionCEN dircen = new DireccionCEN(dircad); DireccionEN diren = dircen.ReadOID(id); DireccionViewModel vi = new AssemblerDireccion().ConvertENToModelUI(diren); ViewData["ciudad"] = diren.Ciudad.Nombre; SessionClose(); return View(vi); } // GET: Direccion/Create public ActionResult Create() { DireccionViewModel dir = new DireccionViewModel(); CiudadCEN ciudadCEN = new CiudadCEN(); IList<CiudadEN> listaCiudad = ciudadCEN.ReadAll(0, -1); ViewData["listaCiudad"] = listaCiudad; return View(dir); } // POST: Direccion/Create [HttpPost] public ActionResult Create(DireccionViewModel dir) { try { // TODO: Add insert logic here //String indx = "Index"; CiudadCEN ciudadCEN = new CiudadCEN(); CiudadEN ciudadEN = ciudadCEN.ReadOID(dir.ciudad); CiudadCEN c = new CiudadCEN(); if(ciudadEN == null) { c.New_(dir.ciudad, dir.provincia); } else if(ciudadEN.Provincia == null) { c.Modify(ciudadEN.Nombre, dir.provincia); } DireccionCEN dircen = new DireccionCEN(); dircen.New_(dir.cod_pos, dir.calle, dir.numero_puerta, dir.pos_x, dir.pos_y, dir.ciudad); UsuarioCEN usu = new UsuarioCEN(); int idd = usu.DgetOIDfromEmail(User.Identity.Name); UsuarioEN usuen = usu.ReadOID(idd); //Console.Write("\n"+idd+"\n"); if (usuen != null) { String[] tipo = usuen.GetType().ToString().Split('.'); if (tipo[tipo.Length - 1].Equals("RestauranteEN")) { RestauranteCEN rescen = new RestauranteCEN(); rescen.AgregarDireccion(idd, dir.id); } } return RedirectToAction("Index"); } catch { return View(); } } // GET: Direccion/Edit/5 public ActionResult Edit(int id) { SessionInitialize(); DireccionCAD dircad = new DireccionCAD(session); DireccionCEN dircen = new DireccionCEN(dircad); DireccionEN diren = dircen.ReadOID(id); DireccionViewModel dirview = new AssemblerDireccion().ConvertENToModelUI(diren); SessionClose(); return View(dirview); } // POST: Direccion/Edit/5 [HttpPost] public ActionResult Edit(DireccionViewModel view) { try { // TODO: Add update logic here DireccionCEN dircen = new DireccionCEN(); dircen.Modify(view.id, view.cod_pos, view.calle, view.numero_puerta, view.pos_x, view.pos_y); return RedirectToAction("Index"); } catch { return View(); } } // GET: Direccion/Delete/5 public ActionResult Delete(int id) { SessionInitialize(); DireccionCAD dircad = new DireccionCAD(session); DireccionCEN dircen = new DireccionCEN(dircad); DireccionEN diren = dircen.ReadOID(id); DireccionViewModel dirview = new AssemblerDireccion().ConvertENToModelUI(diren); SessionClose(); return View(dirview); } // POST: Direccion/Delete/5 [HttpPost] public ActionResult Delete(DireccionViewModel view) { try { // TODO: Add delete logic here new DireccionCEN().Destroy(view.id); return RedirectToAction("Index"); } catch { return View(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SecondProject.Controllers.Services.Model.Domain { public class Client { public string serviceUrl { get; set; } public bool shouldRegisterWithEureka { get; set; } public bool shouldFetchRegistry { get; set; } public Healthcheck healthcheck { get; set; } } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text; using System.Net; using System.Web.Mvc; using System.Data; using System.Data.Entity; using System.Threading.Tasks; using CriticalPath.Data; using CriticalPath.Web.Models; using CP.i8n; namespace CriticalPath.Web.Controllers { public partial class ProcessStepsController : BaseController { protected virtual async Task<IQueryable<ProcessStep>> GetProcessStepQuery(QueryParameters qParams) { var query = GetProcessStepQuery(); if (!string.IsNullOrEmpty(qParams.SearchString)) { query = from a in query where a.Title.Contains(qParams.SearchString) | a.Description.Contains(qParams.SearchString) select a; } if (qParams.ProcessId != null) { query = query.Where(x => x.ProcessId == qParams.ProcessId); } if (qParams.TemplateId != null) { query = query.Where(x => x.TemplateId == qParams.TemplateId); } if (qParams.IsApproved != null) { query = query.Where(x => x.IsApproved == qParams.IsApproved.Value); } if (qParams.ApproveDateMin != null) { query = query.Where(x => x.ApproveDate >= qParams.ApproveDateMin.Value); } if (qParams.ApproveDateMax != null) { var maxDate = qParams.ApproveDateMax.Value.AddDays(1); query = query.Where(x => x.ApproveDate < maxDate); } qParams.TotalCount = await query.CountAsync(); return query.Skip(qParams.Skip).Take(qParams.PageSize); } protected virtual async Task<List<ProcessStepDTO>> GetProcessStepDtoList(QueryParameters qParams) { var query = await GetProcessStepQuery(qParams); var list = qParams.TotalCount > 0 ? await query.ToListAsync() : new List<ProcessStep>(); var result = new List<ProcessStepDTO>(); foreach (var item in list) { result.Add(new ProcessStepDTO(item)); } return result; } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<ActionResult> Index(QueryParameters qParams) { await PutCanUserInViewBag(); var query = await GetProcessStepQuery(qParams); var result = new PagedList<ProcessStep>(qParams); if (qParams.TotalCount > 0) { result.Items = await query.ToListAsync(); } PutPagerInViewBag(result); return View(result.Items); } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<ActionResult> GetProcessStepList(QueryParameters qParams) { var result = await GetProcessStepDtoList(qParams); return Json(result, JsonRequestBehavior.AllowGet); } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<ActionResult> GetProcessStepPagedList(QueryParameters qParams) { var items = await GetProcessStepDtoList(qParams); var result = new PagedList<ProcessStepDTO>(qParams, items); return Json(result, JsonRequestBehavior.AllowGet); } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<JsonResult> GetProcessStepsForAutoComplete(QueryParameters qParam) { var query = GetProcessStepQuery() .Where(x => x.Title.Contains(qParam.SearchString)) .Take(qParam.PageSize); var list = from x in query select new { id = x.Id, value = x.Title, label = x.Title }; return Json(await list.ToListAsync(), JsonRequestBehavior.AllowGet); } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<ActionResult> Details(int? id, bool? modal) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ProcessStep processStep = await FindAsyncProcessStep(id.Value); if (processStep == null) { return HttpNotFound(); } await PutCanUserInViewBag(); if (modal ?? false) { return PartialView("_Details", processStep); } return View(processStep); } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<ActionResult> GetProcessStep(int? id) { if (id == null) { return BadRequestTextResult(); } ProcessStep processStep = await FindAsyncProcessStep(id.Value); if (processStep == null) { return NotFoundTextResult(); } return Json(new ProcessStepDTO(processStep), JsonRequestBehavior.AllowGet); } [Authorize(Roles = "admin, supervisor, clerk")] public async Task<ActionResult> Edit(int? id, bool? modal) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ProcessStep processStep = await FindAsyncProcessStep(id.Value); if (processStep == null) { return HttpNotFound(); } SetSelectLists(processStep); if (modal ?? false) { ViewBag.Modal = true; return PartialView("_Edit", processStep); } return View(processStep); } [Authorize(Roles = "admin, supervisor, clerk")] [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit(ProcessStep processStep, bool? modal) { if (ModelState.IsValid) { OnEditSaving(processStep); DataContext.Entry(processStep).State = EntityState.Modified; await DataContext.SaveChangesAsync(this); OnEditSaved(processStep); if (modal ?? false) { return Json(new { saved = true }); } return RedirectToAction("Index"); } SetSelectLists(processStep); if (modal ?? false) { ViewBag.Modal = true; return PartialView("_Edit", processStep); } return View(processStep); } protected override bool CanUserCreate() { if (!_canUserCreate.HasValue) { _canUserCreate = Request.IsAuthenticated && ( IsUserAdmin() || IsUserSupervisor() || IsUserClerk()); } return _canUserCreate.Value; } protected override async Task<bool> CanUserCreateAsync() { if (!_canUserCreate.HasValue) { _canUserCreate = Request.IsAuthenticated && ( await IsUserAdminAsync() || await IsUserSupervisorAsync() || await IsUserClerkAsync()); } return _canUserCreate.Value; } bool? _canUserCreate; protected override bool CanUserEdit() { if (!_canUserEdit.HasValue) { _canUserEdit = Request.IsAuthenticated && ( IsUserAdmin() || IsUserSupervisor() || IsUserClerk()); } return _canUserEdit.Value; } protected override async Task<bool> CanUserEditAsync() { if (!_canUserEdit.HasValue) { _canUserEdit = Request.IsAuthenticated && ( await IsUserAdminAsync() || await IsUserSupervisorAsync() || await IsUserClerkAsync()); } return _canUserEdit.Value; } bool? _canUserEdit; protected override bool CanUserDelete() { if (!_canUserDelete.HasValue) { _canUserDelete = Request.IsAuthenticated && ( IsUserAdmin()); } return _canUserDelete.Value; } protected override async Task<bool> CanUserDeleteAsync() { if (!_canUserDelete.HasValue) { _canUserDelete = Request.IsAuthenticated && ( await IsUserAdminAsync()); } return _canUserDelete.Value; } bool? _canUserDelete; protected override bool CanUserSeeRestricted() { return true; } protected override Task<bool> CanUserSeeRestrictedAsync() { return Task.FromResult(true); } public new partial class QueryParameters : BaseController.QueryParameters { public QueryParameters() { } public QueryParameters(QueryParameters parameters) : base(parameters) { ProcessId = parameters.ProcessId; TemplateId = parameters.TemplateId; } public int? ProcessId { get; set; } public int? TemplateId { get; set; } public bool? IsApproved { get; set; } public DateTime? ApproveDateMin { get; set; } public DateTime? ApproveDateMax { get; set; } } public partial class PagedList<T> : QueryParameters { public PagedList() { } public PagedList(QueryParameters parameters) : base(parameters) { } public PagedList(QueryParameters parameters, IEnumerable<T> items) : this(parameters) { Items = items; } public IEnumerable<T> Items { set { _items = value; } get { if (_items == null) { _items = new List<T>(); } return _items; } } IEnumerable<T> _items; } partial void OnEditSaving(ProcessStep processStep); partial void OnEditSaved(ProcessStep processStep); partial void SetSelectLists(ProcessStep processStep); } }
using LearningEnglishMobile.Core.ViewModels.Base; using System; using System.Collections.Generic; using System.Text; namespace LearningEnglishMobile.Core.Models.Vocabulary { public class UserWord : ExtendedBindableObject { public int Id { get; set; } public string Word { get; set; } public string Translation { get; set; } private bool _isSelected { get; set; } public bool IsSelected { get => _isSelected; set { _isSelected = value; RaisePropertyChanged(() => IsSelected); } } } }
using UnityEngine; using System.Collections; public class AimMouse : MonoBehaviour { public Vector2 mousePosition; public GameObject projectile; public float projSpeed = 200.0f; private float step; Rigidbody2D projRB; // Use this for initialization void Start () { projRB = projectile.GetComponent<Rigidbody2D>(); mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); } // Update is called once per frame void Update () { step = projSpeed * Time.deltaTime; } public void Fire() { projRB.transform.position = Vector2.MoveTowards(projRB.transform.position, mousePosition, step); } public void Strike() { Vector3 pos = Input.mousePosition; pos.z = transform.position.z - Camera.main.transform.position.z; pos = Camera.main.ScreenToWorldPoint(pos); Vector2 dir = new Vector2 (0, -1); projRB.AddForce(dir * 200.0f); } }
using SGDE.Domain.Entities; using System; namespace SGDE.Domain.ViewModels { public class WorkHistoryViewModel : BaseEntityViewModel { public string reference { get; set; } public DateTime date { get; set; } public string description { get; set; } public string observations { get; set; } public string type { get; set; } public string typeFile { get; set; } public byte[] file { get; set; } public string fileName { get; set; } public int workId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElementosBásicos { class Califiacion_final { static void Main(string[] args) { double nota1, nota2, nota3, promedio1, promedio2, promedio3, notafinal; Console.WriteLine("Ingrese la nota del Primer Computo: "); nota1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Ingrese la nota del Segundo Computo: "); nota2 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Ingrese la nota del Tercer Computo: "); nota3 = Convert.ToDouble(Console.ReadLine()); promedio1 = (nota1 * 0.30); Console.WriteLine("Nota del Primer Computo con el porcentaje aplicado: " + promedio1); promedio2 = (nota2 * 0.35); Console.WriteLine("Nota del Segundo Computo con el porcentaje aplicado: " + promedio2); promedio3 = (nota3 * 0.25); Console.WriteLine("Nota del Tercer Computo con el porcentaje aplicado: " + promedio3); notafinal = (promedio1 + promedio2 + promedio3); Console.WriteLine("La nota final es: " + notafinal); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class JumpTask : GameTask { protected CanJump _jumpScript; public JumpTask() { name = "JUMP"; consumption = 0; cost = 20; description = "What gets you high."; currentValue = ""; example = "JUMP"; _jumpScript = GameManager.Instance.player.GetComponent<CanJump>(); _jumpScript.enabled = false; enabled = false; } public override string Disable() { if (!enabled) return "Task " + name + " already killed."; var msg = base.Disable(); if(!enabled) _jumpScript.enabled = false; return msg; } public override string Enable() { if (enabled) return "Task " + name + " already started."; var msg = base.Enable(); if(enabled) _jumpScript.enabled = true; return msg; } public override string SetValue(string value) { return "JUMP filter expect no parameter."; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; namespace JuniorSlataTestTask.Data.Models { public class Jobseaker { public int id { get; set; } public string FullName { get; set; } public string PhoneNumber { get; set; } public string Position { get; set; } public string TimeToTask { get; set; } public int TaskId { get; set; } private Task task; public Task Task { get { if (task != null) return task; using (AppContext db = new AppContext()) { if (task == null) task = db.Tasks.Where(t => t.id == TaskId).FirstOrDefault(); return task; }; } set { task = value; } } public int? ManagerId { get; set; } private User manager; [NotMapped] public User Manager { get { if (manager != null) return manager; using (AppContext db = new AppContext()) { if (manager == null) Manager = db.Users.Where(t => t.id == ManagerId).FirstOrDefault(); return manager; }; } set { manager = value; } } public int? MentorId { get; set; } private User mentor; [NotMapped] public User Mentor { get { if (mentor != null) return mentor; using (AppContext db = new AppContext()) { if (mentor == null) mentor = db.Users.Where(t => t.id == MentorId).FirstOrDefault(); return mentor; }; } set { mentor = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stack { class Program { static void Main(string[] args) { int top = -1; string s; int newmember = 0; int[] array = new int[10]; /* do { s = Convert.ToString(Console.ReadLine()); if (s != "x") { array[i] = Convert.ToInt32(s); top++; } } while (i > 10 || s != "x"); s = Convert.ToString(Console.ReadLine());*/ do { Console.WriteLine("Press 'a' to push number "); Console.WriteLine("Press 'b' to pop number "); Console.WriteLine("Press 'c' to verify if stack is empty "); Console.WriteLine("Press 'd' to verify if stack is full "); Console.WriteLine("Press 'i' to view all elements "); Console.WriteLine("Press 'x' for exit "); s = Convert.ToString(Console.ReadLine()); switch (s) { case "a": { if (isFull(top, 10) != 0) { newmember = Convert.ToInt32(Console.ReadLine()); top = Push(top, newmember, array); break; } else { Console.WriteLine("Stack is full"); break; } } case "b": { if (IsEmpty(top) != 0) { Console.WriteLine("Stack is empty"); break; } else { top = Pop(top, array[top], array); break; } // break; } case "c": if (IsEmpty(top) == 0) { Console.WriteLine("Stack has elements"); break; } else { Console.WriteLine("Stack is empty"); break; } //break; case "d": if (isFull(top, 10) != 0) { Console.WriteLine("Stack is not full"); break; } else { Console.WriteLine("Stack is full"); break; } case "i": Peek(top, array); break; } } while (s != "x"); } static int Push(int top, int number,params int[] arr) { arr[top + 1] = number; top = top + 1; return top; } static int Pop(int top, int number, params int[] arr) { Console.WriteLine("Following ellement was deleted from stack"); Console.WriteLine(arr[top]); arr[top] = 0; top = top - 1; return top; } static int IsEmpty(int top) { if (top < 0) { return 1; } else return 0; } static int isFull (int top, int max) { if (top+1 < max) return 1; else return 0; } static void Peek (int top, params int []arr) { for (int i=top;i>=0;i--) { Console.WriteLine("Steck elements:"); Console.WriteLine(arr[i]); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameScreenBehavior : Game { private float m_fCurrentTimeLeft; private Text m_txtTimer; private Text m_txtScore; private GameObject m_backgroundMusic; // Use this for initialization void Start () { m_fCurrentTimeLeft = Game.Rules.MoveTimeLimit; m_txtTimer = GameObject.Find("txt_timer").GetComponent<Text>(); m_txtScore = GameObject.Find("txt_score").GetComponent<Text>(); if(Game.SoundSettings.IsSoundOn == 1) m_backgroundMusic = (GameObject)Instantiate(Resources.Load("Prefabs/backgroundMusic"), new Vector3(0, 0, 0), Quaternion.identity); List<IBloodType> m_generatedBloodTypes = GenerateNewBloodElements(); if(Game.State.CorrectAnswers == 5 && Game.Rules.MoveTimeLimit > Game.Rules.MinReducedTimeLimit) { Game.Rules.MoveTimeLimit -= Game.Rules.MoveTimeLimitReduceAmount; Game.State.CorrectAnswers = 0; } } // Update is called once per frame void Update () { m_txtScore.text = Game.State.CurrentScore.ToString("#.#"); if (m_fCurrentTimeLeft > 0) { m_fCurrentTimeLeft -= Time.deltaTime; m_txtTimer.text = m_fCurrentTimeLeft.ToString("00:##"); } else { // Time is up. m_txtTimer.text = 0.ToString(); Destroy(GameObject.Find("backgroundMusic(Clone)")); SceneManager.LoadScene(Game.Scenes.ScoreScreen); } } List<IBloodType> GenerateNewBloodElements() { List<IBloodType> returnList = new List<IBloodType>(); // Maximum blood type enum index depending to the difficulty level. int maxBloodTypeIndex = 0; int maxGeneratedBloodTypeCount = 4; if (Game.Difficulty.Current == Game.Difficulty.Levels.eDL_EASY) { maxBloodTypeIndex = 2; maxGeneratedBloodTypeCount = 3; } else if (Game.Difficulty.Current == Game.Difficulty.Levels.eDL_MEDIUM) maxBloodTypeIndex = 3; else maxBloodTypeIndex = 7; IBloodType.Type bloodTypeForCapsule = (IBloodType.Type)Random.Range(0, maxBloodTypeIndex); IBloodType m_bloodCapsule = BloodCapsule.CreateInstance(bloodTypeForCapsule, GameObject.Find("capsule_position").transform.position); List<IBloodType.Type> generatedBloodTypes = new List<IBloodType.Type>(); if(Game.Difficulty.Current == Game.Difficulty.Levels.eDL_EASY) { generatedBloodTypes.Add(IBloodType.Type.Arh); generatedBloodTypes.Add(IBloodType.Type.Brh); generatedBloodTypes.Add(IBloodType.Type.ZEROrh); generatedBloodTypes = Utilities<IBloodType.Type>.shuffleList(generatedBloodTypes); } else if (Game.Difficulty.Current == Game.Difficulty.Levels.eDL_MEDIUM) { generatedBloodTypes.Add(IBloodType.Type.Arh); generatedBloodTypes.Add(IBloodType.Type.Brh); generatedBloodTypes.Add(IBloodType.Type.ZEROrh); generatedBloodTypes.Add(IBloodType.Type.ABrh); generatedBloodTypes = Utilities<IBloodType.Type>.shuffleList(generatedBloodTypes); } else { while (generatedBloodTypes.Count < maxGeneratedBloodTypeCount) { IBloodType.Type bloodTypeToGenerate = (IBloodType.Type)Random.Range(0, maxBloodTypeIndex); if (!generatedBloodTypes.Contains(bloodTypeToGenerate)) generatedBloodTypes.Add(bloodTypeToGenerate); } } if(!generatedBloodTypes.Contains(bloodTypeForCapsule)) { int indexToChange = Random.Range(0, generatedBloodTypes.Count); generatedBloodTypes[indexToChange] = bloodTypeForCapsule; } string positionString; if (Game.Difficulty.Current == Game.Difficulty.Levels.eDL_EASY) positionString = "easy_blood_position_"; else positionString = "blood_position_"; int i = 1; foreach (IBloodType.Type bloodType in generatedBloodTypes) { if (bloodType == IBloodType.Type.A) returnList.Add(CBloodTypeA.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else if (bloodType == IBloodType.Type.Arh) returnList.Add(CBloodTypeArh.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else if (bloodType == IBloodType.Type.B) returnList.Add(CBloodTypeB.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else if (bloodType == IBloodType.Type.Brh) returnList.Add(CBloodTypeBrh.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else if (bloodType == IBloodType.Type.AB) returnList.Add(CBloodTypeAB.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else if (bloodType == IBloodType.Type.ABrh) returnList.Add(CBloodTypeABrh.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else if (bloodType == IBloodType.Type.ZERO) returnList.Add(CBloodTypeZero.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); else returnList.Add(CBloodTypeZerorh.CreateInstance(GameObject.Find(positionString + i.ToString()).transform.position)); ++i; } return returnList; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MySql.Data; using MySql.Data.MySqlClient; using System.Data; using System.Threading; using System.Configuration; using System.Windows.Forms; namespace BarcodePrinter2 { class BarcodePrinter { bool flag = true; databaseSQL db2; LabelManager2.Application labelapp = null; static string templatepath = ""; static string processpoint = ""; ~BarcodePrinter() { stopprint(); } public void stopprint() { if (this.db2 != null) this.db2.CloseDB(); if (this.labelapp != null) this.labelapp.Quit(); } public void startprint() { Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //根据Key读取<add>元素的Value templatepath = config.AppSettings.Settings["TemplatePATH"].Value; processpoint = config.AppSettings.Settings["processpoint"].Value; this.db2 = new databaseSQL(); this.db2.SSHConnectMySql(); this.labelapp = new LabelManager2.Application(); //创建lppa.exe进程 System.Timers.Timer t = new System.Timers.Timer(100); t.Elapsed += new System.Timers.ElapsedEventHandler(theout); t.AutoReset = true; //设置是执行一次(false)还是一直执行(true); t.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件; } public void theout(object source, System.Timers.ElapsedEventArgs e) { Thread.Sleep(100); if (flag) { flag = false; String selstr = "select distinct tag_index from list_barcodeprint where print_status=0 and processpoint = '" + processpoint + "'"; DataTable reader = this.db2.Select(selstr); if (reader != null) { if (reader.Rows.Count > 0) { Printbarcode(this.labelapp); } flag = true; } } } public void Printbarcode(LabelManager2.Application labelapp) { try { //db.SSHConnectMySql(); String selstr = "select distinct tag_index from list_barcodeprint where print_status=0 and processpoint = '" + processpoint + "'"; DataTable reader = this.db2.Select(selstr); String itemstr = ""; if (reader != null) { for (int i = 0; i < reader.Rows.Count; i++) { string strPath = templatepath; this.labelapp.Documents.Open(strPath, false); LabelManager2.Document labeldoc = labelapp.ActiveDocument; int vcount = labeldoc.Variables.FormVariables.Count; String selsql1 = "select barcode,varible_index from list_barcodeprint where print_status=0 and tag_index=" + reader.Rows[i][0] + " and processpoint = '" + processpoint + "' order by varible_index"; DataTable reader2 = this.db2.Select(selsql1); if (reader2 != null && (reader2.Rows.Count == vcount)) { for (int j = 0; j < reader2.Rows.Count; j++) { itemstr = "var_" + reader2.Rows[j][1].ToString(); labeldoc.Variables.FormVariables.Item(itemstr).Value = reader2.Rows[j][0].ToString(); } labeldoc.PrintDocument(); //打印一次 labeldoc.FormFeed(); //结束打印 String updatesql1 = "update list_barcodeprint set print_status=1 where print_status=0 and tag_index=" + reader.Rows[i][0] + " and processpoint = '" + processpoint + "'"; this.db2.Update(updatesql1); } //textBox_log.Text += "文档关闭\r\n"; labeldoc.Close(true); } } } catch (Exception exceptions) { MessageBox.Show("打印标签出错,请联系设备管理员处理!"); return; } finally { labelapp.Documents.CloseAll(); } } } }