text
stringlengths
13
6.01M
//--------------------------------------------------------------------------------------------------- // <copyright file="MainWindow.xaml.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // <Description> // This program tracks up to 6 people simultaneously. // If a person is tracked, the associated gesture detector will determine if that person is seated or not. // If any of the 6 positions are not in use, the corresponding gesture detector(s) will be paused // and the 'Not Tracked' image will be displayed in the UI. // </Description> //---------------------------------------------------------------------------------------------------- namespace Microsoft.Samples.Kinect.DiscreteGestureBasics { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using Microsoft.Kinect; using Microsoft.Kinect.VisualGestureBuilder; /// <summary> /// Interaction logic for the MainWindow /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { /// <summary> Active Kinect sensor </summary> private KinectSensor kinectSensor = null; /// <summary> Array for the bodies (Kinect will track up to 6 people simultaneously) </summary> private Body[] bodies = null; /// <summary> Reader for body frames </summary> private BodyFrameReader bodyFrameReader = null; /// <summary> Current status text to display </summary> private string statusText = null; /// <summary> KinectBodyView object which handles drawing the Kinect bodies to a View box in the UI </summary> private KinectBodyView kinectBodyView = null; /// <summary> List of gesture detectors, there will be one detector created for each potential body (max of 6) </summary> private List<GestureDetector> gestureDetectorList = null; /// <summary> /// Initializes a new instance of the MainWindow class /// </summary> public MainWindow() { // only one sensor is currently supported this.kinectSensor = KinectSensor.GetDefault(); // set IsAvailableChanged event notifier this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged; // open the sensor this.kinectSensor.Open(); // set the status text this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText : Properties.Resources.NoSensorStatusText; // open the reader for the body frames this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader(); // set the BodyFramedArrived event notifier this.bodyFrameReader.FrameArrived += this.Reader_BodyFrameArrived; // initialize the BodyViewer object for displaying tracked bodies in the UI this.kinectBodyView = new KinectBodyView(this.kinectSensor); // initialize the gesture detection objects for our gestures this.gestureDetectorList = new List<GestureDetector>(); // initialize the MainWindow this.InitializeComponent(); // set our data context objects for display in UI this.DataContext = this; this.kinectBodyViewbox.DataContext = this.kinectBodyView; // create a gesture detector for each body (6 bodies => 6 detectors) and create content controls to display results in the UI int col0Row = 0; int col1Row = 0; int maxBodies = this.kinectSensor.BodyFrameSource.BodyCount; for (int i = 0; i < maxBodies; ++i) { GestureResultView result = new GestureResultView(i, false, false, 0.0f); GestureDetector detector = new GestureDetector(this.kinectSensor, result); this.gestureDetectorList.Add(detector); // split gesture results across the first two columns of the content grid ContentControl contentControl = new ContentControl(); contentControl.Content = this.gestureDetectorList[i].GestureResultView; if (i % 2 == 0) { // Gesture results for bodies: 0, 2, 4 Grid.SetColumn(contentControl, 0); Grid.SetRow(contentControl, col0Row); ++col0Row; } else { // Gesture results for bodies: 1, 3, 5 Grid.SetColumn(contentControl, 1); Grid.SetRow(contentControl, col1Row); ++col1Row; } this.contentGrid.Children.Add(contentControl); } } /// <summary> /// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the current status text to display /// </summary> public string StatusText { get { return this.statusText; } set { if (this.statusText != value) { this.statusText = value; // notify any bound elements that the text has changed if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); } } } } /// <summary> /// Execute shutdown tasks /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void MainWindow_Closing(object sender, CancelEventArgs e) { if (this.bodyFrameReader != null) { // BodyFrameReader is IDisposable this.bodyFrameReader.FrameArrived -= this.Reader_BodyFrameArrived; this.bodyFrameReader.Dispose(); this.bodyFrameReader = null; } if (this.gestureDetectorList != null) { // The GestureDetector contains disposable members (VisualGestureBuilderFrameSource and VisualGestureBuilderFrameReader) foreach (GestureDetector detector in this.gestureDetectorList) { detector.Dispose(); } this.gestureDetectorList.Clear(); this.gestureDetectorList = null; } if (this.kinectSensor != null) { this.kinectSensor.IsAvailableChanged -= this.Sensor_IsAvailableChanged; this.kinectSensor.Close(); this.kinectSensor = null; } } /// <summary> /// Handles the event when the sensor becomes unavailable (e.g. paused, closed, unplugged). /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void Sensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e) { // on failure, set the status text this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText : Properties.Resources.SensorNotAvailableStatusText; } /// <summary> /// Handles the body frame data arriving from the sensor and updates the associated gesture detector object for each body /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void Reader_BodyFrameArrived(object sender, BodyFrameArrivedEventArgs e) { bool dataReceived = false; using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame()) { if (bodyFrame != null) { if (this.bodies == null) { // creates an array of 6 bodies, which is the max number of bodies that Kinect can track simultaneously this.bodies = new Body[bodyFrame.BodyCount]; } // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array. // As long as those body objects are not disposed and not set to null in the array, // those body objects will be re-used. bodyFrame.GetAndRefreshBodyData(this.bodies); dataReceived = true; } } if (dataReceived) { // visualize the new body data this.kinectBodyView.UpdateBodyFrame(this.bodies); // we may have lost/acquired bodies, so update the corresponding gesture detectors if (this.bodies != null) { // loop through all bodies to see if any of the gesture detectors need to be updated int maxBodies = this.kinectSensor.BodyFrameSource.BodyCount; for (int i = 0; i < maxBodies; ++i) { Body body = this.bodies[i]; ulong trackingId = body.TrackingId; // if the current body TrackingId changed, update the corresponding gesture detector with the new value if (trackingId != this.gestureDetectorList[i].TrackingId) { this.gestureDetectorList[i].TrackingId = trackingId; // if the current body is tracked, unpause its detector to get VisualGestureBuilderFrameArrived events // if the current body is not tracked, pause its detector so we don't waste resources trying to get invalid gesture results this.gestureDetectorList[i].IsPaused = trackingId == 0; } } } } } } }
using System; using System.Linq; using SharpStoreDB; namespace Products { class Program { static void Main() { SharpStoreDBcontex contex = new SharpStoreDBcontex(); //contex.Database.Initialize(true); var knifes = contex.Knives.ToList(); //sb.AppendLine("<div class=\"card-deck\">"); foreach (var knife in knifes) { Console.WriteLine("<div class=\"card\">"); Console.WriteLine($"<img class=\"card-img-top\" src=\"{knife.ImageUrl}\" width=\"200px\"alt=\"Card image cap\">"); Console.WriteLine("<div class=\"card-block\">"); Console.WriteLine($"<h4 class=\"card-title\">{knife.Name}</h4>"); //Console.WriteLine($"<p class=\"card-text\"><a href=\"DetailsPizza.exe?pizzaid={knife.Id}\">Recipe</a></p>"); //Console.WriteLine("<form method=\"POST\">"); //Console.WriteLine($"<div class=\"radio\"><label><input type = \"radio\" name=\"pizzaVote\" value=\"up\">Up</label></div>"); //Console.WriteLine($"<div class=\"radio\"><label><input type = \"radio\" name=\"pizzaVote\" value=\"down\">Down</label></div>"); //Console.WriteLine($"<input type=\"hidden\" name=\"pizzaid\" value=\"{knife.Id}\" />"); //Console.WriteLine("<input type=\"submit\" class=\"btn btn-primary\" value=\"Vote\" />"); //Console.WriteLine("</form>"); Console.WriteLine("</div>"); Console.WriteLine("</div>"); } Console.WriteLine("</div>"); } } }
using OpenTK; using OpenTK.Graphics; using StorybrewCommon.Mapset; using StorybrewCommon.Scripting; using StorybrewCommon.Storyboarding; using StorybrewCommon.Storyboarding.Util; using StorybrewCommon.Subtitles; using StorybrewCommon.Util; using System; using System.Collections.Generic; using System.Linq; namespace StorybrewScripts { public class SimpleFlash : StoryboardObjectGenerator { public override void Generate() { par(39482); par(89656); par(146383); par(181292); par(220565); par(266382); par(288200); par(340564); par(375473); par(416927); par(358018); par(356927); par(257654); par(259836); par(78747); } private void par(int time) { var Layer = GetLayer("Main"); var s = Layer.CreateSprite("SB/Flare.png", OsbOrigin.Centre); s.Move(time,320,240); s.Scale(time,20); s.Fade(time - 200, time,0,0.2); s.Fade(time, time + 2000,0.2,0); s.Additive(time,time + 2000); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kadastr.Data.Model { class MeanSurvey { public int Id { get; set; } /// <summary> /// Наименование прибора(инструмента, аппаратуры) /// </summary> public string Name { get; set; } /// <summary> /// Номер в Государственном реестре средств измерений /// </summary> public string Number { get; set; } /// <summary> /// Срок действия свидетельства /// </summary> public string Duration { get; set; } /// <summary> /// Реквизиты свидетельства о поверке прибора(инструмента, аппаратуры) /// </summary> public string CertificateVerification { get; set; } } }
//@Author Justin Scott Bieshaar. //For further questions please read comments or reach me via mail contact@justinbieshaar.com using UnityEngine; using System.Collections.Generic; using XInputDotNetPure; using Exam.Reference.Path; public class PlayerInformation { /// <summary> /// get; private set; /// </summary> public PlayerIndex PlayerIndex { get; private set; } public bool isSaboteur = false; /// <summary> /// Get player index int /// </summary> /// <value>The player I.</value> public int PlayerID { get { switch (this.PlayerIndex) { // no need to break because of returns case PlayerIndex.One: return 0; case PlayerIndex.Two: return 1; case PlayerIndex.Three: return 2; case PlayerIndex.Four: return 3; default: return 0; } } } /// <summary> /// Gets the state of the player. /// </summary> public GamePadState PlayerState { get { return GamePad.GetState(PlayerIndex); } } /// <summary> /// get; private set; /// </summary> /// <value>The selected character path.</value> public string SelectedCharacterPath { get; private set; } public void SetSelectedCharacterPath(CharacterType iCharacterType) { this.SelectedCharacterPath = CharacterPaths.CHARACTER_PATH[iCharacterType]; Debug.Log(CharacterPaths.CHARACTER_PATH[iCharacterType]); } /// <summary> /// Gets a value indicating whether this instance is connected. /// </summary> /// <value><c>true</c> if this instance is connected; otherwise, <c>false</c>.</value> public bool IsConnected { get { return PlayerState.IsConnected; } } /// <summary> /// Initialize information /// </summary> /// <param name="iPlayerIndex"></param> /// <param name="iCharacterType"></param> /// <returns></returns> public PlayerInformation Init(PlayerIndex iPlayerIndex, CharacterType iCharacterType = CharacterType.CHARACTER_YELLOW) { this.PlayerIndex = iPlayerIndex; this.SelectedCharacterPath = CharacterPaths.CHARACTER_PATH[iCharacterType]; return this; } }
namespace Brambillator.Historiarum.Domain.Lookups { public enum MediaType : byte { Text = 0, Audio = 1, Video = 2, Title = 3, Subtitle = 4 } }
using Unity.Entities; public struct PlayerComponent : IComponentData { public float MoveSpeed; public float MaxAngularSpeed; } public struct PlayerIndex : IComponentData { public int Value; } public struct Health : IComponentData { public int Value; } public struct EquippedWeapon : IComponentData { public Entity Entity; } public struct EquippedAbility : IComponentData { public Entity Entity; }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class EndScene : MonoBehaviour { public float delay; public void Awake() { StartCoroutine(WaitForCreditsEnd(delay)); } IEnumerator WaitForCreditsEnd(float delay) { print(Time.time); yield return new WaitForSecondsRealtime(delay); print(Time.time); SceneManager.LoadScene(0); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Cashflow9000.Fragments; namespace Cashflow9000 { public abstract class ItemActivity<T> : Activity, IItemFragmentListener<T> { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ItemActivity); FragmentUtil.LoadFragment(this, Resource.Id.container, GetFragment(Intent.GetIntExtra(GetExtraId(), -1))); } protected abstract Fragment GetFragment(int id); protected abstract string GetExtraId(); public void ItemSaved(T item) { CashflowData.InsertOrReplace(item); Finish(); } public void ItemDeleted(T item) { CashflowData.Delete(item); Finish(); } } }
using SoulHunter.Dialogue; using UnityEngine; public class EndGameCondition : MonoBehaviour { private void OnDestroy() { SceneController.Instance.TransitionScene(0); } }
using OctoFX.Core.Model; namespace OctoFX.Core.Repository { public interface IDealsRepository : IOctoFXRepository<Deal> { } public class DealsRepository : OctoFXRepository<Deal>, IDealsRepository { public DealsRepository(OctoFXContext context) { Context = context; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FinalDoor : MonoBehaviour { //three different pathways List<int> PathOne = new List<int>() { 1, 2, 1, 2, 1, 4, 1, 4, 1, 4, 1 }; List<int> PathTwo = new List<int>() { 1, 2, 1, 1, 4, 1, 4, 1, 4, 1, 2, 3, 2, 1, 2, 1, 4, 1, 4, 1}; List<int> PathThree = new List<int>() { 1, 2, 1, 1, 1, 4, 1, 1, 2, 1, 4 , 1, 4, 1}; int counterEqual1 = 0; int counterEqual2 = 0; int counterEqual3 = 0; int counterTotal = 0; public bool doorOpen = false; //public list public List<int> TempList = new List<int>(); private Animator anim; bool animPlayed = false; // Start is called before the first frame update void Start() { anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { //reset counters counterEqual1 = 0; counterEqual2 = 0; counterEqual3 = 0; counterTotal = 0; //run if the door is still closed if (doorOpen == false) { foreach (int i in TempList) { if (counterTotal < 10) { if (i == PathOne[counterTotal]) { counterEqual1++; //if the two spots in the lists are the same, increse counter } } if (counterTotal < 19) { if (i == PathTwo[counterTotal]) { counterEqual2++; } } if (counterTotal < 13) { if (i == PathOne[counterTotal]) { counterEqual3++; } } counterTotal++; } } if (counterEqual1 == 10) doorOpen = true; else if (counterEqual2 == 19) doorOpen = true; else if (counterEqual3 == 13) doorOpen = true; if (doorOpen == true && animPlayed == false) //play animation if one of the lists is equal { animPlayed = true; anim.Play("door_2_open"); } else if (animPlayed == true) anim.Play("door_2_opened"); } }
using System; using System.ComponentModel; using System.IO; namespace AsyncClasses.EventArgs { /// <summary> /// EventArgs class for returning the result of asynchronous calls to load a DataTable for display in the Clipboard /// grid. /// </summary> public class GetDataCompletedEventArgs : AsyncCompletedEventArgs { #region Public Properties /// <summary> /// Gets the serialized data to be displayed in the grid. /// </summary> public readonly MemoryStream Data; /// <summary> /// Gets the current instance. /// </summary> public readonly int Instance; #endregion #region Constructors /// <summary> /// Creates a new instance of GetDataCompletedEventArgs. /// </summary> /// <param name="data">The data to send.</param> /// <param name="instance">The current instance.</param> /// <param name="e">Exceptions, if any, that occurred during processing.</param> /// <param name="cancelled">Flag indicating whether the operation was cancelled.</param> /// <param name="userState">The user state.</param> public GetDataCompletedEventArgs(MemoryStream data, int instance, Exception e, bool cancelled, object userState) : base(e, cancelled, userState) { Data = data; Instance = instance; //Only throw the exception if we are not cancelling. if (!cancelled) RaiseExceptionIfNecessary(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace AnythingButCreed { class Program { static void Main(string[] args) { var allSongs = new List<Song>(); allSongs.Add(new Song("Creed", "With Arms Wide Open")); allSongs.Add(new Song("Creed", "Higher")); allSongs.Add(new Song("Gorillaz", "Welcome To The World of the Plastic Beach")); allSongs.Add(new Song("Gorillaz", "White Flag")); allSongs.Add(new Song("Gorillaz", "Rhinestone Eyes")); allSongs.Add(new Song("Gorillaz", "Stylo")); allSongs.Add(new Song("Gorillaz", "Superfast Jellyfish")); allSongs.Add(new Song("Gorillaz", "Empire Ants")); allSongs.Add(new Song("Gorillaz", "Glitter Freeze")); allSongs.Add(new Song("Gorillaz", "Some Kind of Nature")); allSongs.Add(new Song("Gorillaz", "On Melancholy Hill")); allSongs.Add(new Song("Gorillaz", "Broken")); var goodSongs = new List<Song>(); goodSongs.AddRange(allSongs.Where(song => song.Artist != "Creed")); foreach (var song in goodSongs) { Console.WriteLine($"{song.Artist}: {song.Title}"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; public class VideoIntroScript : MonoBehaviour { Vector3 initPos; VideoPlayer video; Vector3 videoInitPos; public float Duration = 1f; private float time = 0f; private bool forward = true; public float MovementDistance = 100f; public AnimationCurve MovementCurve; public bool PingPong = true; void Start() { initPos = transform.position; video = GetComponentInChildren<VideoPlayer>(); videoInitPos = video.transform.position; } void Update() { if (time > Duration) { time = Duration; if (PingPong) { forward = false; } else { gameObject.SetActive(false); video.Stop(); } } else { } if (time < 0) { gameObject.SetActive(false); video.Stop(); return; } if (forward) { time += Time.deltaTime; } else { time -= Time.deltaTime; } float percentage = MovementCurve.Evaluate(time / Duration); transform.position = initPos + Vector3.right * MovementDistance * percentage; video.transform.position = videoInitPos; } public void Restart() { time = 0; forward = true; video.Play(); gameObject.SetActive(true); } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; namespace Cryptlex { public static class LexActivator { public enum PermissionFlags : uint { LA_USER = 1, LA_SYSTEM = 2, LA_IN_MEMORY = 4 } public enum ReleaseFlags : uint { LA_RELEASES_ALL = 1, LA_RELEASES_ALLOWED = 2 } private const int MetadataBufferSize = 4096; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void CallbackType(uint status); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void InternalReleaseCallbackAType(uint status, string releaseJson, IntPtr _userData); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void InternalReleaseCallbackType(uint status, IntPtr releaseJson, IntPtr _userData); public delegate void ReleaseUpdateCallbackType(uint status, Release release, object userData); /* To prevent garbage collection of delegate, need to keep a reference */ static readonly List<CallbackType> callbackList = new List<CallbackType>(); static readonly List<InternalReleaseCallbackAType> internalReleaseCallbackAList = new List<InternalReleaseCallbackAType>(); static readonly List<InternalReleaseCallbackType> internalReleaseCallbackList = new List<InternalReleaseCallbackType>(); /// <summary> /// Sets the absolute path of the Product.dat file. /// /// This function must be called on every start of your program /// before any other functions are called. /// </summary> /// <param name="filePath">absolute path of the product file (Product.dat)</param> public static void SetProductFile(string filePath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetProductFile_x86(filePath) : LexActivatorNative.SetProductFile(filePath); } else { status = LexActivatorNative.SetProductFileA(filePath); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Embeds the Product.dat file in the application. /// /// It can be used instead of SetProductFile() in case you want /// to embed the Product.dat file in your application. /// /// This function must be called on every start of your program /// before any other functions are called. /// </summary> /// <param name="productData">content of the Product.dat file</param> public static void SetProductData(string productData) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetProductData_x86(productData) : LexActivatorNative.SetProductData(productData); } else { status = LexActivatorNative.SetProductDataA(productData); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the product id of your application. /// /// This function must be called on every start of your program before /// any other functions are called, with the exception of SetProductFile() /// or SetProductData() function. /// </summary> /// <param name="productId">the unique product id of your application as mentioned on the product page in the dashboard</param> /// <param name="flags">depending upon whether your application requires admin/root permissions to run or not, this parameter can have one of the following values: LA_SYSTEM, LA_USER, LA_IN_MEMORY</param> public static void SetProductId(string productId, PermissionFlags flags) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetProductId_x86(productId, flags) : LexActivatorNative.SetProductId(productId, flags); } else { status = LexActivatorNative.SetProductIdA(productId, flags); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// In case you want to change the default directory used by LexActivator to /// store the activation data on Linux and macOS, this function can be used to /// set a different directory. /// If you decide to use this function, then it must be called on every start of /// your program before calling SetProductFile() or SetProductData() function. /// Please ensure that the directory exists and your app has read and write /// permissions in the directory. /// </summary> /// <param name="directoryPath">absolute path of the directory.</param> public static void SetDataDirectory(string directoryPath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetDataDirectory_x86(directoryPath) : LexActivatorNative.SetDataDirectory(directoryPath); } else { status = LexActivatorNative.SetDataDirectoryA(directoryPath); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Enables network logs. /// This function should be used for network testing only in case of network errors. /// By default logging is disabled. /// </summary> /// <param name="enable">0 or 1 to disable or enable logging.</param> public static void SetDebugMode(uint enable) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetDebugMode_x86(enable) : LexActivatorNative.SetDebugMode(enable); } else { status = LexActivatorNative.SetDebugMode(enable); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// In case you don't want to use the LexActivator's advanced /// device fingerprinting algorithm, this function can be used to set a custom /// device fingerprint. /// If you decide to use your own custom device fingerprint then this function must be /// called on every start of your program immediately after calling SetProductFile() /// or SetProductData() function. /// The license fingerprint matching strategy is ignored if this function is used. /// </summary> /// <param name="fingerprint">string of minimum length 64 characters and maximum length 256 characters</param> public static void SetCustomDeviceFingerprint(string fingerprint) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetCustomDeviceFingerprint_x86(fingerprint) : LexActivatorNative.SetCustomDeviceFingerprint(fingerprint); } else { status = LexActivatorNative.SetCustomDeviceFingerprintA(fingerprint); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the license key required to activate the license. /// </summary> /// <param name="licenseKey">a valid license key</param> public static void SetLicenseKey(string licenseKey) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetLicenseKey_x86(licenseKey) : LexActivatorNative.SetLicenseKey(licenseKey); } else { status = LexActivatorNative.SetLicenseKeyA(licenseKey); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the license user email and password for authentication. /// /// This function must be called before ActivateLicense() or IsLicenseGenuine() /// function if 'requireAuthentication' property of the license is set to true. /// </summary> /// <param name="email">user email address</param> /// <param name="password">user password</param> public static void SetLicenseUserCredential(string email, string password) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetLicenseUserCredential_x86(email, password) : LexActivatorNative.SetLicenseUserCredential(email, password); } else { status = LexActivatorNative.SetLicenseUserCredentialA(email, password); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets server sync callback function. /// /// Whenever the server sync occurs in a separate thread, and server returns the response, /// license callback function gets invoked with the following status codes: /// LA_OK, LA_EXPIRED, LA_SUSPENDED, LA_E_REVOKED, LA_E_ACTIVATION_NOT_FOUND, /// LA_E_MACHINE_FINGERPRINT, LA_E_AUTHENTICATION_FAILED, LA_E_COUNTRY, LA_E_INET, /// LA_E_SERVER, LA_E_RATE_LIMIT, LA_E_IP /// </summary> /// <param name="callback"></param> public static void SetLicenseCallback(CallbackType callback) { var wrappedCallback = callback; #if NETFRAMEWORK var syncTarget = callback.Target as System.Windows.Forms.Control; if (syncTarget != null) { wrappedCallback = (v) => syncTarget.Invoke(callback, new object[] { v }); } #endif callbackList.Add(wrappedCallback); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetLicenseCallback_x86(wrappedCallback) : LexActivatorNative.SetLicenseCallback(wrappedCallback); } else { status = LexActivatorNative.SetLicenseCallback(wrappedCallback); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the lease duration for the activation. /// /// The activation lease duration is honoured when the allow client /// lease duration property is enabled. /// </summary> /// <param name="leaseDuration"></param> public static void SetActivationLeaseDuration(uint leaseDuration) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetActivationLeaseDuration_x86(leaseDuration) : LexActivatorNative.SetActivationLeaseDuration(leaseDuration); } else { status = LexActivatorNative.SetActivationLeaseDuration(leaseDuration); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the activation metadata. /// /// The metadata appears along with the activation details of the license /// in dashboard. /// </summary> /// <param name="key">string of maximum length 256 characters with utf-8 encoding</param> /// <param name="value">string of maximum length 256 characters with utf-8 encoding</param> public static void SetActivationMetadata(string key, string value) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetActivationMetadata_x86(key, value) : LexActivatorNative.SetActivationMetadata(key, value); } else { status = LexActivatorNative.SetActivationMetadataA(key, value); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the trial activation metadata. /// /// The metadata appears along with the trial activation details of the product /// in dashboard. /// </summary> /// <param name="key">string of maximum length 256 characters with utf-8 encoding</param> /// <param name="value">string of maximum length 256 characters with utf-8 encoding</param> public static void SetTrialActivationMetadata(string key, string value) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetTrialActivationMetadata_x86(key, value) : LexActivatorNative.SetTrialActivationMetadata(key, value); } else { status = LexActivatorNative.SetTrialActivationMetadataA(key, value); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the current app version of your application. /// /// The app version appears along with the activation details in dashboard. It /// is also used to generate app analytics. /// </summary> /// <param name="appVersion"></param> public static void SetAppVersion(string appVersion) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetAppVersion_x86(appVersion) : LexActivatorNative.SetAppVersion(appVersion); } else { status = LexActivatorNative.SetAppVersionA(appVersion); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the current release version of your application. /// /// The release version appears along with the activation details in dashboard. /// </summary> /// <param name="releaseVersion"> string in following allowed formats: x.x, x.x.x, x.x.x.x </param> public static void SetReleaseVersion(string releaseVersion) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetReleaseVersion_x86(releaseVersion) : LexActivatorNative.SetReleaseVersion(releaseVersion); } else { status = LexActivatorNative.SetReleaseVersionA(releaseVersion); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the release published date of your application. /// /// </summary> /// <param name="releasePublishedDate"> unix timestamp of release published date. </param> public static void SetReleasePublishedDate(uint releasePublishedDate) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetReleasePublishedDate_x86(releasePublishedDate) : LexActivatorNative.SetReleasePublishedDate(releasePublishedDate); } else { status = LexActivatorNative.SetReleasePublishedDate(releasePublishedDate); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the release platform e.g. windows, macos, linux /// /// The release platform appears along with the activation details in dashboard.. /// </summary> /// <param name="releasePlatform"> release platform e.g. windows, macos, linux public static void SetReleasePlatform(string releasePlatform) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetReleasePlatform_x86(releasePlatform) : LexActivatorNative.SetReleasePlatform(releasePlatform); } else { status = LexActivatorNative.SetReleasePlatformA(releasePlatform); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the release channel e.g. stable, beta /// /// The release channel appears along with the activation details in dashboard.. /// </summary> /// <param name="releaseChannel"> release channel e.g. stable public static void SetReleaseChannel(string releaseChannel) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetReleaseChannel_x86(releaseChannel) : LexActivatorNative.SetReleaseChannel(releaseChannel); } else { status = LexActivatorNative.SetReleaseChannelA(releaseChannel); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the meter attribute uses for the offline activation request. /// /// This function should only be called before GenerateOfflineActivationRequest() /// function to set the meter attributes in case of offline activation. /// </summary> /// <param name="name">name of the meter attribute</param> /// <param name="uses">the uses value</param> public static void SetOfflineActivationRequestMeterAttributeUses(string name, uint uses) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetOfflineActivationRequestMeterAttributeUses_x86(name, uses) : LexActivatorNative.SetOfflineActivationRequestMeterAttributeUses(name, uses); } else { status = LexActivatorNative.SetOfflineActivationRequestMeterAttributeUsesA(name, uses); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the network proxy to be used when contacting Cryptlex servers. /// /// The proxy format should be: [protocol://][username:password@]machine[:port] /// /// NOTE: Proxy settings of the computer are automatically detected. So, in most of the /// cases you don't need to care whether your user is behind a proxy server or not. /// </summary> /// <param name="proxy">proxy string having correct proxy format</param> public static void SetNetworkProxy(string proxy) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetNetworkProxy_x86(proxy) : LexActivatorNative.SetNetworkProxy(proxy); } else { status = LexActivatorNative.SetNetworkProxyA(proxy); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// In case you are running Cryptlex on-premise, you can set the host for your on-premise server. /// /// </summary> /// <param name="host">the address of the Cryptlex on-premise server</param> public static void SetCryptlexHost(string host) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetCryptlexHost_x86(host) : LexActivatorNative.SetCryptlexHost(host); } else { status = LexActivatorNative.SetCryptlexHostA(host); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Sets the two-factor authentication code for the user authentication. /// /// </summary> /// <param name="twoFactorAuthenticationCode">the 2FA code</param> public static void SetTwoFactorAuthenticationCode(string twoFactorAuthenticationCode) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.SetTwoFactorAuthenticationCode_x86(twoFactorAuthenticationCode) : LexActivatorNative.SetTwoFactorAuthenticationCode(twoFactorAuthenticationCode); } else { status = LexActivatorNative.SetTwoFactorAuthenticationCodeA(twoFactorAuthenticationCode); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Gets the product metadata as set in the dashboard. /// /// This is available for trial as well as license activations. /// </summary> /// <param name="key">metadata key to retrieve the value</param> /// <returns>Returns the value of metadata for the key.</returns> public static string GetProductMetadata(string key) { var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetProductMetadata_x86(key, builder, builder.Capacity) : LexActivatorNative.GetProductMetadata(key, builder, builder.Capacity); } else { status = LexActivatorNative.GetProductMetadataA(key, builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the product version name. /// </summary> /// <returns>Returns the value of the product version name.</returns> public static string GetProductVersionName() { var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetProductVersionName_x86(builder, builder.Capacity) : LexActivatorNative.GetProductVersionName(builder, builder.Capacity); } else { status = LexActivatorNative.GetProductVersionNameA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the product version display name. /// </summary> /// <returns>Returns the value of the product version display name.</returns> public static string GetProductVersionDisplayName() { var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetProductVersionDisplayName_x86(builder, builder.Capacity) : LexActivatorNative.GetProductVersionDisplayName(builder, builder.Capacity); } else { status = LexActivatorNative.GetProductVersionDisplayNameA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the product version feature flag. /// </summary> /// <param name="name">name of the product version feature flag</param> /// <returns>Returns the product version feature flag.</returns> public static ProductVersionFeatureFlag GetProductVersionFeatureFlag(string name) { uint enabled = 0; var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetProductVersionFeatureFlag_x86(name, ref enabled, builder, builder.Capacity) : LexActivatorNative.GetProductVersionFeatureFlag(name, ref enabled, builder, builder.Capacity); } else { status = LexActivatorNative.GetProductVersionFeatureFlagA(name, ref enabled, builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return new ProductVersionFeatureFlag(name, enabled > 0, builder.ToString()); } throw new LexActivatorException(status); } /// <summary> /// Gets the license metadata of the license. /// </summary> /// <param name="key">metadata key to retrieve the value</param> /// <returns>Returns the value of metadata for the key.</returns> public static string GetLicenseMetadata(string key) { var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseMetadata_x86(key, builder, builder.Capacity) : LexActivatorNative.GetLicenseMetadata(key, builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseMetadataA(key, builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the license meter attribute allowed, total and gross uses. /// </summary> /// <param name="name">name of the meter attribute</param> /// <returns>Returns the values of meter attribute allowed, total and gross uses.</returns> public static LicenseMeterAttribute GetLicenseMeterAttribute(string name) { uint allowedUses = 0, totalUses = 0, grossUses = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseMeterAttribute_x86(name, ref allowedUses, ref totalUses, ref grossUses) : LexActivatorNative.GetLicenseMeterAttribute(name, ref allowedUses, ref totalUses, ref grossUses); } else { status = LexActivatorNative.GetLicenseMeterAttributeA(name, ref allowedUses, ref totalUses, ref grossUses); } if (LexStatusCodes.LA_OK == status) { return new LicenseMeterAttribute(name, allowedUses, totalUses, grossUses); } throw new LexActivatorException(status); } /// <summary> /// Gets the license key used for activation. /// </summary> /// <returns>Returns the license key.</returns> public static string GetLicenseKey() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseKey_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseKey(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseKeyA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the allowed activations of the license. /// </summary> /// <returns>Returns the allowed activations.</returns> public static uint GetLicenseAllowedActivations() { uint allowedActivations = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseAllowedActivations_x86(ref allowedActivations) : LexActivatorNative.GetLicenseAllowedActivations(ref allowedActivations); } else { status = LexActivatorNative.GetLicenseAllowedActivations(ref allowedActivations); } switch (status) { case LexStatusCodes.LA_OK: return allowedActivations; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the total activations of the license. /// </summary> /// <returns>Returns the total activations.</returns> public static uint GetLicenseTotalActivations() { uint totalActivations = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseTotalActivations_x86(ref totalActivations) : LexActivatorNative.GetLicenseTotalActivations(ref totalActivations); } else { status = LexActivatorNative.GetLicenseTotalActivations(ref totalActivations); } switch (status) { case LexStatusCodes.LA_OK: return totalActivations; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the license creation date timestamp. /// </summary> /// <returns>Returns the timestamp.</returns> public static uint GetLicenseCreationDate() { uint creationDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseCreationDate_x86(ref creationDate) : LexActivatorNative.GetLicenseCreationDate(ref creationDate); } else { status = LexActivatorNative.GetLicenseCreationDate(ref creationDate); } switch (status) { case LexStatusCodes.LA_OK: return creationDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the activation creation date timestamp. /// </summary> /// <returns>Returns the timestamp.</returns> public static uint GetLicenseActivationDate() { uint activationDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseActivationDate_x86(ref activationDate) : LexActivatorNative.GetLicenseActivationDate(ref activationDate); } else { status = LexActivatorNative.GetLicenseActivationDate(ref activationDate); } switch (status) { case LexStatusCodes.LA_OK: return activationDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the license expiry date timestamp. /// </summary> /// <returns>Returns the timestamp.</returns> public static uint GetLicenseExpiryDate() { uint expiryDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseExpiryDate_x86(ref expiryDate) : LexActivatorNative.GetLicenseExpiryDate(ref expiryDate); } else { status = LexActivatorNative.GetLicenseExpiryDate(ref expiryDate); } switch (status) { case LexStatusCodes.LA_OK: return expiryDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the license maintenance expiry date timestamp. /// </summary> /// <returns>Returns the timestamp.</returns> public static uint GetLicenseMaintenanceExpiryDate() { uint maintenanceExpiryDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseMaintenanceExpiryDate_x86(ref maintenanceExpiryDate) : LexActivatorNative.GetLicenseMaintenanceExpiryDate(ref maintenanceExpiryDate); } else { status = LexActivatorNative.GetLicenseMaintenanceExpiryDate(ref maintenanceExpiryDate); } switch (status) { case LexStatusCodes.LA_OK: return maintenanceExpiryDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the maximum allowed release version of the license. /// </summary> /// <returns>Returns the max allowed release version.</returns> public static string GetLicenseMaxAllowedReleaseVersion() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseMaxAllowedReleaseVersion_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseMaxAllowedReleaseVersion(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseMaxAllowedReleaseVersionA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the email associated with the license user. /// </summary> /// <returns>Returns the license user email.</returns> public static string GetLicenseUserEmail() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseUserEmail_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseUserEmail(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseUserEmailA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the name associated with the license user. /// </summary> /// <returns>Returns the license user name.</returns> public static string GetLicenseUserName() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseUserName_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseUserName(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseUserNameA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the company associated with the license user. /// </summary> /// <returns>Returns the license user company.</returns> public static string GetLicenseUserCompany() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseUserCompany_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseUserCompany(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseUserCompanyA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the metadata associated with the license user. /// </summary> /// <param name="key">key to retrieve the value</param> /// <returns>Returns the value of metadata for the key.</returns> public static string GetLicenseUserMetadata(string key) { var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseUserMetadata_x86(key, builder, builder.Capacity) : LexActivatorNative.GetLicenseUserMetadata(key, builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseUserMetadataA(key, builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the name associated with the license organization. /// </summary> /// <returns>Returns the license organization name.</returns> public static string GetLicenseOrganizationName() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseOrganizationName_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseOrganizationName(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseOrganizationNameA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the license organization address. /// </summary> /// <returns>Returns the license organization address.</returns> public static OrganizationAddress GetLicenseOrganizationAddress() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseOrganizationAddressInternal_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseOrganizationAddressInternal(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseOrganizationAddressInternalA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { string jsonAddress = builder.ToString(); if (jsonAddress.Length > 0) { OrganizationAddress organizationAddress = null; organizationAddress = JsonConvert.DeserializeObject<OrganizationAddress>(jsonAddress); return organizationAddress; } return null; } throw new LexActivatorException(status); } /// <summary> /// Gets the user licenses for the product. /// /// This function sends a network request to Cryptlex servers to get the licenses. /// /// Make sure AuthenticateUser() function is called before calling this function. /// </summary> /// <returns>Returns the list of user licenses.</returns> public static List<UserLicense> GetUserLicenses() { var builder = new StringBuilder(4096); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetUserLicensesInternal_x86(builder, builder.Capacity) : LexActivatorNative.GetUserLicensesInternal(builder, builder.Capacity); } else { status = LexActivatorNative.GetUserLicensesInternalA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { string userLicensesJson = builder.ToString(); List<UserLicense> userLicenses = new List<UserLicense>(); if (!string.IsNullOrEmpty(userLicensesJson)) { userLicenses = JsonConvert.DeserializeObject<List<UserLicense>>(userLicensesJson); return userLicenses; } return userLicenses; } throw new LexActivatorException(status); } /// <summary> /// Gets the license type (node-locked or hosted-floating). /// </summary> /// <returns>Returns the license type.</returns> public static string GetLicenseType() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLicenseType_x86(builder, builder.Capacity) : LexActivatorNative.GetLicenseType(builder, builder.Capacity); } else { status = LexActivatorNative.GetLicenseTypeA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the activation metadata. /// </summary> /// <param name="key">key to retrieve the value</param> /// <returns>Returns the value of metadata for the key.</returns> public static string GetActivationMetadata(string key) { var builder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetActivationMetadata_x86(key, builder, builder.Capacity) : LexActivatorNative.GetActivationMetadata(key, builder, builder.Capacity); } else { status = LexActivatorNative.GetActivationMetadataA(key, builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the initial and current mode of activation (online or offline). /// </summary> /// <returns>Returns the activation mode.</returns> public static ActivationMode GetActivationMode() { var initialModeBuilder = new StringBuilder(MetadataBufferSize); var currentModeBuilder = new StringBuilder(MetadataBufferSize); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetActivationMode_x86(initialModeBuilder, initialModeBuilder.Capacity, currentModeBuilder, currentModeBuilder.Capacity) : LexActivatorNative.GetActivationMode(initialModeBuilder, initialModeBuilder.Capacity, currentModeBuilder, currentModeBuilder.Capacity); } else { status = LexActivatorNative.GetActivationModeA(initialModeBuilder, initialModeBuilder.Capacity, currentModeBuilder, currentModeBuilder.Capacity); } if (LexStatusCodes.LA_OK == status) { return new ActivationMode(initialModeBuilder.ToString(), currentModeBuilder.ToString()); } throw new LexActivatorException(status); } /// <summary> /// Gets the meter attribute uses consumed by the activation. /// </summary> /// <param name="name"></param> /// <returns>Returns the value of meter attribute uses by the activation.</returns> public static uint GetActivationMeterAttributeUses(string name) { uint uses = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetActivationMeterAttributeUses_x86(name, ref uses) : LexActivatorNative.GetActivationMeterAttributeUses(name, ref uses); } else { status = LexActivatorNative.GetActivationMeterAttributeUsesA(name, ref uses); } if (LexStatusCodes.LA_OK == status) { return uses; } throw new LexActivatorException(status); } /// <summary> /// Gets the server sync grace period expiry date timestamp. /// </summary> /// <returns>Returns server sync grace period expiry date timestamp.</returns> public static uint GetServerSyncGracePeriodExpiryDate() { uint expiryDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetServerSyncGracePeriodExpiryDate_x86(ref expiryDate) : LexActivatorNative.GetServerSyncGracePeriodExpiryDate(ref expiryDate); } else { status = LexActivatorNative.GetServerSyncGracePeriodExpiryDate(ref expiryDate); } switch (status) { case LexStatusCodes.LA_OK: return expiryDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the trial activation metadata. /// </summary> /// <param name="key">key to retrieve the value</param> /// <returns>Returns the value of metadata for the key.</returns> public static string GetTrialActivationMetadata(string key) { var builder = new StringBuilder(4096); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetTrialActivationMetadata_x86(key, builder, builder.Capacity) : LexActivatorNative.GetTrialActivationMetadata(key, builder, builder.Capacity); } else { status = LexActivatorNative.GetTrialActivationMetadataA(key, builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the trial expiry date timestamp. /// </summary> /// <returns>Returns trial expiry date timestamp.</returns> public static uint GetTrialExpiryDate() { uint trialExpiryDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetTrialExpiryDate_x86(ref trialExpiryDate) : LexActivatorNative.GetTrialExpiryDate(ref trialExpiryDate); } else { status = LexActivatorNative.GetTrialExpiryDate(ref trialExpiryDate); } switch (status) { case LexStatusCodes.LA_OK: return trialExpiryDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the trial activation id. Used in case of trial extension. /// </summary> /// <returns>Returns the trial id.</returns> public static string GetTrialId() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetTrialId_x86(builder, builder.Capacity) : LexActivatorNative.GetTrialId(builder, builder.Capacity); } else { status = LexActivatorNative.GetTrialIdA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Gets the trial expiry date timestamp. /// </summary> /// <returns>Returns trial expiry date timestamp.</returns> public static uint GetLocalTrialExpiryDate() { uint trialExpiryDate = 0; int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLocalTrialExpiryDate_x86(ref trialExpiryDate) : LexActivatorNative.GetLocalTrialExpiryDate(ref trialExpiryDate); } else { status = LexActivatorNative.GetLocalTrialExpiryDate(ref trialExpiryDate); } switch (status) { case LexStatusCodes.LA_OK: return trialExpiryDate; case LexStatusCodes.LA_FAIL: return 0; default: throw new LexActivatorException(status); } } /// <summary> /// Gets the version of this library. /// </summary> /// <returns>Returns the version of this library.</returns> public static string GetLibraryVersion() { var builder = new StringBuilder(512); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GetLibraryVersion_x86(builder, builder.Capacity) : LexActivatorNative.GetLibraryVersion(builder, builder.Capacity); } else { status = LexActivatorNative.GetLibraryVersionA(builder, builder.Capacity); } if (LexStatusCodes.LA_OK == status) { return builder.ToString(); } throw new LexActivatorException(status); } /// <summary> /// Checks whether a new release is available for the product. /// /// This function should only be used if you manage your releases through /// Cryptlex release management API. /// /// When this function is called the release update callback function gets invoked /// which passes the following parameters: /// /// status - determines if any update is available or not. It also determines whether /// an update is allowed or not. Expected values are LA_RELEASE_UPDATE_AVAILABLE, /// LA_RELEASE_UPDATE_NOT_AVAILABLE, LA_RELEASE_UPDATE_AVAILABLE_NOT_ALLOWED. /// /// release - object of the latest available release, depending on the /// flag LA_RELEASES_ALLOWED or LA_RELEASES_ALL passed to the CheckReleaseUpdate(). /// /// userData - data that is passed to the callback function when it is registered /// using the CheckReleaseUpdate function. This parameter is optional and can be null if no user data /// is passed to the CheckReleaseUpdate function. /// </summary> /// <param name="releaseUpdateCallback">name of the callback function</param> /// <param name="releaseFlags">if an update only related to the allowed release is required, then use LA_RELEASES_ALLOWED. Otherwise, if an update for all the releases is required, then use LA_RELEASES_ALL.</param> /// <param name="userData">data that can be passed to the callback function. This parameter has to be null if no user data needs to be passed to the callback.</param> public static void CheckReleaseUpdate(ReleaseUpdateCallbackType releaseUpdateCallback, ReleaseFlags releaseFlags, object userData) { InternalReleaseCallbackType internalReleaseCallback = (releaseStatus, releaseJson, _userData) => { string releaseJsonString = Marshal.PtrToStringUni(releaseJson); Release release = null; release = JsonConvert.DeserializeObject<Release>(releaseJsonString); var wrappedCallback = releaseUpdateCallback; #if NETFRAMEWORK var syncTarget = releaseUpdateCallback.Target as System.Windows.Forms.Control; if (syncTarget != null) { wrappedCallback = (u, v, w) => syncTarget.Invoke(releaseUpdateCallback, new object[] {u, v, w}); } #endif wrappedCallback(releaseStatus, release, userData); }; internalReleaseCallbackList.Add(internalReleaseCallback); InternalReleaseCallbackAType internalReleaseCallbackA = (releaseStatus, releaseJson, _userData) => { Release release = null; release = JsonConvert.DeserializeObject<Release>(releaseJson); releaseUpdateCallback(releaseStatus, release, userData); }; internalReleaseCallbackAList.Add(internalReleaseCallbackA); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.CheckReleaseUpdateInternal_x86(internalReleaseCallback, releaseFlags, IntPtr.Zero) : LexActivatorNative.CheckReleaseUpdateInternal(internalReleaseCallback, releaseFlags, IntPtr.Zero); } else { status = LexActivatorNative.CheckReleaseUpdateInternalA(internalReleaseCallbackA, releaseFlags, IntPtr.Zero); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Checks whether a new release is available for the product. /// /// This function should only be used if you manage your releases through /// Cryptlex release management API. /// </summary> /// <param name="platform">release platform e.g. windows, macos, linux</param> /// <param name="version">current release version</param> /// <param name="channel">release channel e.g. stable</param> /// <param name="callback">name of the callback function</param> public static void CheckForReleaseUpdate(string platform, string version, string channel, CallbackType callback) { var wrappedCallback = callback; #if NETFRAMEWORK var syncTarget = callback.Target as System.Windows.Forms.Control; if (syncTarget != null) { wrappedCallback = (v) => syncTarget.Invoke(callback, new object[] { v }); } #endif callbackList.Add(wrappedCallback); int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.CheckForReleaseUpdate_x86(platform, version, channel, wrappedCallback) : LexActivatorNative.CheckForReleaseUpdate(platform, version, channel, wrappedCallback); } else { status = LexActivatorNative.CheckForReleaseUpdateA(platform, version, channel, wrappedCallback); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// It sends the request to the Cryptlex servers to authenticate the user. /// </summary> /// <param name="email">user email address</param> /// <param name="password">user password</param> /// <returns>LA_OK</returns> public static int AuthenticateUser(string email, string password) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.AuthenticateUser_x86(email, password) : LexActivatorNative.AuthenticateUser(email, password); } else { status = LexActivatorNative.AuthenticateUserA(email, password); } if (LexStatusCodes.LA_OK == status) { return LexStatusCodes.LA_OK; } else { throw new LexActivatorException(status); } } /// <summary> /// Activates the license by contacting the Cryptlex servers. It /// validates the key and returns with encrypted and digitally signed token /// which it stores and uses to activate your application. /// /// This function should be executed at the time of registration, ideally on /// a button click. /// </summary> /// <returns>LA_OK, LA_EXPIRED, LA_SUSPENDED, LA_FAIL</returns> public static int ActivateLicense() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ActivateLicense_x86() : LexActivatorNative.ActivateLicense(); } else { status = LexActivatorNative.ActivateLicense(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_EXPIRED: return LexStatusCodes.LA_EXPIRED; case LexStatusCodes.LA_SUSPENDED: return LexStatusCodes.LA_SUSPENDED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Activates your licenses using the offline activation response file. /// </summary> /// <param name="filePath">path of the offline activation response file</param> /// <returns>LA_OK, LA_EXPIRED, LA_SUSPENDED, LA_FAIL</returns> public static int ActivateLicenseOffline(string filePath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ActivateLicenseOffline_x86(filePath) : LexActivatorNative.ActivateLicenseOffline(filePath); } else { status = LexActivatorNative.ActivateLicenseOfflineA(filePath); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_EXPIRED: return LexStatusCodes.LA_EXPIRED; case LexStatusCodes.LA_SUSPENDED: return LexStatusCodes.LA_SUSPENDED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Generates the offline activation request needed for generating /// offline activation response in the dashboard. /// </summary> /// <param name="filePath">path of the file for the offline request</param> public static void GenerateOfflineActivationRequest(string filePath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GenerateOfflineActivationRequest_x86(filePath) : LexActivatorNative.GenerateOfflineActivationRequest(filePath); } else { status = LexActivatorNative.GenerateOfflineActivationRequestA(filePath); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Deactivates the license activation and frees up the corresponding activation /// slot by contacting the Cryptlex servers. /// /// This function should be executed at the time of de-registration, ideally on /// a button click. /// </summary> /// <returns>LA_OK, LA_FAIL</returns> public static int DeactivateLicense() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.DeactivateLicense_x86() : LexActivatorNative.DeactivateLicense(); } else { status = LexActivatorNative.DeactivateLicense(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Generates the offline deactivation request needed for deactivation of /// the license in the dashboard and deactivates the license locally. /// /// A valid offline deactivation file confirms that the license has been successfully /// deactivated on the user's machine. /// </summary> /// <param name="filePath">path of the file for the offline request</param> /// <returns>LA_OK, LA_FAIL</returns> public static int GenerateOfflineDeactivationRequest(string filePath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GenerateOfflineDeactivationRequest_x86(filePath) : LexActivatorNative.GenerateOfflineDeactivationRequest(filePath); } else { status = LexActivatorNative.GenerateOfflineDeactivationRequestA(filePath); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// It verifies whether your app is genuinely activated or not. The verification is /// done locally by verifying the cryptographic digital signature fetched at the time of activation. /// /// After verifying locally, it schedules a server check in a separate thread. After the /// first server sync it periodically does further syncs at a frequency set for the license. /// /// In case server sync fails due to network error, and it continues to fail for fixed /// number of days (grace period), the function returns LA_GRACE_PERIOD_OVER instead of LA_OK. /// /// This function must be called on every start of your program to verify the activation /// of your app. /// </summary> /// <returns>LA_OK, LA_EXPIRED, LA_SUSPENDED, LA_GRACE_PERIOD_OVER, LA_FAIL</returns> public static int IsLicenseGenuine() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.IsLicenseGenuine_x86() : LexActivatorNative.IsLicenseGenuine(); } else { status = LexActivatorNative.IsLicenseGenuine(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_EXPIRED: return LexStatusCodes.LA_EXPIRED; case LexStatusCodes.LA_SUSPENDED: return LexStatusCodes.LA_SUSPENDED; case LexStatusCodes.LA_GRACE_PERIOD_OVER: return LexStatusCodes.LA_GRACE_PERIOD_OVER; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// It verifies whether your app is genuinely activated or not. The verification is /// done locally by verifying the cryptographic digital signature fetched at the time of activation. /// /// This is just an auxiliary function which you may use in some specific cases, when you /// want to skip the server sync. /// /// NOTE: You may want to set grace period to 0 to ignore grace period. /// </summary> /// <returns>LA_OK, LA_EXPIRED, LA_SUSPENDED, LA_GRACE_PERIOD_OVER, LA_FAIL</returns> public static int IsLicenseValid() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.IsLicenseValid_x86() : LexActivatorNative.IsLicenseValid(); } else { status = LexActivatorNative.IsLicenseValid(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_EXPIRED: return LexStatusCodes.LA_EXPIRED; case LexStatusCodes.LA_SUSPENDED: return LexStatusCodes.LA_SUSPENDED; case LexStatusCodes.LA_GRACE_PERIOD_OVER: return LexStatusCodes.LA_GRACE_PERIOD_OVER; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Starts the verified trial in your application by contacting the /// Cryptlex servers. /// /// This function should be executed when your application starts first time on /// the user's computer, ideally on a button click. /// </summary> /// <returns>LA_OK, LA_TRIAL_EXPIRED</returns> public static int ActivateTrial() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ActivateTrial_x86() : LexActivatorNative.ActivateTrial(); } else { status = LexActivatorNative.ActivateTrial(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_TRIAL_EXPIRED: return LexStatusCodes.LA_TRIAL_EXPIRED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Activates your trial using the offline activation response file. /// </summary> /// <param name="filePath">path of the offline activation response file</param> /// <returns>LA_OK, LA_TRIAL_EXPIRED, LA_FAIL</returns> public static int ActivateTrialOffline(string filePath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ActivateTrialOffline_x86(filePath) : LexActivatorNative.ActivateTrialOffline(filePath); } else { status = LexActivatorNative.ActivateTrialOfflineA(filePath); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_TRIAL_EXPIRED: return LexStatusCodes.LA_TRIAL_EXPIRED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Generates the offline trial activation request needed for generating /// offline trial activation response in the dashboard. /// </summary> /// <param name="filePath">path of the file for the offline request</param> public static void GenerateOfflineTrialActivationRequest(string filePath) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.GenerateOfflineTrialActivationRequest_x86(filePath) : LexActivatorNative.GenerateOfflineTrialActivationRequest(filePath); } else { status = LexActivatorNative.GenerateOfflineTrialActivationRequestA(filePath); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// It verifies whether trial has started and is genuine or not. The /// verification is done locally by verifying the cryptographic digital signature /// fetched at the time of trial activation. /// /// This function must be called on every start of your program during the trial period. /// </summary> /// <returns>LA_OK, LA_TRIAL_EXPIRED, LA_FAIL</returns> public static int IsTrialGenuine() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.IsTrialGenuine_x86() : LexActivatorNative.IsTrialGenuine(); } else { status = LexActivatorNative.IsTrialGenuine(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_TRIAL_EXPIRED: return LexStatusCodes.LA_TRIAL_EXPIRED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Starts the local (unverified) trial. /// /// This function should be executed when your application starts first time on /// the user's computer. /// </summary> /// <param name="trialLength">trial length in days</param> /// <returns>LA_OK, LA_LOCAL_TRIAL_EXPIRED, LA_FAIL</returns> public static int ActivateLocalTrial(uint trialLength) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ActivateLocalTrial_x86(trialLength) : LexActivatorNative.ActivateLocalTrial(trialLength); } else { status = LexActivatorNative.ActivateLocalTrial(trialLength); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_LOCAL_TRIAL_EXPIRED: return LexStatusCodes.LA_LOCAL_TRIAL_EXPIRED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// It verifies whether trial has started and is genuine or not. The /// verification is done locally. /// /// This function must be called on every start of your program during the trial period. /// /// NOTE: The function is only meant for local (unverified) trials. /// </summary> /// <returns>LA_OK, LA_LOCAL_TRIAL_EXPIRED, LA_FAIL</returns> public static int IsLocalTrialGenuine() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.IsLocalTrialGenuine_x86() : LexActivatorNative.IsLocalTrialGenuine(); } else { status = LexActivatorNative.IsLocalTrialGenuine(); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_LOCAL_TRIAL_EXPIRED: return LexStatusCodes.LA_LOCAL_TRIAL_EXPIRED; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Extends the local trial. /// /// NOTE: The function is only meant for local (unverified) trials. /// </summary> /// <param name="trialExtensionLength">number of days to extend the trial</param> /// <returns>LA_OK, LA_FAIL</returns> public static int ExtendLocalTrial(uint trialExtensionLength) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ExtendLocalTrial_x86(trialExtensionLength) : LexActivatorNative.ExtendLocalTrial(trialExtensionLength); } else { status = LexActivatorNative.ExtendLocalTrial(trialExtensionLength); } switch (status) { case LexStatusCodes.LA_OK: return LexStatusCodes.LA_OK; case LexStatusCodes.LA_FAIL: return LexStatusCodes.LA_FAIL; default: throw new LexActivatorException(status); } } /// <summary> /// Increments the meter attribute uses of the activation. /// </summary> /// <param name="name">name of the meter attribute</param> /// <param name="increment">the increment value</param> public static void IncrementActivationMeterAttributeUses(string name, uint increment) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.IncrementActivationMeterAttributeUses_x86(name, increment) : LexActivatorNative.IncrementActivationMeterAttributeUses(name, increment); } else { status = LexActivatorNative.IncrementActivationMeterAttributeUsesA(name, increment); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Decrements the meter attribute uses of the activation. /// </summary> /// <param name="name">name of the meter attribute</param> /// <param name="decrement">the decrement value</param> public static void DecrementActivationMeterAttributeUses(string name, uint decrement) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.DecrementActivationMeterAttributeUses_x86(name, decrement) : LexActivatorNative.DecrementActivationMeterAttributeUses(name, decrement); } else { status = LexActivatorNative.DecrementActivationMeterAttributeUsesA(name, decrement); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Resets the meter attribute uses consumed by the activation. /// </summary> /// <param name="name">name of the meter attribute</param> public static void ResetActivationMeterAttributeUses(string name) { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.ResetActivationMeterAttributeUses_x86(name) : LexActivatorNative.ResetActivationMeterAttributeUses(name); } else { status = LexActivatorNative.ResetActivationMeterAttributeUsesA(name); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } /// <summary> /// Resets the activation and trial data stored in the machine. /// /// This function is meant for developer testing only. /// /// NOTE: The function does not reset local (unverified) trial data. /// </summary> public static void Reset() { int status; if (LexActivatorNative.IsWindows()) { status = IntPtr.Size == 4 ? LexActivatorNative.Reset_x86() : LexActivatorNative.Reset(); } else { status = LexActivatorNative.Reset(); } if (LexStatusCodes.LA_OK != status) { throw new LexActivatorException(status); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oop.BranchingOverBoolean { class Account1 { public Decimal Balance { get; private set; } private bool IsVerified { get; set; } private bool IsClosed { get; set; } private Action OnUnfreeze { get;} public Account1(Action onUnfreeze) { OnUnfreeze = onUnfreeze; } public void Deposit(decimal amount) { if (IsClosed) return; ManageUnfreeze = StayUnfrozen; Balance += amount; } private Action ManageUnfreeze { get; set; } //{ // if (IsFrozen) // { // Unfreeze(); // } // else // { // StayUnfrozen(); // } //} private void StayUnfrozen() { } private void Unfreeze() { OnUnfreeze(); ManageUnfreeze = StayUnfrozen; } public void Withdraw(decimal amount) { if (!IsVerified) return; if (IsClosed) return; ManageUnfreeze(); //Withdraw money Balance -= amount; } public void HoldVerified() { IsVerified = true; } public void Close() { IsClosed = true; } public void Freeze() { if (!IsVerified) return; if (IsClosed) return; ManageUnfreeze = Unfreeze; } } }
using System; using System.Text; using HTTPServer.core; namespace HTTPServer.test { public class MockPathContents: IPathContents { public string DirectoryPath { get; } public MockPathContents(string directoryPath) { DirectoryPath = directoryPath; } public string[] GetFiles(string directoryExtension) { return new []{ "C:\\gitwork\\HTTP Server\\file.txt" }; } public string[] GetDirectories(string directoryExtension) { return new []{ "C:\\gitwork\\HTTP Server\\.git" }; } public byte[] GetFileContents(string filePath) { return Encoding.UTF8.GetBytes("This is the content of the file."); } public void PostContents(Request request) { } public void PutContents(Request request) { } } }
using System; using System.Windows; namespace SC.WPFSamples { class DependencyObjectDemo { static void Demo() { var obj = new MyDependencyObject(); obj.ValueChanged += (sender, e) => { Console.WriteLine("value changed from {0} to {1}", e.OldValue, e.NewValue); }; obj.Value = 33; Console.WriteLine(obj.Maximum); obj.Value = 210; Console.WriteLine(obj.Value); object value = obj.GetValue(MyDependencyObject.ValueProperty); Console.WriteLine(value); } static void obj_ValueChanged(object sender, RoutedPropertyChangedEventArgs<int> e) { throw new NotImplementedException(); } } }
using System.Web.UI; namespace irrsa { public partial class Default : Page { } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace StudentPortal { public partial class Forget : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btn1_Click(object sender, EventArgs e) { String a = DropDownList1.Text; String b = Byn1.Text; string strcon = ConfigurationManager.ConnectionStrings["db"].ConnectionString; SqlConnection con = new SqlConnection(strcon); con.Open(); if (a == "Student") { SqlCommand cmd = new SqlCommand("Select * from StudentInfo where StudentID=@id", con); cmd.Parameters.AddWithValue("@id", Byn1.Text); var dataReader = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(dataReader); if (dt.Rows.Count > 0) { TextBox2.Text = dt.Rows[0]["StudentName"].ToString(); } else { } } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { } protected void Byn1_TextChanged(object sender, EventArgs e) { } protected void btn2_Click(object sender, EventArgs e) { string strcon = ConfigurationManager.ConnectionStrings["db"].ConnectionString; SqlConnection con = new SqlConnection(strcon); con.Open(); SqlCommand cmd = new SqlCommand("update StudentInfo set Password=@pass where StudentID=@id and StudentName=@pass1", con); cmd.Parameters.AddWithValue("@id", Byn1.Text); cmd.Parameters.AddWithValue("@pass1", TextBox2.Text); //cmd.Parameters.AddWithValue("@pass1", tb1.Text); if (TextBox1.Text == tb1.Text) { cmd.Parameters.AddWithValue("@pass", tb1.Text); cmd.ExecuteNonQuery(); l1.Text = "Password Changed Successfully"; } else { l1.Text = "Password Not Matched"; } } protected void Btn2_Click1(object sender, EventArgs e) { Response.Redirect("Home.aspx"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crossroads.Utilities.Services.Interfaces { public interface IPasswordService { string GetNewUserPassword(int length, int numSpecialChars); string GeneratorPasswordResetToken(string username); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Management; namespace LaunchpadMonitor { public partial class Form1 : Form { Timer updateTimer =new Timer(); IGathererRenderer gathererRenderer = null; ILaunchpad launchpadRenderer = null; public Form1() { InitializeComponent(); List<CPU> cpus = CPU.CountCPUs(); UpdateGathererComboBox(cpus); updateTimer.Tick += new EventHandler(timerEventHandler); updateTimer.Enabled = false; launchpadRenderer = new DiffingLaunchpadRenderer(); gathererRenderer = new LaunchpadGathererRenderer(launchpadRenderer); launchpadRenderer.LeftButtonPressDelegate = delegate(bool release) { if (release) gathererRenderer.ZoomOut(); scaleTextBox.Text = gathererRenderer.Scale.ToString(); }; launchpadRenderer.RightButtonPressDelegate = delegate(bool release) { if (release) gathererRenderer.ZoomIn(); scaleTextBox.Text = gathererRenderer.Scale.ToString(); }; } private void UpdateGathererComboBox(IEnumerable<CPU> cpus) { processorComboBox.Items.Clear(); foreach (CPU cpu in cpus) { foreach (PerfCPU perfCPU in cpu.PerfCPUs) { Gatherer gatherer = new Gatherer(perfCPU.ManagementObjectSampler, 1000, perfCPU.ToString()); processorComboBox.Items.Add(gatherer); } } } private void timerEventHandler(object sender, EventArgs e) { Gatherer perfCPU = processorComboBox.SelectedItem as Gatherer; try { gathererRenderer.Present(); loadTextBox1.Text = perfCPU.Latest.ToString(); } catch (Exception x) { } } private void processorComboBox_SelectedIndexChanged(object sender, EventArgs e) { updateTimer.Interval = 250; updateTimer.Enabled = true; gathererRenderer.Gatherer = processorComboBox.SelectedItem as Gatherer; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { launchpadRenderer.Dispose(); } private void zoomInButton_Click(object sender, EventArgs e) { gathererRenderer.ZoomIn(); } private void zoomOutButton_Click(object sender, EventArgs e) { gathererRenderer.ZoomOut(); } } }
namespace FormattingNumbers { using System; using System.Globalization; using System.Threading; public class Startup { public static void Main(string[] args) { Console.WriteLine(Execute()); } private static string Execute() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; var args = Console.ReadLine().Split(new[] { ' ', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries); var a = int.Parse(args[0]); var b = double.Parse(args[1]); var c = double.Parse(args[2]); var binary = Convert.ToString(a, 2); if (binary.Length > 10) { binary = binary.Remove(11); } else if (binary.Length < 10) { binary = new string('0', 10 - binary.Length) + binary; } return string.Format("|{0,-10}|{1}|{2,10:F2}|{3,-10:F3}| ", a.ToString("X"), binary, b, c); } } }
using System; namespace ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tickets { public class HelpDesk_Tickets_SimplePost_vm { public int? Id { get; set; } public string Title { get; set; } public string Description { get; set; } public string RequestorUserName { get; set; } public string Location { get; set; } public string Department { get; set; } public DateTime? RequestedDueDate { get; set; } public int TicketCategoryID { get; set; } } }
using System; using Microsoft.UnifiedRedisPlatform.Core.Constants; namespace Microsoft.UnifiedRedisPlatform.Core.Exceptions { [Serializable] public class InvalidConfigurationException: Exception { public InvalidConfigurationException(string invalidArgument, Exception innerException) :base(string.Format(Constant.ExceptionMessages.InvalidConfiguration, invalidArgument), innerException) { } } }
using System; namespace Equal_Sums_Even_Odd_Position { class Program { static void Main(string[] args) { int firstInterval = int.Parse(Console.ReadLine()); int secondInterval = int.Parse(Console.ReadLine()); for (int number = firstInterval; number <= secondInterval; number++) { int firstDigit = number % 10; int secondDigit = number / 10 % 10; int thirdDigit = number / 100 % 10; int fourthDigit = number / 1000 % 10; int fifthDigit = number / 10000 % 10; int sixthDigit = number / 100000 % 10; if ((firstDigit + thirdDigit + fifthDigit) == (secondDigit + fourthDigit + sixthDigit)) { Console.Write(number + " "); } } } } }
namespace TellStoryTogether.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddNotificationTable : DbMigration { public override void Up() { CreateTable( "dbo.Notification", c => new { NotificationId = c.Int(nullable: false, identity: true), Time = c.DateTime(nullable: false), Content = c.String(), State = c.String(), Seen = c.Boolean(nullable: false), Starred = c.Int(nullable: false), Favorited = c.Int(nullable: false), Commented = c.Int(nullable: false), Forked = c.Int(nullable: false), Article_ArticleId = c.Int(), User_UserId = c.Int(), }) .PrimaryKey(t => t.NotificationId) .ForeignKey("dbo.Article", t => t.Article_ArticleId) .ForeignKey("dbo.UserProfile", t => t.User_UserId) .Index(t => t.Article_ArticleId) .Index(t => t.User_UserId); } public override void Down() { DropForeignKey("dbo.Notification", "User_UserId", "dbo.UserProfile"); DropForeignKey("dbo.Notification", "Article_ArticleId", "dbo.Article"); DropIndex("dbo.Notification", new[] { "User_UserId" }); DropIndex("dbo.Notification", new[] { "Article_ArticleId" }); DropTable("dbo.Notification"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; namespace MeriMudra.App_Start { public class BundleConfig { public static void RegisterBundle(BundleCollection bundles) { //Scripts bundles.Add(new ScriptBundle("~/Script/HomeJs").Include( "~/js/bootstrap.min.js", "~/js/menumaker.js", "~/js/jquery.sticky.js", "~/js/sticky-header.js", "~/js/owl.carousel.min.js", "~/js/slider-carousel.js", "~/js/service-carousel.js", "~/js/back-to-top.js" )); //CSS bundles.Add(new ScriptBundle("~/style/HomeCss").Include( "~/css/bootstrap.min.css", "~/css/style.css", "~/css/font-awesome.min.css", "~/css/fontello.css", "~/css/flaticon.css" )); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClientBySocket { public partial class ClientForm : Form { SocketClientManager _scm = null; string ip = "127.0.0.1"; int port = 23001; public ClientForm() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { InitSocket(); } public void OnReceiveMsg() { byte[] buffer = _scm.socketInfo.buffer;//??? string msg = Encoding.ASCII.GetString(buffer).Replace("\0", ""); if (string.Empty.Equals(msg)) return; if (txtMsg.InvokeRequired)//该值指示调用方在对控件进行方法调用时是否必须调用invoke方法,因为调用方位于创建控件所在线程以外的线程中 { this.Invoke(new Action(() => { txtMsg.Text += AppendReceiveMsg(msg); })); } else { txtMsg.Text += AppendReceiveMsg(msg); } } public void OnConnected() { if (txtMsg.InvokeRequired) { this.Invoke(new Action(() => { txtMsg.Text += GetDateNow() + " " + "连接服务器" + ip + " : " + port + "成功\r\n"; string ipClient = _scm._socket.LocalEndPoint.ToString().Split(':')[0];//客户端ip string posrClient = _scm._socket.LocalEndPoint.ToString().Split(':')[1];//客户端port lblClientIps.Text = ipClient; lblClientPorts.Text = posrClient; lblRemoteIps.Text = ip; lblRemotePorts.Text = port.ToString(); lblStatuss.Text = "正常"; })); } else { txtMsg.Text += GetDateNow() + " " + "连接服务器" + ip + " : " + port + "成功\r\n"; } } public void OnFaildConnect() { if (txtMsg.InvokeRequired) { this.Invoke(new Action(() => { txtMsg.Text += GetDateNow() + " " + "连接服务器" + ip + " : " + port + " 失败\r\n"; lblStatuss.Text = "连接失败"; })); } else { txtMsg.Text += GetDateNow() + " " + "连接服务器" + ip + " : " + port + " 成功\r\n"; } } private void button1_Click(object sender, EventArgs e) { try { _scm.SendMsg(txtSend.Text); txtMsg.Text += AppendSendMsg(txtSend.Text); txtSend.Text = ""; } catch (SocketException ex) { MessageBox.Show(ex.ErrorCode.ToString()+":"+ex.Message); } } public string AppendSendMsg(string msg) { return GetDateNow() + " " + "[发送] " + msg + "\r\n"; } public string AppendReceiveMsg(string msg) { return GetDateNow() + " " + "[接收] " + msg + "\r\n"; } public string GetDateNow() { return DateTime.Now.ToString("HH:mm:ss"); } private void InitSocket() { _scm = new SocketClientManager(ip, port); _scm.OnReceiveMsg += OnReceiveMsg; _scm.OnConnected += OnConnected; _scm.OnFaildConnect += OnFaildConnect; _scm.Start(); } private void btnConnected_Click(object sender, EventArgs e) { InitSocket(); } private void btnClose_Click(object sender, EventArgs e) { if (!_scm._socket.Connected) return; _scm._isConnected = false; _scm.SendMsg("\0\0\0faild"); _scm._socket.Shutdown(System.Net.Sockets.SocketShutdown.Both); _scm._socket.Close(); lblClientIps.Text = ""; lblClientPorts.Text = ""; lblRemoteIps.Text = ""; lblRemotePorts.Text = ""; lblStatuss.Text = "未连接"; txtMsg.Text += "连接已经断开\r\n"; } private void lblClientIp_Click(object sender, EventArgs e) { } private void lblClientPort_Click(object sender, EventArgs e) { } private void lblRemoteIp_Click(object sender, EventArgs e) { } private void lblRemotePort_Click(object sender, EventArgs e) { } private void lblStatus_Click(object sender, EventArgs e) { } private void txtSend_TextChanged(object sender, EventArgs e) { } private void label6_Click(object sender, EventArgs e) { } private void lblClientIps_Click(object sender, EventArgs e) { } private void lblClientPorts_Click(object sender, EventArgs e) { } private void lblRemoteIps_Click(object sender, EventArgs e) { } private void lblRemotePorts_Click(object sender, EventArgs e) { } private void lblStatuss_Click(object sender, EventArgs e) { } private void txtMsg_TextChanged(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using ServiceReference1; namespace MediaWebApp.Pages.File { public class EditFileModel : PageModel { private readonly MapperConfiguration config; private readonly IMapper iMapper; FileMetadataTagClient pcc = new FileMetadataTagClient(); [BindProperty(SupportsGet = true)] public int Id { get; set; } [BindProperty] public Models.FileDTO FileDTO { get; set; } public List<string> TagKeys { get; set; } [BindProperty] public string TagKey1 { get; set; } [BindProperty] public string TagValue1 { get; set; } public EditFileModel() { config = new MapperConfiguration( cfg => { cfg.CreateMap<ServiceReference1.FileDTO, Models.FileDTO>(); cfg.CreateMap<Models.FileDTO, ServiceReference1.FileDTO>(); cfg.CreateMap<ServiceReference1.MetadataDTO, Models.MetadataDTO>(); cfg.CreateMap<Models.MetadataDTO, ServiceReference1.MetadataDTO>(); cfg.CreateMap<ServiceReference1.TagDTO, Models.TagDTO>(); cfg.CreateMap<Models.TagDTO, ServiceReference1.TagDTO>(); }); iMapper = config.CreateMapper(); FileDTO = new Models.FileDTO(); TagKey1 = ""; TagValue1 = ""; } public async Task OnGetAsync() { var files = await pcc.GetFilesAndMetadataAsync(); var OriginalFile = files.First(f => f.Id == Id); FileDTO = iMapper.Map<ServiceReference1.FileDTO, Models.FileDTO>(OriginalFile); var MetadataDTO = new Models.MetadataDTO(); MetadataDTO = iMapper.Map<ServiceReference1.MetadataDTO, Models.MetadataDTO>(OriginalFile.Metadata); var Tags = new List<Models.TagDTO>(); foreach (var tag in OriginalFile.Tags) { Tags.Add(iMapper.Map<ServiceReference1.TagDTO, Models.TagDTO>(tag)); } FileDTO.Metadata = MetadataDTO; FileDTO.Tags = Tags; } public async Task<IActionResult> OnPostAsync() { var files = await pcc.GetFilesAndMetadataAsync(); var OriginalFile = files.First(f => f.Id == Id); var Tag = new ServiceReference1.TagDTO { Key = TagKey1, Value = TagValue1 }; Tag.File = OriginalFile; Tag.FileId = OriginalFile.Id; try { await pcc.AddTagAsync(Tag); } catch (Exception e) { return RedirectToAction("Error"); } return RedirectToAction("./Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ManageDomain.Models.ServerWatch { public class DataHttpRequest { public int id { get; set; } public int serverid { get; set; } public DateTime timestamp { get; set; } public int requestcount { get; set; } public DateTime createtime { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Compression; using System.IO; using com.dlut.ssdut.zucky.DotNetFetion; namespace EasyDev.Util { [Obsolete("此工具类中的方法都已经有对应的扩展方法实现")] public class CompressUtil { /// <summary> /// 采用GZIP算法对数据进行压缩 /// </summary> /// <param name="toCompressData">要压缩的数据</param> /// <returns>UTF8编码的压缩结果</returns> public static string Compress(byte[] toCompressData) { return toCompressData.Compress(); } /// <summary> /// 对UTF8编码的压缩数据进行解压缩 /// </summary> /// <param name="toExtractData">要解压的数据</param> /// <returns>UTF8编码的解压缩数据</returns> public static string Extract(byte[] toExtractData) { return toExtractData.Extract(); } /// <summary> /// 采用GZIP算法对数据进行压缩 /// </summary> /// <param name="toCompressData">要压缩的数据</param> /// <returns>UTF8编码的压缩结果</returns> public static string Compress(string toCompressData) { return toCompressData.Compress(); } /// <summary> /// 对UTF8编码的压缩数据进行解压缩 /// </summary> /// <param name="toExtractData">要解压的数据</param> /// <returns>UTF8编码的解压缩数据</returns> public static string Extract(string toExtractData) { return toExtractData.Extract(); } } }
using EduHome.Models.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EduHome.ViewModels { public class TeacherVM { public List<Course> Courses { get; set; } public Teacher Teacher { get; set; } public string Image { get; set; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApplication1.EfStuff.Model.Energy; namespace WebApplication1.Models.Energy { public class PersonalAccountViewModel { public long Id { get; set; } public long TariffId { get; set; } public long CitizenId { get; set; } public long ElectricityMeterId { get; set; } public string UserName { get; set; } public string Address { get; set; } public string Number { get; set; } public Rate Rate { get; set; } public Person Person { get; set; } public DateTime DateRegistration { get; set; } public DateTime DateLastPayment { get; set; } public string SerialNumber { get; set; } public int Consumption { get; set; } public int Debt { get; set; } } }
using System.Windows; using System.Windows.Controls; namespace Crystal.Plot2D { public class Header : ContentControl, IPlotterElement { public Header() { FontSize = 12; HorizontalAlignment = HorizontalAlignment.Center; Margin = new Thickness(0, 0, 0, 3); } public PlotterBase Plotter { get; private set; } public void OnPlotterAttached(PlotterBase _plotter) { Plotter = _plotter; _plotter.HeaderPanel.Children.Add(this); } public void OnPlotterDetaching(PlotterBase _plotter) { Plotter = null; _plotter.HeaderPanel.Children.Remove(this); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UnityStandardAssets.CrossPlatformInput { public class IceBallMagic : MonoBehaviour { GameObject player; private string[] _enemy_OneHalf = {"golem","Shell_Crab","DarkDragon"}; private string[] _enemy_Three = { "SkeletonWizard","SkeletonDarkKnight","SkeletonWeak1","SkeletonWeak1","SkeletonWeak2", "SkeletonMedium1","SkeletonMedium2","SkeletonStrong","demon","demonBoss", "Spider","SpiderBoss","StringSpider","WarriorMachine","FlyMachine", "Ghost","CubeMachine"}; private string[] _enemy_Half = {"wizard", "Imomusi","ImomusiBoss","Imomusi2","icedemon","ImomusiDark" }; private string[] _enemy_One = {"troll", "goblin","Hobgoblin","RhinoObject","whale", "demonTree","Knight"}; // Use this for initialization void Start() { player = GameObject.Find("Player"); Destroy(this.gameObject, 100.0f); } // Update is called once per frame void Update() { } private void OnTriggerEnter(Collider enemyObj) { if (enemyObj.tag == "Enemy") { for (int i = 0; _enemy_OneHalf.Length > i; i++) { if (enemyObj.name == _enemy_Three[i]) { enemyObj.GetComponent<SkeletonStatus>()._life -= player.GetComponent<UnityChanControlScriptWithRgidBody>()._magicPower * 1.5f * 4; enemyObj.GetComponent<SkeletonStatus>()._isMagic = true; } } for (int i = 0; _enemy_Three.Length > i; i++) { if (enemyObj.name == _enemy_Three[i]) { enemyObj.GetComponent<SkeletonStatus>()._life -= player.GetComponent<UnityChanControlScriptWithRgidBody>()._magicPower * 3 * 4; enemyObj.GetComponent<SkeletonStatus>()._isMagic = true; if(i == 14 || i == 16){ enemyObj.GetComponent<MachineAI>().Broken(); } } } for (int i = 0; _enemy_Half.Length > i; i++) { if (enemyObj.name == _enemy_Half[i]){ enemyObj.GetComponent<SkeletonStatus>()._life -= player.GetComponent<UnityChanControlScriptWithRgidBody>()._magicPower * 0.5f* 4; enemyObj.GetComponent<SkeletonStatus>()._isMagic = true; } } for (int i = 0; _enemy_One.Length > i; i++) { if (enemyObj.name == _enemy_One[i]) { enemyObj.GetComponent<SkeletonStatus>()._life -= player.GetComponent<UnityChanControlScriptWithRgidBody>()._magicPower * 4; enemyObj.GetComponent<SkeletonStatus>()._isMagic = true; } Destroy(this.gameObject, 10.0f); } } if(enemyObj.tag == "Death"){ for (int i = 0; _enemy_Three.Length > i; i++) { if (enemyObj.name == _enemy_Three[i]) { if (i == 14 || i == 16) { enemyObj.GetComponent<MachineAI>().Broken(); } } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace JenzaBank { public partial class vntTransferir : Form { Validacion val = new Validacion(); Interfaz ocultar = new Interfaz(); public vntTransferir() { InitializeComponent(); } bool aux = true; Int32 cnta; //Resta public void RealizarTransfRes() { Double reti = 0; //este es el nombre del archivo que administra los clientes string fileName = "clientes.txt"; //este es el nombre de un archivo de copia string fileCopia = "copia_clientes.txt"; // esto inserta texto en un archivo existente, si el archivo no existe lo crea StreamWriter writer = File.AppendText(fileCopia); StreamReader reader = File.OpenText(fileName); StreamReader readeer = File.OpenText(fileName); //este vector es para realizar la presentación de los datos string clave = (txtClave.Text); reti = Convert.ToDouble(txtValor.Text); cnta = Convert.ToInt32(txtTrans.Text); while (!reader.EndOfStream) { //este contador es para moverse entre las diferentes etiquetas string lineaActual = reader.ReadLine(); string[] dato = lineaActual.Split('/'); if (dato[7] == clave) { string lineaAux = readeer.ReadLine(); string[] datos = lineaActual.Split('/'); if (cnta == Convert.ToInt32(datos[0])) { if (reti <= Convert.ToDouble(datos[6])) { reti = Convert.ToDouble(datos[6]) - reti; writer.WriteLine("{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}", datos[0], datos[1], datos[2], datos[3], datos[4], datos[5], reti, datos[7]); } else { MessageBox.Show("No posee los fondos suficientes para realizar esta operación.", "Transacción Declinada", MessageBoxButtons.OK, MessageBoxIcon.Warning); aux = false; writer.WriteLine(lineaActual); } } } else { writer.WriteLine(lineaActual); } } writer.Close(); reader.Close(); readeer.Close(); File.Replace(fileCopia, fileName, null, true); } //Suma public void RealizarTransfSum() { //este es el nombre del archivo que administra los clientes string fileName = "clientes.txt"; //este es el nombre de un archivo de copia string fileCopia = "copia_clientes.txt"; // esto inserta texto en un archivo existente, si el archivo no existe lo crea StreamWriter writer = File.AppendText(fileCopia); StreamReader reader = File.OpenText(fileName); //este vector es para realizar la presentación de los datos string clave = (txtClave.Text); Int32 retir = Convert.ToInt32(txtValor.Text); cnta= Convert.ToInt32(txtTrans.Text); while (!reader.EndOfStream) { //este contador es para moverse entre las diferentes etiquetas string lineaActual = reader.ReadLine(); string[] datos = lineaActual.Split('/'); if (cnta == Convert.ToInt32(datos[0])) { if (aux == true) { retir = Convert.ToInt32(datos[6]) + retir; writer.WriteLine("{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}", datos[0], datos[1], datos[2], datos[3], datos[4], datos[5], retir, datos[7]); MessageBox.Show("Se transfirio correctamente a la cuenta #" + cnta, "Transacción Éxitosa", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { writer.WriteLine(lineaActual); } } else { //MessageBox.Show("La cuenta ingresada no existe.", "Transacción Declinada", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); writer.WriteLine(lineaActual); } } writer.Close(); reader.Close(); File.Replace(fileCopia, fileName, null, true); this.Close(); } public struct Cliente { public string codigo; public string nombre; public string apellido; public string direccion; public string telefono; public string email; public string saldo; public string contrasena; } private void vntTransferir_Load(object sender, EventArgs e) { } private void txtValor_KeyPress(object sender, KeyPressEventArgs e) { val.SoloNumeros(e); } private void btConsignar_Click(object sender, EventArgs e) { if (txtClave.Text == "" || txtValor.Text == "") { } else { RealizarTransfRes(); RealizarTransfSum(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Navigation; using ProyectoSCA_Navigation.Clases; namespace ProyectoSCA_Navigation.Views { public partial class ConsultarPerfil : Page { string usuario = App.Correo; //Flags, true, puede disparar el evento, false no bool[] flags = new bool[10]; /*** 0 - Abrir Inserts *** 1 - Abrir Gets, luego Llenar campos de datos *** 2 - Error Windows ***/ Afiliado afiliado = new Afiliado(); Empleado empleado = new Empleado(); List<BeneficiarioGrid> listaBeneficiarios = new List<BeneficiarioGrid>(); List<BeneficiarioNormal> beneficiarioNormal = new List<BeneficiarioNormal>(); BeneficiarioContingencia beneficiarioContingencia = new BeneficiarioContingencia(); DateTime fecha = DateTime.Now; /******************************************************************************************************************************** ************************************************** Inicializadores ********************************************************* *********************************************************************************************************************************/ private System.ServiceModel.BasicHttpBinding bind; private System.ServiceModel.EndpointAddress endpoint; private ProyectoSCA_Navigation.ServiceReference.WSCosecolSoapClient Wrapper; private string m_EndPoint = "http://localhost:1809/WSCosecol.asmx"; public ConsultarPerfil() { InitializeComponent(); bind = new System.ServiceModel.BasicHttpBinding(); endpoint = new System.ServiceModel.EndpointAddress(m_EndPoint); Wrapper = new ServiceReference.WSCosecolSoapClient(bind, endpoint); } // Executes when the user navigates to this page. protected override void OnNavigatedTo(NavigationEventArgs e) { string afiliadoID = NavigationContext.QueryString["User"]; for (int i = 0; i < flags.Length; i++) { flags[i] = false; } flags[0] = true; flags[1] = true; flags[2] = true; Wrapper.AgregarPeticionCompleted += new EventHandler<ServiceReference.AgregarPeticionCompletedEventArgs>(Wrapper_AgregarPeticionCompleted); Wrapper.AgregarPeticionAsync(ServiceReference.peticion.getAfiliado, afiliadoID); } /******************************************************************************************************************************** ***************************************************** Metodo PRINCIPAL ****************************************************** *********************************************************************************************************************************/ //es el metodo que corre cuando se dispara el evento de recibir respuesta, aqui van todas las respuestas //con los codigos que le pertenecen, consultar TABLA DE PETICIONES.XLSX private void Wrapper_AgregarPeticionCompleted(object sender, ServiceReference.AgregarPeticionCompletedEventArgs e) { if (e.Error == null) { string temp = e.Result.Substring(0, 3); string recievedResponce = e.Result.Substring(3); if (recievedResponce == "False") { if (flags[2]) { flags[2] = false; MessageBox.Show("Ha ocurrido un error. Intente su consulta de nuevo.\nSi el problema persiste, refresque la pagina e intente de nuevo."); } } else { switch (temp) { case "p21"://Get datos Afiliado if (flags[0]) { flags[0] = false; if (recievedResponce != "") { afiliado = MainPage.tc.getAfiliado(recievedResponce); numeroCertificado_txt.Text = afiliado.certificadoCuenta.ToString(); pNombre_txt.Text = afiliado.primerNombre; sNombre_txt.Text = afiliado.segundoNombre; pApellido_txt.Text = afiliado.primerApellido; sApellido_txt.Text = afiliado.segundoApellido; direccion_txt.Text = afiliado.direccion; id_txt.Text = afiliado.identidad; genero_txt.Text = afiliado.genero; try { telefono_txt.Text = afiliado.telefonoPersonal[0]; telefono2_txt.Text = afiliado.telefonoPersonal[1]; celular_txt.Text = afiliado.celular[0]; celular2_txt.Text = afiliado.celular[1]; } catch { } profesion_txt.Text = afiliado.Ocupacion; email_txt.Text = afiliado.CorreoElectronico; lugarNacimiento_txt.Text = afiliado.lugarDeNacimiento; fechaNacimiento_txt.Text = afiliado.fechaNacimiento; estadoCivil_txt.Text = afiliado.estadoCivil; estadoAfiliado_txt.Text = afiliado.EstadoAfiliado; empresa_txt.Text = afiliado.NombreEmpresa; fechaIngresoEmpresa_txt.Text = afiliado.fechaIngresoCooperativa; telefonoEmpresa_txt.Text = afiliado.TelefonoEmpresa; departamentoEmpresa_txt.Text = afiliado.DepartamentoEmpresa; direccionEmpresa_txt.Text = afiliado.DireccionEmpresa; beneficiarioNormal = afiliado.bensNormales; beneficiarioContingencia = (BeneficiarioContingencia)afiliado.BeneficiarioCont; foreach (BeneficiarioNormal item in beneficiarioNormal) { listaBeneficiarios.Add(new BeneficiarioGrid() { PrimerNombre = item.primerNombre, SegundoNombre = item.segundoNombre, PrimerApellido = item.primerApellido, SegundoApellido = item.segundoApellido, NumeroIdentidad = item.identidad, Fecha_Nacimiento = item.fechaNacimiento, Genero = item.genero, Direccion = item.direccion, Parentesco = item.Parentesco, PorcentajeSeguros = item.porcentajeSeguros, PorcentajeAportaciones = item.porcentajeAportaciones, TipoBeneficiario = "Normal", }); } //Este es el Beneficiario de Contingencia listaBeneficiarios.Add(new BeneficiarioGrid() { PrimerNombre = beneficiarioContingencia.primerNombre, SegundoNombre = beneficiarioContingencia.segundoNombre, PrimerApellido = beneficiarioContingencia.primerApellido, SegundoApellido = beneficiarioContingencia.segundoApellido, NumeroIdentidad = beneficiarioContingencia.identidad, Fecha_Nacimiento = beneficiarioContingencia.fechaNacimiento, Genero = beneficiarioContingencia.genero, Direccion = beneficiarioContingencia.direccion, Parentesco = beneficiarioContingencia.Parentesco, TipoBeneficiario = "De Contingencia", PorcentajeAportaciones = 100, PorcentajeSeguros = 100 }); gridBeneficiarios.ItemsSource = listaBeneficiarios; } else { MessageBox.Show("No se ha encontrado el registro!"); } } break; case "p22"://Get datos Empleados if (flags[1]) { flags[1] = false; if (recievedResponce != "") { datosLaborales_tab.IsEnabled = false; beneficiarios_tab.IsEnabled = false; empleado = MainPage.tc.getEmpleado(recievedResponce); label20.Content = ""; numeroCertificado_txt.Text = ""; pNombre_txt.Text = empleado.primerNombre; sNombre_txt.Text = empleado.segundoNombre; pApellido_txt.Text = empleado.primerApellido; sApellido_txt.Text = empleado.segundoApellido; direccion_txt.Text = empleado.direccion; id_txt.Text = empleado.identidad; genero_txt.Text = empleado.genero; telefono_txt.Text = empleado.telefonoPersonal[0]; celular_txt.Text = empleado.celular[0]; profesion_txt.Text = ""; puesto_txt.Text = empleado.Puesto; email_txt.Text = empleado.correoElectronico; lugarNacimiento_txt.Text = ""; fechaNacimiento_txt.Text = empleado.fechaNacimiento; estadoCivil_txt.Text = empleado.estadoCivil; } else { MessageBox.Show("No se ha encontrado el registro!"); } } break; default: if (flags[2]) { flags[2] = false; MessageBox.Show("No se entiende la peticion. (No esta definida)"); } break; } } } else { if (flags[2]) { flags[2] = false; MessageBox.Show("Ha ocurrido un error. Intente su consulta de nuevo.\nSi el problema persiste, refresque la pagina e intente de nuevo."); } } } /******************************************************************************************************************************** ************************************************** Metodos de Botones ***************************************************** *********************************************************************************************************************************/ private void aceptarCambios_btn_Click(object sender, RoutedEventArgs e) { } private void rechazar_btn_Click(object sender, RoutedEventArgs e) { } /******************************************************************************************************************************** ************************************************** Metodos Auxiliares ***************************************************** *********************************************************************************************************************************/ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Problem_3_Nether_Realms { public class Problem_3_Nether_Realms { public static void Main() { var deamonName = Console.ReadLine().Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); var result = new SortedDictionary<string, List<double>>(); foreach (var name in deamonName) { var patern = new Regex(@"[^0-9\*\-\+\/\.]"); var healthPattern = patern.Matches(name).Cast<Match>().Select(x => x.Value).ToArray(); var newHealtPatern = string.Join("", healthPattern); var patern1 = new Regex(@"([-+]?(\d+\.)?\d+)"); var damagePattern = patern1.Matches(name).Cast<Match>().Select(x => x.Value).ToArray(); var patern2 = new Regex(@"[\*\/]"); var aritmeticSymbols = patern2.Matches(name).Cast<Match>().Select(x => x.Value).ToArray(); var listDaemon = new List<double>(); var sumSymbols = 0; foreach (var symbol in newHealtPatern) { sumSymbols += symbol; } listDaemon.Add(sumSymbols); var sumDamage = 0.0; foreach (var symbol in damagePattern) { var digit = double.Parse(symbol); sumDamage += digit; } foreach (var item in aritmeticSymbols) { if (item == "*") { sumDamage *= 2; } else { sumDamage /= 2; } } listDaemon.Add(sumDamage); result.Add(name, listDaemon); } foreach (var item in result) { Console.WriteLine($"{item.Key} - {item.Value[0]} health, {item.Value[1]:f2} damage"); } } } }
using System.Collections.Generic; using System; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace ProjectCompany.Models { public class Project { public int Id {get; private set;} [Required] public string Title { get; set; } public List<Contribution> Contributions { get; set; } [Required] public DatePeriod DatePeriod { get; set; } public Project(){} public Project(string title, DatePeriod datePeriod) { this.Title = title; this.DatePeriod = datePeriod; this.Contributions = new List<Contribution>(); } } }
namespace Sentry.DiagnosticSource.IntegrationTests; public static class TestDbBuilder { public static async Task CreateTableAsync(SqlConnection connection) { await using var dbContext = GetDbContext(connection); await dbContext.Database.EnsureCreatedAsync(); #if NETFRAMEWORK using var command = connection.CreateCommand(); #else await using var command = connection.CreateCommand(); #endif command.CommandText = "create table MyTable (Value nvarchar(100));"; await command.ExecuteNonQueryAsync(); } public static TestDbContext GetDbContext(SqlConnection connection, ILoggerFactory loggerFactory = null) { var builder = new DbContextOptionsBuilder<TestDbContext>(); builder.UseSqlServer(connection); builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); if (loggerFactory != null) { builder.UseLoggerFactory(loggerFactory); } return new TestDbContext(builder.Options); } public static async Task AddEfDataAsync(SqlConnection connection) { await using var dbContext = GetDbContext(connection); dbContext.Add( new TestEntity { Property = "SHOULD NOT APPEAR IN PAYLOAD" }); await dbContext.SaveChangesAsync(); } public static async Task GetEfDataAsync(SqlConnection connection) { await using var dbContext = GetDbContext(connection); await dbContext.TestEntities.ToListAsync(); } public static async Task AddDataAsync(SqlConnection connection) { #if NETFRAMEWORK using var command = connection.CreateCommand(); #else await using var command = connection.CreateCommand(); #endif command.Parameters.AddWithValue("value", "SHOULD NOT APPEAR IN PAYLOAD"); command.CommandText = "insert into MyTable (Value) values (@value);"; await command.ExecuteNonQueryAsync(); } public static async Task<List<string>> GetDataAsync(SqlConnection connection) { #if NETFRAMEWORK using var command = connection.CreateCommand(); #else await using var command = connection.CreateCommand(); #endif command.Parameters.AddWithValue("value", "SHOULD NOT APPEAR IN PAYLOAD"); command.CommandText = "select Value from MyTable where Value = @value"; #if NETFRAMEWORK using var reader = await command.ExecuteReaderAsync(); #else await using var reader = await command.ExecuteReaderAsync(); #endif var values = new List<string>(); while (await reader.ReadAsync()) { values.Add(reader.GetString(0)); } return values; } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Quote.Common; using Quote.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tests.Common; namespace UnitTests { [TestClass] public class CsvLenderDataReaderTests { [TestMethod] [ExpectExceptionWithMessage(typeof(ValidationException), "No header record was found.")] public async Task When_File_Is_Empty() { var dataReaderMock = new Mock<ILenderRawRateProvider>(); dataReaderMock.Setup(l => l.Read()).Returns(Task.FromResult("")); var lenderData = await new CsvLenderRateDeserializer(dataReaderMock.Object).Deserialize(); } [TestMethod] [ExpectExceptionWithMessage(typeof(ValidationException), "Cannot find any lender in the file.")] public async Task When_Only_Header_Is_Provided() { var dataReaderMock = new Mock<ILenderRawRateProvider>(); dataReaderMock.Setup(l => l.Read()).Returns(Task.FromResult("Lender,Rate,Available")); var lenderData = await new CsvLenderRateDeserializer(dataReaderMock.Object).Deserialize(); } [TestMethod] [ExpectExceptionWithMessage(typeof(ValidationException), "Cannot find any lender in the file.")] [DataRow("Lenders,Rate,Available")] [DataRow("abc")] [DataRow("abc,xyz,123")] public async Task No_Data_With_Incorrect_Header_Should_Throw_Exception(string headers) { var dataReaderMock = new Mock<ILenderRawRateProvider>(); dataReaderMock.Setup(l => l.Read()).Returns(Task.FromResult(headers)); var lenderData = await new CsvLenderRateDeserializer(dataReaderMock.Object).Deserialize(); } [TestMethod] [ExpectExceptionWithMessage(typeof(ValidationException), "CSV File headers are incorrect. Please make sure you have three headers with names 'Lender', 'Rate' and 'Available'.")] public async Task Incorrect_Header_With_Data() { var expected = 0; var data = @"Lenders,Rate,Available Bob,0.075,640"; var dataReaderMock = new Mock<ILenderRawRateProvider>(); dataReaderMock.Setup(l => l.Read()).Returns(Task.FromResult(data)); var lenderData = await new CsvLenderRateDeserializer(dataReaderMock.Object).Deserialize(); var actual = lenderData.Count(); Assert.AreEqual(expected, actual); } [TestMethod] public async Task Header_With_One_Row() { var expected = 1; var data = @"Lender,Rate,Available Bob,0.075,640"; var dataReaderMock = new Mock<ILenderRawRateProvider>(); dataReaderMock.Setup(l => l.Read()).Returns(Task.FromResult(data)); var lenderData = await new CsvLenderRateDeserializer(dataReaderMock.Object).Deserialize(); var actual = lenderData.Count(); Assert.AreEqual(expected, actual); } [TestMethod] [ExpectExceptionWithMessage(typeof(ValidationException), "The data 'asd' you specified in CSV file is not correct type.")] public async Task Incorrect_Rate_Should_Throw_Exception() { var data = @"Lender,Rate,Available Bob,asd,640"; var dataReaderMock = new Mock<ILenderRawRateProvider>(); dataReaderMock.Setup(l => l.Read()).Returns(Task.FromResult(data)); var lenderData = await new CsvLenderRateDeserializer(dataReaderMock.Object).Deserialize(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InoDrive.Domain.Models.OutputModels { public class OutputBidForMyTripModel { public String FirstName { get; set; } public String LastName { get; set; } public Int32 BidId { get; set; } public UserModel UserClaimed { get; set; } public Int32 TripId { get; set; } public DateTimeOffset LeavingDate { get; set; } public DateTimeOffset CreationDate { get; set; } public Decimal? Pay { get; set; } public PlaceModel OriginPlace { get; set; } public PlaceModel DestinationPlace { get; set; } public Int32 TotalPlaces { get; set; } public Int32 FreePlaces { get; set; } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using OfficeOpenXml; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using WebApp.Data; using WebApp.Data.Models; using Z.EntityFramework.Extensions; namespace WebApp.Services { public class ExcelImportService { private RepositoryContext _dbContext { get; set; } public ExcelImportService(RepositoryContext dbContext) { _dbContext = dbContext; } public async Task ImportProducts(IFormFile excelFile, string currentUrl) { EntityFrameworkManager.ContextFactory = context => _dbContext; using (ExcelPackage package = new ExcelPackage(excelFile.OpenReadStream())) { ExcelWorksheet workSheet = package.Workbook.Worksheets[0]; int totalRows = workSheet.Dimension.Rows; var localTires = new List<Tires>(); var localBrandsModels = new List<TiresModelsBrands>(); var localBrandsModelsImages = new List<TiresImages>(); var allocatedModelsBrands = _dbContext.TiresModelsBrands.ToList(); var allocatedTires = _dbContext.Tires.ToList(); var allocatedImages = _dbContext.Images.Include(x => x.TiresImages) .Include(x => x.ArticlesImages) .Include(x => x.Certificates) .Where(i => i.TiresImages.Count == 0 && i.ArticlesImages.Count == 0 && i.Certificates.Count == 0).ToList(); //Allocated not used images for (int i = 1; i <= totalRows; i++) { var brand = workSheet.Cells[i, 1]?.Value?.ToString(); var model = workSheet.Cells[i, 2]?.Value?.ToString(); var fullInfo = workSheet.Cells[i, 3]?.Value?.ToString(); var vehicleType = workSheet.Cells[i, 5]?.Value?.ToString(); var width = workSheet.Cells[i, 6]?.Value?.ToString(); var profile = workSheet.Cells[i, 7]?.Value?.ToString(); var diameter = workSheet.Cells[i, 8]?.Value?.ToString(); var loadIndex = workSheet.Cells[i, 9]?.Value?.ToString(); var speedIndex = workSheet.Cells[i, 10]?.Value?.ToString(); var price = ParsePrice(workSheet.Cells[i, 15]?.Value?.ToString()); var vendorCode = workSheet.Cells[i, 21]?.Value?.ToString(); var country = Countries.GetShortName(workSheet.Cells[i, 24]?.Value?.ToString()) ?? string.Empty; var category = "Шины"; var brandModelAsgt = allocatedModelsBrands.FirstOrDefault(x => x.Brand == brand && x.Model == model); if (brandModelAsgt == null) { brandModelAsgt = TiresModelsBrands.CreateAsgt(brand, model, country, category); allocatedModelsBrands.Add(brandModelAsgt); localBrandsModels.Add(brandModelAsgt); } var linkPart = workSheet.Cells[i, 22]?.Value?.ToString() ?? string.Empty; if (!string.IsNullOrEmpty(linkPart)) { var imageId = allocatedImages.Where(image => image.Link.Contains(linkPart)).FirstOrDefault()?.Id; if (imageId != null) { localBrandsModelsImages.Add(new TiresImages { Id = Guid.NewGuid(), ImageId = imageId.Value, IsPreview = true, ModelBrandId = brandModelAsgt.Id }); } } localTires.Add(new Tires { Id = Guid.NewGuid(), BrandModelId = brandModelAsgt.Id, FullInfo = fullInfo ?? string.Empty, Season = ParseSeason(workSheet.Cells[i, 4]?.Value?.ToString()), Width = width ?? string.Empty, Profile = profile ?? string.Empty, Diameter = diameter == null ? string.Empty : $"R{diameter}", LoadIndex = loadIndex ?? string.Empty, SpeedIndex = speedIndex ?? string.Empty, VehicleType = ParseVehicleType(vehicleType), VendorCode = vendorCode ?? string.Empty, Spike = ParseSpike(workSheet.Cells[i, 12]?.Value?.ToString()), Price = price, WholesalePrice = price }); } localBrandsModels.ForEach(x => { x.StartPrice = localTires.Where(t => t.BrandModelId == x.Id).Min(p => p.Price); }); var tiresToAdd = localTires.Where(x => !allocatedTires.Any(l => l.FullInfo == x.FullInfo)).ToList(); await _dbContext.TiresModelsBrands.AddRangeAsync(localBrandsModels); await _dbContext.TiresImages.AddRangeAsync(localBrandsModelsImages); await _dbContext.Tires.AddRangeAsync(tiresToAdd); await _dbContext.BulkSaveChangesAsync(); //await _dbContext.BulkInsertAsync(localBrandsModels, bulk => { bulk.BatchSize = 1000; }); //await _dbContext.BulkInsertAsync(tiresToAdd, bulk => { bulk.BatchSize = 5000; }); //await _dbContext.BulkInsertAsync(localBrandsModelsImages, bulk => { bulk.BatchSize = 1000; }); } } private bool ParseSpike(string value) { if (value == "шип") return true; return false; } private string ParseSeason(string value) { switch (value) { case "зимняя": return "Зима"; case "летняя": return "Лето"; case "всесезонная": return "Всесезонный"; default: return string.Empty; } } private string ParseVehicleType(string value) { switch (value) { case "легковой": return "1"; case "внедорожник": return "2"; case "микроавтобус": return "3"; case "грузовой": return "4"; case "мото": return "6"; default: return string.Empty; } } private int ParsePrice(string price) { int response = int.Parse(Regex.Match(price, @"\d+").ToString()); return response; } } }
using System; using System.Collections.Generic; using System.Text; namespace p27_euler { public class QuadraticPrimeCounter { private SimplePrime sp = new SimplePrime(); public long countConsecutivePrimes(int a, int b) { long n = 0; while(sp.isPrime(n * n + a * n + b)) { n++; } return n; } } }
using System.Collections.Generic; namespace DealOrNoDeal.Data.Rounds { /// <summary> /// Holds the dollar amounts for each version of the game /// /// Author: Alex DeCesare /// Version: 04-September-2021 /// </summary> public static class DollarValuesForEachRound { /// <summary> /// Holds the dollar values that each briefcase can have for a quick play, 18 case, game /// </summary> public static IList<int> QuickPlay = new List<int> { 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 10000, 25000, 50000, 75000, 100000 }; /// <summary> /// Holds the dollar values that each briefcase can have for a syndicated, 26 case, game /// </summary> public static IList<int> Syndicated = new List<int> { 0, 1, 5, 10, 25, 50, 75, 100, 200, 300, 400, 500, 750, 1000, 2500, 5000, 10000, 25000, 50000, 75000, 100000, 150000, 200000, 250000, 350000, 500000 }; /// <summary> /// Holds the dollar values that each briefcase can have for a regular/default, 26 case, game /// </summary> public static IList<int> Regular = new List<int> { 0, 1, 5, 10, 25, 50, 75, 100, 200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000, 75000, 100000, 200000, 300000, 400000, 500000, 750000, 1000000 }; } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class NPC : MonoBehaviour { [Header("NPC 資料")] public NPCData data; [Header("對話資訊")] public GameObject panel; [Header("對畫名稱")] public Text textName; [Header("對話內容")] public Text textContent; [Header("第一段對話完要顯示的物件")] public GameObject objectShow; public GameObject spawnShow; [Header("任務資訊")] public RectTransform rectMission; private AudioSource aud; private Player player; private Animator ani; //private string private void Awake() { aud = GetComponent<AudioSource>(); player = FindObjectOfType<Player>(); ani = GetComponent<Animator>(); data.state = StateNPC.NOMission; } private IEnumerator Type() { PlayAni(); player.stop = true; textContent.text = ""; string dialog = data.dialogs[(int)data.state]; for (int i = 0; i < dialog.Length; i++) { textContent.text += dialog[i]; aud.PlayOneShot(data.soundType, 0.5f); yield return new WaitForSeconds(data.speed); } player.stop = false; NoMission(); } private void PlayAni() { if(data.state != StateNPC.Finish) { ani.SetBool("speak", true); } else { ani.SetTrigger("完成"); } } private void NoMission() { if (data.state != StateNPC.NOMission) return; data.state = StateNPC.Missioning; objectShow.SetActive(true); spawnShow.SetActive(true); StartCoroutine(ShowMission()); } private IEnumerator ShowMission() { while (rectMission.anchoredPosition.x > -220) { rectMission.anchoredPosition -= new Vector2(1000 * Time.deltaTime, 0); yield return null; } } private void Missioning() { } public void Finish() { data.state = StateNPC.Finish; } private void DialogStart() { panel.SetActive(true); textName.text = name; StartCoroutine(Type()); } private void DialogStop() { panel.SetActive(false); ani.SetBool("speak", false); } //面向玩家 private void LookAtPlayer(Collider other) { Vector3 pos = other.transform.position; pos.y = transform.position.y; Quaternion angle = Quaternion.LookRotation(other.transform.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, angle, Time.deltaTime * 5); } private void OnTriggerEnter(Collider other) { if (other.name == "player") { DialogStart(); } } private void OnTriggerExit(Collider other) { if (other.name == "player") { DialogStop(); } } private void OnTriggerStay(Collider other) { if (other.name == "player") { LookAtPlayer(other); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Colours { class WeaponC : Weapon { private readonly int[] DAMAGE = new int[3] { 2, 4, 6 }; private readonly int[] RADIUS = new int[3] { 4, 8, 16 }; private readonly int[] COOLGAIN = new int[3] { 2, 3, 4 }; private readonly int[] COOLTIMEMAX = new int[3] { 30, 25, 20 }; private readonly int[] POWERMAX = new int[3] { 120, 180, 240 }; //DAMAGE OUTPUT: 120, 240, 360 const byte NUMBER = 3; const bool AUTO = true; public override byte Number { get { return NUMBER; } } public override bool Auto { get { return AUTO; } } int power; int shots;// int cooltime; bool charging; bool empty; bool fired; UI hud; public WeaponC(UI ui, Texture2D weaponTexture, Texture2D hairTexture) : base(ui, weaponTexture, hairTexture) { hud = ui; } public override bool Fire() { if (active && !empty && level != -1) { fired = false; if (power > 0) { power -= COOLGAIN[level]; fired = true; cooltime = COOLTIMEMAX[level]; shots++; } if (power <= 0) { fired = false; empty = true; } } return fired; } public override void Cool() { if (level != -1) { if (power < POWERMAX[level])//recharging { if (cooltime > 0) { cooltime--; } if (cooltime <= 0) { charging = true; power++; } } else if (power >= POWERMAX[level])//charged { empty = false; charging = false; power = POWERMAX[level];//reset overfill on delevel shots = 0;// } } } public override void InstaCool() { empty = false; charging = false; power = POWERMAX[level]; } public override void DrawUI(Vector2 mousePos, Vector2 playerPos, byte colour) { if (level != -1) { hud.DrawWeaponStatus(1, power, POWERMAX[level], empty, charging, Color.Red, Color.Orange); hud.DrawBool(16, 850, fired); hud.DrawInt(128, 800, shots); hud.DrawInt(128, 825, (shots * DAMAGE[level])); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Observer { abstract class ObservadorDeContainers { public abstract void AnalizarContainer(AlgoObservable container); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public enum RGBType { All, Red, Green, Blue, End } public enum PlatformType { Normal, HorizontalMove, } public class Platform : MonoBehaviour { private PlatformMaker platformMaker; private ObjectPool<Platform> parentPool; private Transform playerTr; private PlatformType platformType = PlatformType.Normal; private float moveSpeed = 2f; [SerializeField] private Tile centerTile; public Tile CenterTile { get { return centerTile; } } [SerializeField] private SpriteRenderer spriteRenderer; private void Awake() { spriteRenderer = GetComponentInChildren<SpriteRenderer>(); } public void SetParent(ObjectPool<Platform> parent) { if (this.parentPool == null) this.parentPool = parent; } private void Update() { if (playerTr.transform.position.y > centerTile.transform.position.y + GameConstant.PlatformDestroyDistance) { PlatformOff(); } } private enum MoveDirection { left,right,down,up } private IEnumerator MoveHorizontal() { MoveDirection moveDirection = (MoveDirection)UnityEngine.Random.Range(0, 2); moveSpeed = UnityEngine.Random.Range(1f, PlatformData.GetMaximumSpeed); while (true) { if (moveDirection == MoveDirection.left) { this.transform.position += Vector3.left * moveSpeed * Time.deltaTime; if (this.transform.position.x <= GameConstant.LeftEndPosit+GameConstant.HorizontalMoveOffset) { moveDirection = MoveDirection.right; } } else if (moveDirection == MoveDirection.right) { this.transform.position += Vector3.right * moveSpeed * Time.deltaTime; if (this.transform.position.x >= GameConstant.RightEndPosit-GameConstant.HorizontalMoveOffset) { moveDirection = MoveDirection.left; } } yield return null; } } private IEnumerator MoveVertical() { yield break; } //소멸 private void PlatformOff() { if (platformMaker != null) platformMaker.MakeNextPlatform(); StopAllCoroutines(); this.gameObject.SetActive(false); } public void SetProperties(Transform playerTr, PlatformMaker platformMaker) { if (this.playerTr == null) this.playerTr = playerTr; if (this.platformMaker == null) this.platformMaker = platformMaker; } public void SetPlatformType(PlatformType platformType) { this.platformType = platformType; switch (platformType) { case PlatformType.HorizontalMove: { StartCoroutine(MoveHorizontal()); } break; } } public void Initialize(RGBType rgbType) { SetLayerAndSprite(rgbType); } private void SetLayerAndSprite(RGBType rgbType) { #if UNITY_EDITOR // rgbType = RGBType.All; #endif Color targetColor = Color.black; int layerMask = LayerMask.NameToLayer(LayerName.All); switch (rgbType) { case RGBType.Red: { targetColor = Color.red; layerMask = LayerMask.NameToLayer(LayerName.Red); } break; case RGBType.Green: { targetColor = Color.green; layerMask = LayerMask.NameToLayer(LayerName.Green); } break; case RGBType.Blue: { targetColor = Color.blue; layerMask = LayerMask.NameToLayer(LayerName.Blue); } break; } if (spriteRenderer != null) spriteRenderer.color= targetColor; if (centerTile != null) centerTile.gameObject.layer = layerMask; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BankApp.DTOs { public class Transfer { [Required] public int idSender { get; set; } [Required] public int idReceiver { get; set; } [Required] [RegularExpression(@"^[+]?\d+([.]\d+)?$")] public int amount { get; set; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PayByPhoneTwitter.Controllers; using Moq; using System.Collections.Generic; using PayByPhoneTwitter.Models; using FluentAssertions; namespace PayByPhoneTwitter.Tests { [TestClass] public class JSonControllerTests { public Mock<ITweetAggregator> tweetAggregatorMock { get; set; } public Mock<IAccountAggregateRenderer> aggregateRendererMock { get; set; } public JSonController jsonController { get; set; } [TestInitialize] public void Setup() { tweetAggregatorMock = new Mock<ITweetAggregator>(); aggregateRendererMock = new Mock<IAccountAggregateRenderer>(MockBehavior.Strict); List<string> accounts = new List<string>(); accounts.Add("Test"); tweetAggregatorMock.Setup(x => x.Accounts).Returns(accounts); jsonController = new JSonController(); jsonController.TweetAggregatorFactory = SetupHelperMethods.SetupMockTweetAggregatorFactory(tweetAggregatorMock).Object; jsonController.Renderer = aggregateRendererMock.Object; } [TestMethod] public void JSon_ShouldReturnContentResultContainingOnlyJSonOutputFromRenderer() { List<AccountAggregate> reference = new List<AccountAggregate>(); tweetAggregatorMock.Setup(x => x.Get()).Returns(reference).Verifiable(); aggregateRendererMock.Setup(x => x.RenderAccountAggregate(It.Is<List<AccountAggregate>>(d => d == reference))).Returns("JSON!").Verifiable(); System.Web.Mvc.ContentResult result = jsonController.Index() as System.Web.Mvc.ContentResult; result.ContentType.Should().Be("application/json"); result.Content.Should().Be("JSON!"); tweetAggregatorMock.Verify(); aggregateRendererMock.Verify(); } } }
using Backend.Model; using Backend.Model.Pharmacies; using System.Collections.Generic; using System.Linq; namespace IntegrationAdaptersTenderService.Repository.Implementation { public class MySqlTenderMessageRepository : ITenderMessageRepository { private readonly MyDbContext _context; public MySqlTenderMessageRepository(MyDbContext context) { _context = context; } public void CreateTenderMessage(TenderMessage tm) { _context.TenderMessages.Add(tm); _context.SaveChanges(); } public TenderMessage GetAcceptedByTenderId(int id) { return _context.TenderMessages.FirstOrDefault(x => x.TenderId == id && x.IsAccepted == true); } public IEnumerable<TenderMessage> GetAll() { return _context.TenderMessages.ToList(); } public IEnumerable<TenderMessage> GetAllByTender(int id) { return _context.TenderMessages.Where(tm => tm.TenderId == id).ToList(); } public TenderMessage GetById(int id) { return _context.TenderMessages.FirstOrDefault(tm => tm.Id == id); } public void UpdateTenderMessage(TenderMessage tm) { _context.TenderMessages.Update(tm); _context.SaveChanges(); } } }
using Discord; using Discord.Commands; namespace JhinBot { public interface IPollService : IService { bool PeekPollForContext(ICommandContext context); EmbedBuilder GetPollCantBeClosedEmbed(ICommandContext context); EmbedBuilder GetPollClosedEmbed(ICommandContext context); EmbedBuilder GetPollShowEmbed(ICommandContext context); EmbedBuilder GetPollStartEmbed(ICommandContext context); void TryAddingNewVote(string pollVote, ICommandContext context); bool TryToStartNewPoll(string[] pollChoices, ICommandContext context); bool TryToClosePoll(ICommandContext context); void ClosePoll(ICommandContext context); } }
namespace Krafteq.ElsterModel { using System; using Krafteq.ElsterModel.ValidationCore; using LanguageExt; using static LanguageExt.Prelude; public class KzFieldType : NewType<KzFieldType, string> { readonly Func<object, Validation<KzFieldError, KzFieldValue>> valueFactory; public static readonly KzFieldType Boolean = new KzFieldType( "boolean", BooleanValue); public static readonly KzFieldType MoneyIntUp = new KzFieldType("money-int.round-up", DecimalValue(KzFieldValue.MoneyInt, MoneyInt.RoundUp)); public static readonly KzFieldType MoneyIntDown = new KzFieldType( "money-int.round-down", DecimalValue(KzFieldValue.MoneyInt, MoneyInt.RoundDown)); public static readonly KzFieldType MoneyUp = new KzFieldType("money.round-up", DecimalValue(KzFieldValue.Money, Money.RoundUp)); public static readonly KzFieldType MoneyDown = new KzFieldType("money.round-down", DecimalValue(KzFieldValue.Money, Money.RoundDown)); public static readonly KzFieldType UnsignedMoneyDown = new KzFieldType("money-unsigned.round-down", DecimalValue(KzFieldValue.UnsignedMoney, UnsignedMoney.RoundDown)); public static readonly KzFieldType UnsignedMoneyUp = new KzFieldType("money-unsigned.round-up", DecimalValue(KzFieldValue.UnsignedMoney, UnsignedMoney.RoundUp)); KzFieldType(string value, Func<object, Validation<KzFieldError, KzFieldValue>> valueFactory) : base(value) { this.valueFactory = valueFactory; } public Validation<KzFieldError, KzFieldValue> CreateFieldValue(object value) => this.valueFactory(value); static Func<object, Validation<KzFieldError, KzFieldValue>> DecimalValue<T>( Func<T, KzFieldValue> fieldValueFactory, Func<decimal, Validation<NumericError, T>> intermediateFactory) => DecimalValue(x => intermediateFactory(x).Map(fieldValueFactory)); static Func<object, Validation<KzFieldError, KzFieldValue>> DecimalValue( Func<decimal, Validation<NumericError, KzFieldValue>> fieldValueFactory) => value => CreateDecimal(value) .Bind(d => fieldValueFactory(d) .MapFail(KzFieldError.FromDecimalValidationError) ); static Validation<KzFieldError, KzFieldValue> BooleanValue(object value) => CreateBoolean(value).Map(KzFieldValue.Boolean); static Validation<KzFieldError, bool> CreateBoolean(object value) => TryCreateBool(value).ToValidation(KzFieldError.BooleanPresentationError); static Validation<KzFieldError, decimal> CreateDecimal(object value) => TryCreateDecimal(value).ToValidation(KzFieldError.DecimalPresentationError); static Option<bool> TryCreateBool(object value) { if (isnull(value)) return None; if (value is string stringValue) return parseBool(stringValue); if (value is bool boolValue) return boolValue; return Try(() => Convert.ToBoolean(value)).ToOption(); } static Option<decimal> TryCreateDecimal(object value) { if (isnull(value)) return None; if (value is string stringValue) return parseDecimal(stringValue); return Try(() => Convert.ToDecimal(value)).ToOption(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIManager : MonoBehaviour { [SerializeField] Text seedText = default; [SerializeField] Text timerText = default; [SerializeField] Text counterText = default; [SerializeField] Text zoneText = default; public void UpdateScore(int Score) { counterText.text = $"x {Score}"; } public void UpdateZone(Zone newZone) { zoneText.text = newZone.name; SetUiColour(newZone.zoneColour); seedText.text = $"Current Seed:\n {newZone.GetZoneSeed()}"; } public void SetUiColour(Color newColour) { seedText.color = newColour; timerText.color = newColour; counterText.color = newColour; zoneText.color = newColour; } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace PeriodicTable { class InputTable { //initial table stores all basic explosives found in the Internet //in addition, it can be used to reset Table.txt //russian version private StringBuilder InitialTableRus; //english version private StringBuilder InitialTableEng; //file TableName is the one we work with private string TableName; public InputTable(string tableName) { //because I can //russian InitialTableRus = new StringBuilder( "Алюминий\tAl\n" + "Аммония карбонат\t(NH4)2CO3\n" + "Аммония нитрат\tNH4NO3\n" + "Аммония перхлорат\tNH4ClO4\n" + "Аммония пикрат\tNH4C6H2(NO2)3O\n" + "Аммония сульфат\t(NH4)2SO4\n" + "Аммония хлорид\tNH4Cl\n" + "Антрацен\tC14H10\n" + "Бария нитрат\tBa(NO3)2\n" + "Бария хлорат\tBa(ClO3)2H2O\n" + "Бария хромат\tBaCrO4\n" + "Бария перекись\tBaO2\n" + "Бария силицид\tBaSi2\n" + "Бумага\t-1,3\n" + "Вазелин\tC18H38\n" + "Глицерин\tC3H5(OH)3\n" + "Глюкоза\tC6H12O6\n" + "Гремучая ртуть\tHg(ONC)2\n" + "Декстрин\tC6H10O5\n" + "Динитробензол\tC6H4(NO2)2\n" + "Динитроглицерин\tC3H5(ONO2)2OH\n" + "Динитроксилол\tC6H2(NO2)2(CH3)2\n" + "Динитронафталин\tC10H6(NO2)2\n" + "Динитрохлоргидрин\tC3H5(ONO2)2Cl\n" + "Динитрофенол\tC6H3(NO2)2OH\n" + "Динитротолуол\tC6H3(NO2)2CH3\n" + "Дициандиамид\t(CN)2(NH2)2\n" + "Калия бихромат\tK2Cr2O7\n" + "Калия нитрат\tKNO3\n" + "Калия хлорат\tKClO3\n" + "Калия перхлорат\tKClO4\n" + "Калия пикрат\tC6H2(NO2)3OK\n" + "Кальция нитрат\tCa(NO3)2H8O4\n" + "Кальция перхлорат\tCa(ClO4)2\n" + "Кальция хлорат\tCa(ClO3)2\n" + "Кальция силицид\tCaSi2\n" + "Камфора\tC10H16O\n" + "Керосин\t-3,43\n" + "Клетчатка\tC6H10O5\n" + "Крахмал\tC6H10O5\n" + "Маннит\tC6H8(OH)6\n" + "Мононитроглицерин\tC3H5(ONO2)(OH)2\n" + "Мононитроглицерин\tC10H7NO2\n" + "Мононитрохлоргидрин\tC3H5(ONO2)OHCl\n" + "Мононитротолуол\tC6H4(NO2)CH3\n" + "Мононитрофенол\tC6H4(NO2)OH\n" + "Мука злаков\tC15H25O11\n" + "Мука древесная(очищ.)\tC15H22O10\n" + "Мука древесная(опилки)\t-1,35\n" + "Масло(растительное)\tC23H36O7\n" + "Натрия нитрат\tNaNO3\n" + "Натрия хлорат\tNaClO3\n" + "Натрия перхлорат\tNaClO4\n" + "Натрия пикрат\tC6H2(NO2)3ONa\n" + "Нафталин\tC10H8\n" + "Нитробензол\tC6H5NO2\n" + "Нитроглицерин\tC3H5(ONO2)3\n" + "Нитрогуанидин\tC(NH2)2NNO2\n" + "Нитроклетчатка(коллоксилин)\tC24H31N9O38\n" + "Нитроклетчатка(пироксилин)\tC24H29N11O42\n" + "Нитрокрахмал\t-0,335\n" + "Нитроманнит\tC6H8(NO3)6\n" + "Парафин\tC24H50\n" + "Пикриновая кислота\tC6H2(NO2)3OH\n" + "Сахар(тростниковый)\tC12H22O11\n" + "Сера\tS\n" + "Свинца нитрат\tPb(NO3)2\n" + "Скипидар\tC10H16\n" + "Стронция нитрат\tSr(NO3)2\n" + "Сурьма сернистая\tSb2S3\n" + "Сурьма металлическая\tSb\n" + "Таннин\tC14H10O9\n" + "Тетранитроанилин\tC6H(NH2)(NO2)4\n" + "Тетранитродиглицерин\t(C3H5)2O(NO3)4\n" + "Тетранитродиметиланилин\tC6H(NO2)3N(CH3)2\n" + "Тетранитрометан\tC(NO2)4\n" + "Теранитрометиланилин\tC6H2(NO2)4NCH3\n" + "Тетранитронафталин\tC10H4(NO2)4\n" + "Тринитроанилин\tC6H2(NO2)3NH2\n" + "Тринитробензол\tC6H3(NO2)3\n" + "Тринитродиметиланилин\tC6H2(NO2)3N(CH3)2\n" + "Тринитрокрезол\tC6HCH3(NO2)3OH\n" + "Тринитронафталин\tC10H5(NO2)3\n" + "Тринитрорезорцин\tC6H(NO2)3(OH)2\n" + "Тринитротолуол\tC6H2(NO2)3CH3\n" + "Уголь\tC\n" + "Фенол\tC6H5OH" ); //english InitialTableEng = new StringBuilder( "Aluminum\tAl\n" + "Ammonium carbonate\t(NH4)2CO3\n" + "Ammonium nitrate\tNH4NO3\n" + "Ammonium perchlorate\tNH4ClO4\n" + "Ammonium picrate\tNH4C6H2(NO2)30O\n" + "Ammonium sulfate\t(NH4)2SO4\n" + "Ammonium chloride\tNH4Cl\n" + "Anthracene\tC14H10\n" + "Barium nitrate\tBa(NO3)2\n" + "Barium chlorate\tBa(ClO3)2H2O\n" + "Barium chromate\tBaCrO4\n" + "Barium peroxide\tBaO2\n" + "Barium silicide\tBaSi2\n" + "Paper\t-1.3\n" + "Vaseline\tC18H38\n" + "Glycerin\tC3H5(OH)3\n" + "Glucose\tC6H12O6\n" + "Explosive mercury\tHg(ONC)2\n" + "Dextrin\tC6H10O5\n" + "Dinitrobenzene\tC6H4(NO2)2\n" + "Dinitroglycerin\tC3H5(ONO2)2OH\n" + "Dinitroxylene\tC6H2(NO2)2(CH3)2\n" + "Dinitronaphthalene\tC10H6(NO2)2\n" + "Dinitrochlorohydrin\tC3H5(ONO2)2Cl\n" + "Dinitrophenol\tC6H3(NO2)2OH\n" + "Dinitrotoluene\tC6H3(NO2)2CH3\n" + "Dicyandiamide\t(CN)2(NH2)2\n" + "Potassium Dichromate\tK2Cr2O7\n" + "Potassium nitrate\tKNO3\n" + "Potassium chlorate\tKClO3\n" + "Potassium perchlorate\tKClO4\n" + "Potassium picrate\tC6H2(NO2)3OK\n" + "Calcium nitrate\tCa(NO3)2H8O4\n" + "Calcium perchlorate\tCa(ClO4)2\n" + "Calcium chlorate\tCa(ClO3)2\n" + "Calcium silicide\tCaSi2\n" + "Camphor\tC10H16O\n" + "Kerosene\t-3.43\n" + "Fiber\tC6H10O5\n" + "Starch\tC6H10O5\n" + "Mannitol\tC6H8(OH)6\n" + "Mononitroglycerin\tC3H5(ONO2)(OH)2\n" + "Mononitroglycerin\tC10H7NO2\n" + "Mononitrochlorohydrin\tC3H5(ONO2)OHCl\n" + "Mononitrotoluene\tC6H4(NO2)CH3\n" + "Mononitrophenol\tC6H4(NO2)OH\n" + "Cereal flour\tC15H25O11\n" + "Wood flour(peeled.)\tC15H22O10\n" + "Wood flour(sawdust)\t-1.35\n" + "Oil(vegetable)\tC23H36O7\n" + "Sodium nitrate\tNaNO3\n" + "Sodium chlorate\tNaClO3\n" + "Sodium perchlorate\tNaClO4\n" + "Sodium picrate\tC6H2(NO2)3ONa\n" + "Naphthalene\tC10H8\n" + "Nitrobenzene\tC6H5NO2\n" + "Nitroglycerin\tC3H5(ONO2)3\n" + "Nitroguanidine\tC(NH2)2NNO2\n" + "Nitrocellulose(colloxylin)\tC24H31N9O38\n" + "Nitrocellulose(pyroxylin)\tC24H29N11O42\n" + "Nitro starch\t-0.335\n" + "Nitromannite\tC6H8(NO3)6\n" + "Paraffin\tC24H50\n" + "Picric acid\tC6H2(NO2)3OH\n" + "Sugar(cane)\tC12H22O11\n" + "Sulfur\tS\n" + "Lead nitrate\tPb(NO3)2\n" + "Turpentine\tC10H16\n" + "Strontium nitrate\tSr(NO3)2\n" + "Antimony sulphide\tSb2S3\n" + "Antimony metal\tSb\n" + "Tannin\tC14H10O9\n" + "Tetranitroaniline\tC6H(NH2)(NO2)4\n" + "Tetranitrodiglycerin\t(C3H5)2O(NO3)4\n" + "Tetranitrodimethylaniline\tC6H(NO2)3N(CH3)2\n" + "Tetranitromethane\tC(NO2)4\n" + "Teranitromethylaniline\tC6H2(NO2)4NCH3\n" + "Tetranitronaphthalene\tC10H4(NO2)4\n" + "Trinitroaniline\tC6H2(NO2)3NH2\n" + "Trinitrobenzene\tC6H3(NO2)3\n" + "Trinitrodimethylaniline\tC6H2(NO2)3N(CH3)2\n" + "Trinitrocresol\tC6HCH3(NO2)3OH\n" + "Trinitronaphthalene\tC10H5(NO2)3\n" + "Trinitroresorcinol\tC6H(NO2)3(OH)2\n" + "Trinitrotoluene\tC6H2(NO2)3CH3\n" + "Coal\tC\n" + "Phenol\tC6H5OH" ); TableName = tableName; } //create file depending on culture public void CreateTable(string cultureName) { //Table.ru-RU.txt, for example var fileName = TableName + "." + cultureName + ".txt"; //if there's no Table we create it and fill with InitialTable if (!File.Exists(fileName)) { using (StreamWriter sw = new StreamWriter(fileName, false)) { sw.WriteLine((cultureName == "ru-RU") ? InitialTableRus : InitialTableEng); } } } } }
namespace Sentry.Tests.Extensibility; public class SentryEventExceptionProcessorTests { [Fact] public void Process_IncompatibleType_ProcessExceptionNotInvoked() { var sut = Substitute.For<SentryEventExceptionProcessor<InvalidOperationException>>(); sut.Process(new Exception(), new SentryEvent()); sut.DidNotReceive().ProcessException(Arg.Any<InvalidOperationException>(), Arg.Any<SentryEvent>()); } [Fact] public void Process_ExactType_ProcessExceptionInvoked() { var sut = Substitute.For<SentryEventExceptionProcessor<Exception>>(); sut.Process(new Exception(), new SentryEvent()); sut.Received(1).ProcessException(Arg.Any<Exception>(), Arg.Any<SentryEvent>()); } [Fact] public void Process_BaseType_ProcessExceptionInvoked() { var sut = Substitute.For<SentryEventExceptionProcessor<ArgumentException>>(); sut.Process(new ArgumentNullException(), new SentryEvent()); sut.Received(1).ProcessException(Arg.Any<ArgumentException>(), Arg.Any<SentryEvent>()); } }
using System.Windows.Controls; using LAB02.Tools.Navigation; using LAB02.ViewModels; namespace LAB02.Views { /// <summary> /// Interaction logic for EnterInfoControl.xaml /// </summary> public partial class EnterInfoView : UserControl, INavigatable { public EnterInfoView() { InitializeComponent(); DataContext = new EnterInfoViewModel(); } } }
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode ReverseList(ListNode head) { ListNode pre = null, curr = head; while (curr != null) { ListNode tmp = curr.next; curr.next = pre; pre = curr; curr = tmp; } return pre; } }
using System.Collections.Generic; using System.Linq; using Simulator.Utils; // ReSharper disable MemberCanBeMadeStatic.Local namespace Simulator { public class CpuMemory { public CpuMemory(int size) { MemorySize = size; Blocks = new List<CpuBinary>(); GenerateMemory(); } private List<CpuBinary> Blocks { get; } private int MemorySize { get; } public CpuValue GetValueAt(int address, int length) { if (address < 0 || address >= MemorySize) throw new IncorrectMemoryAddressException(); return CpuValue.FromBinary(Blocks.Skip(address).Take(length)); } public void SetValue(CpuValue value, int address) { if (address < 0 || address >= MemorySize) throw new IncorrectMemoryAddressException(); for (var i = address; i < value.Size + address; i++) Blocks[i] = value.Bin[i - address] == '1' ? CpuBinary.One : CpuBinary.Zero; } private void GenerateMemory() { for (var i = 0; i < MemorySize; i++) Blocks.Add(CpuBinary.Zero); } } }
namespace Joqds.Tools.KpiExtractor.Contract { public enum KpiTypeStatus { Draft=0, Active, Disable } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RPC.v1 { public interface IServiceDiscoverer { /// <summary> /// Returns an array of all known interface types that have an RPCAttribute defined on them. /// </summary> /// <returns></returns> RPCInterface[] DiscoverInterfaces(); /// <summary> /// Given a specific interface type, find its concrete implementation class to be invoked service-side. /// </summary> /// <param name="type"></param> /// <returns></returns> Type DiscoverImplementationFor(Type type); } }
using System; using System.Text.Json; using System.Threading.Tasks; using Core.Interfaces; using StackExchange.Redis; namespace Infrastructure.Services { public class ResponceCacheService : IResponseCacheService { private readonly IDatabase _database; public ResponceCacheService(IConnectionMultiplexer redis) { _database=redis.GetDatabase(); } public async Task CacheResponseAsync(string cacheKey, object response, TimeSpan timeToLive) { if(response==null){ return ; } var options=new JsonSerializerOptions{ PropertyNamingPolicy=JsonNamingPolicy.CamelCase }; var serialisedResponse=JsonSerializer.Serialize(response,options); await _database.StringSetAsync(cacheKey,serialisedResponse,timeToLive); } public async Task<string> GetCacheResponseAsync(string cacheKey) { var cachedResponse=await _database.StringGetAsync(cacheKey); if(cachedResponse.IsNullOrEmpty){ return null; } return cachedResponse; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using PatientsRegistry.Search; namespace PatientsRegistry.Registry { public interface IPatientsRegistry { Task<PatientDto> FindPatientAsync(Guid id); Task<IEnumerable<PatientDto>> FindPatientsAsync(SearchParameters parameters); Task<PatientDto> RegisterPatientAsync(PatientCreate patientCreate); Task<PatientDto> UpdatePatientAsync(PatientUpdate patient); Task DeactivatePatientAsync(Guid id); Task<ContactDto> SetContact(Guid patientId, ContactDto contact); Task RemoveContact(Guid patientId, string contactType, string contactKind); } }
using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using DG.Tweening; using UnityEngine; using UnityEngine.UI; public class SuccessEffect : MonoBehaviour { private static SuccessEffect _instances; public static SuccessEffect Instances { get { if (_instances == null) { _instances = FindObjectOfType<SuccessEffect>(); } return _instances; } } public Text _now_Score; //显示当前关卡分数组件 public Text _diamond; //显示钻石数量组件 public GameObject _new_Title; //新纪录组件 private List<Transform> _stars_List; //星星组件数组 private int _times; //星星动画执行次数 private int _score; //分数计数器 private int _add_Once; //计数每次加的字数 private int _add_Times; //增加次数 private bool _auto; //自动播放开关 private bool _start_Effect; //特效开关 private int _star_Number; //星星数量 private int _diamond_Number; //钻石计数器 private int _add_Diamond_Number; //钻石数 private bool _diamond_Bool; //控制增加钻石为零时只执行一次的开关 void Update() { if(!_start_Effect) return; ScoreEffect(); ShowDiamond(_star_Number); KillEffect(); } //初始化函数 void Initialization() { _stars_List = new List<Transform>(); _stars_List.Add(transform.GetChild(0)); _stars_List.Add(transform.GetChild(1)); _stars_List.Add(transform.GetChild(2)); _auto = true; _diamond_Bool = false; _score = 0; _diamond_Number = 0; _add_Once = 3; _add_Times = MyKeys.Game_Score/_add_Once; if (_star_Number - MyKeys.PassStarsMax > 0) { _add_Diamond_Number = (_star_Number - MyKeys.PassStarsMax) * 2; } else { _add_Diamond_Number = 0; } } public void StartSuccessEffect(int starNumber) { _star_Number = starNumber; Initialization(); _start_Effect = true; } //分数动效 void ScoreEffect() { if (_auto && _score < MyKeys.Game_Score) { int temp = _score / _add_Once; if (temp < _add_Times) { _score += _add_Once; } else { _score++; } _now_Score.text = _score.ToString(); MyAudio.PlayAudio(StaticParameter.s_Count, false, StaticParameter.s_Count_Volume); } } //钻石动效 void ShowDiamond(int stars) { if (_score == MyKeys.Game_Score) { //得到的钻石数>0,执行钻石动效 if (_diamond_Number < _add_Diamond_Number) { _diamond_Number ++; _diamond.text = _diamond_Number.ToString(); MyAudio.PlayAudio(StaticParameter.s_Count, false, StaticParameter.s_Count_Volume); if (_diamond_Number == _add_Diamond_Number) { StarsEffect(stars); } } //得到的钻石数为0 if (_add_Diamond_Number == 0&& !_diamond_Bool) { _diamond_Bool = true; _diamond.text = _add_Diamond_Number.ToString(); StarsEffect(stars); if (stars == 0) { NewScoreEffect(); } } } } //星星动效 void StarsEffect(int number) { if (number > 0) { _stars_List[_times].gameObject.SetActive(true); _stars_List[_times].DOScale(2, 0.5f); _stars_List[_times].DOPlay(); MyAudio.PlayAudio(StaticParameter.s_Star, false, StaticParameter.s_Star_Volume); StartCoroutine(Next(number)); } else { NewScoreEffect(); } } IEnumerator Next(int number) { yield return new WaitForSeconds(1); _times++; if (_auto) { if (_times < number) { StarsEffect(number); } else { _times = 0; NewScoreEffect(); } } } //新纪录动效 void NewScoreEffect() { MyAudio.PlayAudio(StaticParameter.s_New_record, false, StaticParameter.s_New_record_Volume); if (MyKeys.Game_Score == MyKeys.Top_Score) { _new_Title.SetActive(true); _new_Title.transform.DOScale(1, 0.5f); _new_Title.transform.DOPlay(); } } //跳过动效 void KillEffect() { if (Input.GetMouseButtonDown(0) && _auto) { _auto = false; //显示分数 _now_Score.text = MyKeys.Game_Score.ToString(); //显示钻石 if (_add_Diamond_Number>0) { _diamond.text = _add_Diamond_Number.ToString(); } //显示新纪录 if (MyKeys.Game_Score == MyKeys.Top_Score) { _new_Title.gameObject.SetActive(true); _new_Title.transform.DOKill(); _new_Title.transform.localScale = Vector3.one; } //显示星级 for (int i = 0; i < _star_Number; i++) { _stars_List[i].gameObject.SetActive(true); _stars_List[i].localScale = Vector3.one*2; _stars_List[i].DOKill(); } } } }
using System; using System.Collections.Generic; using System.Text; using Hayaa.DataAccess; using Hayaa.BaseModel; using Hayaa.Security.Service.Config; /// <summary> ///代码效率工具生成,此文件不要修改 /// </summary> namespace Hayaa.Security.Service.Dao { internal partial class Rel_App_AppFunctionDal : CommonDal { private static String con = ConfigHelper.Instance.GetConnection(DefineTable.DatabaseName); internal static int Add(Rel_App_AppFunction info) { string sql = "insert into Rel_App_AppFunction(Id,AppId,AppFunctionId) values(@Id,@AppId,@AppFunctionId)"; return Insert<Rel_App_AppFunction>(con, sql, info); } internal static int Update(Rel_App_AppFunction info) { string sql = "update Rel_App_AppFunction set Id=@Id,AppId=@AppId,AppFunctionId=@AppFunctionId where Rel_App_AppFunctionId=@Rel_App_AppFunctionId"; return Update<Rel_App_AppFunction>(con, sql, info); } internal static bool Delete(List<int> IDs) { string sql = "delete from Rel_App_AppFunction where Rel_App_AppFunctionId in @ids"; return Excute(con, sql, new { ids = IDs.ToArray() }) > 0; } internal static Rel_App_AppFunction Get(int Id) { string sql = "select * from Rel_App_AppFunction where Rel_App_AppFunctionId=@Rel_App_AppFunctionId"; return Get<Rel_App_AppFunction>(con, sql, new { Rel_App_AppFunctionId = Id }); } //internal static List<Rel_App_AppFunction> GetList(Rel_App_AppFunctionSearchPamater pamater) //{ // string sql = "select * from Rel_App_AppFunction " + pamater.CreateWhereSql(); // return GetList<Rel_App_AppFunction>(con, sql, pamater); //} } }
using senai_hroads_webApi.Contexts; using senai_hroads_webApi.Domains; using senai_hroads_webApi.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace senai_hroads_webApi.Repositories { public class LoginRepository : ILoginRepository { HroadsContext _context = new HroadsContext(); public Usuario BuscarPorEmailSenha(string email, string senha) { Usuario usuarioLogin = _context.Usuarios.FirstOrDefault(e => e.Email == email && e.Senha == senha); if (usuarioLogin.Email != null) { return usuarioLogin; } return null; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net.Http; using System.Diagnostics; using System.Web.Script.Serialization; using System.Text; using System.Net.Http.Headers; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Genesys.WebServicesClient; namespace Genesys.WebServicesClient.Test { [TestClass] public class Samples { public TestContext TestContext { get; set; } [TestMethod] public void Receive_events() { var client = new GenesysClient.Setup() { ServerUri = TestParams.ServerUri, UserName = TestParams.UserName, Password = TestParams.Password, AsyncTaskScheduler = TaskScheduler.Default, } .Create(); using (client) { var versionResponse = client.CreateRequest("GET", "/api/v2/diagnostics/version").SendAsync().Result; TestContext.WriteLine("Received: {0}", versionResponse); using (var eventReceiver = client.CreateEventReceiver(new GenesysEventReceiver.Setup())) { var subscription = eventReceiver.SubscribeAll((s, e) => { TestContext.WriteLine("Comet message received: {0}", e); }); eventReceiver.Open(5000); var postResponse = client.CreateRequest("POST", "/api/v2/me", new { operationName = "Ready" }).SendAsync().Result; TestContext.WriteLine("POST response: {0}", postResponse); Thread.Sleep(1000); var notReadyPostResponse = client.CreateRequest("POST", "/api/v2/me", new { operationName = "NotReady" }).SendAsync().Result; TestContext.WriteLine("POST response: {0}", notReadyPostResponse); Thread.Sleep(1000); subscription.Dispose(); Thread.Sleep(1000); } } } } }
using System.Windows.Controls; using GalaSoft.MvvmLight; using JeopardySimulator.Ui.Infrastructure; namespace JeopardySimulator.Ui.Views { /// <summary> /// Description for CommandResultsView. /// </summary> public partial class CommandResultsView : UserControl { /// <summary> /// Initializes a new instance of the CommandResultsView class. /// </summary> public CommandResultsView() { if (ViewModelBase.IsInDesignModeStatic) { ViewModelLocatorHelper.CreateStaticViewModelLocatorForDesigner(this, new ViewModelLocator()); } InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using MongoDB.Bson.Serialization.IdGenerators; namespace C9Native { /// <summary> /// Construct from a privilege name or LUID and provide all information about it. /// </summary> public class PrivilegeInformation { private LUID _luid; /// <summary> /// Return the LUID that identifies this privilege. /// </summary> public LUID luid => _luid; private string _name; /// <summary> /// Return the formal name of this privilege. /// </summary> public string name => _name; private string _display; /// <summary> /// Return the human readable description of this privilege. /// </summary> public string display => _display; /// <summary> /// Given the name of a privilege, construct an object with all information we might need about it. /// </summary> /// <param name="privilegename">Name of the privilege.</param> public PrivilegeInformation(string privilegename) { _name = privilegename; _luid = NameToLuid(privilegename); _display = NameToDisplayName(privilegename); } /// <summary> /// Given the LUID for a privilege construct an object with all the information we might need. /// </summary> /// <param name="luid">LUID for the privilege we're interested in.</param> public PrivilegeInformation(LUID luid) { _luid = luid; _name = LuidToName(luid); if (_name != null) { _display = NameToDisplayName(_name); } } /// <summary> /// Return a full human readable description of this privilege. /// </summary> /// <returns></returns> public string Describe() { return $"{_name} -> {_display} ({_luid.HighPart}/{_luid.LowPart})"; } public static LUID NameToLuid(string name) { var result = new LUID(); [DllImport("advapi32.dll")] static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid); bool getok = LookupPrivilegeValue(null, name, ref result); if (!getok) { return result; } return result; } /// <summary> /// Given a privilege name, return the human readable display name for that privilege. /// </summary> /// <param name="name">Name of the privilege we're interested in.</param> /// <returns>Human readable string that describes the provided privilege name.</returns> public static string NameToDisplayName(string name) { string result = null; [DllImport("advapi32.dll", SetLastError = true)] static extern bool LookupPrivilegeDisplayName( string systemName, string privilegeName, //in System.Text.StringBuilder displayName, // out ref uint cbDisplayName, out uint languageId ); uint length = 0; uint language; bool lenok = LookupPrivilegeDisplayName(null, name, null, ref length, out language); if (length > 0) { var builder = new StringBuilder(); builder.EnsureCapacity((int)length); bool getok = LookupPrivilegeDisplayName(null, name, builder, ref length, out language); if (getok) { result = builder.ToString(); } } return result; } /// <summary> /// Given an LUID return the string name for that LUID. /// </summary> /// <param name="luid">LUID that we want the name of.</param> /// <returns>Name of the LUID provided as a privilege.</returns> public static string LuidToName(LUID luid) { string result = null; [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool LookupPrivilegeName( string lpSystemName, IntPtr lpLuid, System.Text.StringBuilder lpName, ref int cchName); IntPtr ptrLuid = Marshal.AllocHGlobal(Marshal.SizeOf(luid)); Marshal.StructureToPtr(luid, ptrLuid, true); try { int namelength = 0; bool lenok = LookupPrivilegeName(null, ptrLuid, null, ref namelength); if (namelength > 0) { var builder = new StringBuilder(); builder.EnsureCapacity(namelength + 1); bool getok = LookupPrivilegeName(null, ptrLuid, builder, ref namelength); if (getok) { result = builder.ToString(); } } } finally { Marshal.FreeHGlobal(ptrLuid); } return result; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Emgu.CV; using Emgu.CV.Structure; using Emgu.Util; namespace RGBonClick { public partial class Form1 : Form { Capture _capture = null; Image<Bgr, Byte> color_img = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { _capture = new Capture(); _capture.ImageGrabbed += _capture_ImageGrabbed; _capture.Start(); imageBox1.MouseClick += new MouseEventHandler(imageBox1_MouseClick); } void imageBox1_MouseClick(object sender, MouseEventArgs e) { red_lbl.Text = color_img[e.Location.Y, e.Location.X].Red.ToString(); green_lbl.Text = color_img[e.Location.Y, e.Location.X].Green.ToString(); blue_lbl.Text = color_img[e.Location.Y, e.Location.X].Blue.ToString(); } void _capture_ImageGrabbed(object sender, EventArgs e) { color_img = _capture.RetrieveBgrFrame().Resize(imageBox1.Width, imageBox1.Height, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR); imageBox1.Image = color_img; } protected override void OnClosing(CancelEventArgs e) { _capture.Stop(); base.OnClosing(e); } } }
using HBPonto.Kernel.Enums; using HBPonto.Kernel.Helpers; using HBPonto.Kernel.Interfaces.Authentication; using HBPonto.Kernel.Interfaces.DTOs; using HBPonto.Kernel.Interfaces.Repositories; using HBPonto.Kernel.Interfaces.Services; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using System; using System.IdentityModel.Tokens.Jwt; using System.Net.Http; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using static HBPonto.Authentication.DTOs.AuthUserDTO; using static HBPonto.Database.Entities.User; namespace HBPonto.Authentication.Services { public class AuthenticationService : IAuthenticationService { private readonly AppSettings _appSettings; private IJiraBaseService _jiraBaseService; private IUserRepository _userRepository; public AuthenticationService(IOptions<AppSettings> appSettings, IJiraBaseService jiraBaseService, IUserRepository userRepository) { _appSettings = appSettings.Value; _jiraBaseService = jiraBaseService; _userRepository = userRepository; } public IAuthUserDTO CreateUser(string userName, string authJiraToken, string token, string userId) { return AuthUserDTOFactory.Create(userName, authJiraToken, token, userId); } public async Task<(HttpResponseMessage, string)> AuthorizationUser(AuthUser authUser) { var authentication = _jiraBaseService.GetAuthenticationString(authUser.username, authUser.password); HttpClient client = _jiraBaseService.GetHttpClient(authentication); var url = $"/rest/auth/1/session"; var stringContent = new StringContent(JsonConvert.SerializeObject(authUser), Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, stringContent); return (response, authentication); } public async Task<HttpResponseMessage> AuthorizeCurrentUser() { HttpClient client = _jiraBaseService.GetHttpClient(_appSettings.AuthJiraToken); var url = $"/rest/auth/1/session"; return await client.GetAsync(url); } public (string, string) GenerateToken(AuthUser authUser) { //Método busca um usuário no banco se não encontrar então insere um novo usuário e retorna o usuário inserido //por isso a geração do token deve ser feita depois de consultar no jira se usuário existe e depois de manipular o erro var user = _userRepository.GetUserByName(authUser.username) ?? _userRepository.InsertNewUser(UserFactory.Create(authUser.username, RoleEnum.NOT_ATTRIBUTED.Value)); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, user.Role ?? string.Empty) }), Expires = DateTime.UtcNow.AddYears(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return (tokenHandler.WriteToken(token), user.Id); } } }
using System; using System.Collections.Generic; using System.Windows.Input; using Slayer.ViewModels; namespace Slayer.DesignTimeData { public class MockLoadViewModel : BaseViewModel, ILoadViewModel { public MockLoadViewModel() { } public ICommand LoadCommand { get; private set; } public ICommand CancelLoadCharCommand { get; set; } public IList<string> Files { get { return new List<string>{"file 1", "file 2", "file 3"};} set { throw new NotImplementedException();} } public string SelectedFile { get { return Files[0]; } set { throw new NotImplementedException();} } } }
 using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class LevelManager : MonoBehaviour { //position of the first floor public float InitialFloorPosition; //space between floors public float FloorSpace; //graphic floor public GameObject FloorModel; //how many floors are on the game public int FloorsAmount; //created floors GameObject[] floors; //graphic hole public Holes HoleModel; //how many holes are on the game public int HolesAmount; //created holes Holes[] holes; //currnet hole being used int currentHole; //folder to agrupate enemies public Transform EnemiesParent; //graphic enemy public Enemy EnemyModel; //created enemies Enemy[] enemies; //speed of the game, as many entities use the same speed this is handle by the game manager public float OverallSpeed; //event to change the speed to all entities using it public static event UnityAction<float> SpeedChange; //game stats static int currentLevel; static int score; static int hiScore; const int scoreBase = 5; //references to external entities public LevelData LevelDatabase; HUDManager hud; Player player; //helper to prevent enemies created over enemies struct EnemyPos { public int Floor; public int XPos; } private void Start () { //create game necessary elements CreateFloors(); CreateHoles(); CreateEnemies(); //get player reference player = FindObjectOfType<Player>(); //get ui reference and update it hud = FindObjectOfType<HUDManager>(); hud.UpdateScore(score); hud.SetHiScore(hiScore); hud.SetEnemies(currentLevel); //set speed if(SpeedChange != null) SpeedChange(OverallSpeed); //shuffle enemies models if(currentLevel == 0) LevelDatabase.EnemyModels.Shuffle(); } //cancel all subscription to the event private void OnDestroy () { SpeedChange = null; } void CreateFloors () { Vector3 floorPosition = Vector3.zero; floorPosition.y = InitialFloorPosition; floors = new GameObject[FloorsAmount]; floors[0] = FloorModel; floors[0].transform.position = floorPosition; for(int i = 1; i < FloorsAmount; i++) { floors[i] = Instantiate(FloorModel); floors[i].transform.SetParent(FloorModel.transform.parent); floorPosition.y += FloorSpace; floors[i].transform.position = floorPosition; floors[i].name = "Floor " + i; } } void CreateHoles () { holes = new Holes[HolesAmount]; holes[0] = HoleModel; for(int i = 1; i < HolesAmount; i++) { holes[i] = Instantiate(HoleModel); holes[i].transform.SetParent(HoleModel.transform.parent); holes[i].transform.position = Vector3.up * -10; holes[i].name = "Hole " + i; } SetHole(1); SetHole(-1); } //when score is added adds a new hole and update the gui public void AddScore () { SetHole(); score += scoreBase + (scoreBase * currentLevel); hud.UpdateScore(score); } //add holes to the level... public void SetHole (int d = 0) { if(currentHole == HolesAmount)//... if the limit is not yet reached return; //only create holes in clean floors int f; bool repeatedLine; do { f = Random.Range(0, 8); repeatedLine = false; for(int i = 0; i < holes.Length; i++) { if(holes[i].CurrentFloor == f) repeatedLine = true; } } while(repeatedLine); //if "d" comes with value different to zero its used as fixed direction, //if not then the first 3 holes goes right and the other 3 go left if(d == 0) { if(currentHole < 5) d = 1; else d = -1; } holes[currentHole].Set(f, new Vector3(Random.Range(-7, 7), InitialFloorPosition + f * FloorSpace, 0), d, InitialFloorPosition, FloorSpace, FloorsAmount); currentHole++; } void CreateEnemies () { LevelDatabase.ResetEnemyIndex(); int enemiesAmount = currentLevel; enemies = new Enemy[enemiesAmount]; //check that there is no enemy being instantiated over other enemy EnemyPos currentPos = new EnemyPos();//position assigned to a new enemy List<EnemyPos> ep = new List<EnemyPos>();//record of previously created enemies bool repeated = false; for(int i = 0; i < enemiesAmount; i++) { enemies[i] = Instantiate(EnemyModel); enemies[i].transform.SetParent(EnemiesParent); do { repeated = false; currentPos.Floor = Random.Range(0, FloorsAmount); currentPos.XPos= Random.Range(-7, 7); for(int j = 0; j < ep.Count; j++) { if(currentPos.Floor == ep[j].Floor && currentPos.XPos == ep[j].XPos) repeated = true; } } while(repeated); ep.Add(currentPos); enemies[i].Set(currentPos.Floor, currentPos.XPos, LevelDatabase.GetEnemyModel(), InitialFloorPosition, FloorSpace, FloorsAmount); } } public void Win () { //game speed is set to zero if(SpeedChange != null) SpeedChange(0); currentLevel++; //if this is the last level, dont seek next level info if(currentLevel >= LevelDatabase.Levels.Length) hud.ShowNextLevel(LevelDatabase.Levels[currentLevel - 1].FinishMessage, -1, LevelDatabase.Levels[currentLevel - 1].ExtraLife); else hud.ShowNextLevel(LevelDatabase.Levels[currentLevel - 1].FinishMessage, currentLevel, LevelDatabase.Levels[currentLevel - 1].ExtraLife); //if level has a life give it to the player if(LevelDatabase.Levels[currentLevel - 1].ExtraLife) player.AddLife(); } public void GameOver () { //game speed is set to zero if(SpeedChange != null) SpeedChange(0); if(currentLevel >= LevelDatabase.Levels.Length) currentLevel = LevelDatabase.Levels.Length - 1; hud.ShowGameOver(score, score > hiScore, currentLevel); if(score > hiScore) { hiScore = score; hud.SetHiScore(hiScore); } //restart info currentLevel = 0; score = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using KartLib; namespace KartSystem { public class MeasuresPresenter:BasePresenter { IMesuresView _view; public MeasuresPresenter(IMesuresView view) { _view = view; } public override void ViewLoad() { base.ViewLoad(); if (_view != null) { _view.Measuries = KartDataDictionary.sMeasures= Loader.DbLoad<Measure>(""); } } } }
// René DEVICHI 2011 using System; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.IO; using EARTHLib; namespace GETagging { public partial class Form1 : Form { static string GEFolderName = "My Tagging"; ApplicationGE earth = null; Coordinate Latitude, Longitude; public Form1() { InitializeComponent(); } private void trace(string format, params object[] args) { listBox1.Items.Add(string.Format(format, args)); } private void button4_Click(object sender, EventArgs e) { // reset the COM object if connection has been broken since the first call // (i.e. GE has been closed) if (earth != null) { try { earth.IsInitialized(); } catch (Exception /*e*/) { earth = null; } } if (earth == null) { // establish the COM connection with Google Earth try { earth = new EARTHLib.ApplicationGE(); } catch (Exception /*e*/) { return; } } try { int n = 0; while (earth.IsInitialized() == 0) { System.Threading.Thread.Sleep(100); // wait 10s if (++n >= 100) { throw new Exception("Google Earth is not available"); } } //trace("IsInitialized={0} VersionAppType={1} IsOnline={2}", earth.IsInitialized(), earth.VersionAppType, earth.IsOnline()); } catch(Exception /*e*/) { earth = null; return; } // create a KML to display the crosshairs at the center of GE screen string s = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <kml xmlns=""http://earth.google.com/kml/2.0""> <Folder> <name>{0}</name> <ScreenOverlay> <name>Target</name> <Icon> <href>{1}</href> </Icon> <overlayXY x=""0.500000"" y=""0.500000"" xunits=""fraction"" yunits=""fraction"" /> <screenXY x=""0.500000"" y=""0.500000"" xunits=""fraction"" yunits=""fraction"" /> <size x=""0"" y=""0"" xunits=""pixels"" yunits=""pixels"" /> </ScreenOverlay> <!--LookAt> <longitude>-1.440113</longitude> <latitude>43.653903</latitude> <range>250</range> <tilt>0.000000</tilt> <heading>0.000000</heading> </LookAt--> </Folder> </kml>", GEFolderName, Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "xhairs.png")); string kml = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()) + ".kml"; //trace("kml {0}", kml); // Creates a file for writing UTF-8 encoded text using (StreamWriter sw = File.CreateText(kml)) { sw.Write(s); } earth.OpenKmlFile(kml, 1); // picasa does it, I'm not sure it's necessary try { foreach (FeatureGE f in earth.GetTemporaryPlaces().GetChildren()) { if (f.Name == GEFolderName) { f.Highlight(); break; } } } catch (Exception /*e*/) { } // try { Form2 geotag = new Form2(earth.GetMainHwnd()); DialogResult result = geotag.ShowDialog(this); if (result == DialogResult.OK) { // retrieve the position //CameraInfoGE ci = earth.GetCamera(1); //trace("CameraInfo {0:.######} {1:.######} {2} {3}", ci.FocusPointLatitude, ci.FocusPointLongitude, ci.FocusPointAltitude, ci.FocusPointAltitudeMode); // better: GetCamera doesn't return the Altitude PointOnTerrainGE pot = earth.GetPointOnTerrainFromScreenCoords(0, 0); trace("PointOnTerrain {0:.######} {1:.######} {2:.}", pot.Latitude, pot.Longitude, pot.Altitude); Latitude = new Coordinate(pot.Latitude, CoordinatesPosition.N); Longitude = new Coordinate(pot.Longitude, CoordinatesPosition.E); textBox1.Text = Latitude.ToString(); textBox2.Text = Longitude.ToString(); textBox3.Text = string.Format("{0:.} m", pot.Altitude); } else { trace("cancelled: {0}", result); } } catch (Exception /*e*/) { } // clear the temporary place 'GEFolderName' try { using (StreamWriter sw = File.CreateText(kml)) { sw.Write(@"<kml/>"); } earth.OpenKmlFile(kml, 1); File.Delete(kml); } catch (Exception /*e*/) { } // bring us to the front this.Activate(); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using iTextSharp.text; using iTextSharp.text.pdf; using LimenawebApp.Controllers.API; using LimenawebApp.Controllers.Operations; using LimenawebApp.Controllers.Session; using LimenawebApp.Models; using LimenawebApp.Models.Invoices; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Data.Entity; using System.Globalization; using System.IO; using System.Linq; using System.Transactions; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using static LimenawebApp.Models.Operations.Mdl_planning; namespace LimenawebApp.Controllers { public class InvoicesController : Controller { private dbLimenaEntities dblim = new dbLimenaEntities(); private DLI_PROEntities dlipro = new DLI_PROEntities(); private Cls_session cls_session = new Cls_session(); private Cls_Frezzers cls_Frezzers = new Cls_Frezzers(); private Cls_planning cls_planning = new Cls_planning(); private cls_invoices cls_invoices = new cls_invoices(); //CLASS GENERAL private clsGeneral generalClass = new clsGeneral(); // GET: Invoices public class orderSO { public int sort { get; set; } public int num { get; set; } public string SO { get; set; } public string comment { get; set; } } public ActionResult Planning_order(int id) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Planning"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //Session["opensalesOrders"] = (from obj in dlipro.OpenSalesOrders select new OpenSO{ NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToList(); var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } var orders = (from a in dblim.Tb_PlanningSO where (a.ID_Route == id && a.Warehouse==company_bodega) select a).OrderBy(a => a.query3).ToList(); //FIN HEADER DateTime filterdate = DateTime.Today.AddDays(-31); var lstOpenSales = (from obj in dlipro.OpenSalesOrders where (obj.SODate > filterdate && obj.WareHouse==company_bodega) select new OpenSO { NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToList(); ViewBag.opensalesOrders = lstOpenSales; ViewBag.id_route = id; List<Invoices_api> invoices = new List<Invoices_api>(); var apiinvoices = cls_invoices.GetInvoices("", "", "",8,false, null, null, false); if (apiinvoices != null) { if (apiinvoices.data != null && apiinvoices.data.Count > 0) { invoices = apiinvoices.data; } } ViewBag.invoices = invoices; return View(orders); } else { return RedirectToAction("Login", "Home", new { access = false }); } } private List<DateTime> GetDateRange(DateTime StartingDate, DateTime EndingDate) { if (StartingDate > EndingDate) { return null; } List<DateTime> rv = new List<DateTime>(); DateTime tmpDate = StartingDate; do { rv.Add(tmpDate); tmpDate = tmpDate.AddDays(1); } while (tmpDate <= EndingDate); return rv; } public ActionResult Planning(string whssel,string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Planning"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //FILTROS VARIABLES DateTime filtrostartdate; DateTime filtroenddate; ////filtros de fecha (SEMANAL 2 semanas por la planeacion de Viernes a Lunes) var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); var saturday = sunday.AddDays(13).AddHours(23); //filtros de fecha //MENSUAL //var sunday = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); //var saturday = sunday.AddMonths(1).AddDays(-1); if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); //////// var company_bodega = "0"; if (whssel == null || whssel == "") { if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } } else { company_bodega = whssel; } /////////////////////////////// //List<Tb_Planning> rutaslst = new List<Tb_Planning>(); //Nuevo filtro por bodega List<Routes_calendarPlanning> rutas = new List<Routes_calendarPlanning>(); //si es limena podremos ver las rutas de otras pero minimizadas //if (company_bodega == "01") //{ rutas = cls_planning.GetRoutes(company_bodega, filtrostartdate, filtroenddate); //rutaslst = (from a in dblim.Tb_Planning where (a.Departure >= filtrostartdate && a.Departure <= filtroenddate && a.Warehouse == company_bodega) select a).ToList(); ////verificamos si hay rutas maestras deKY //foreach (DateTime date in GetDateRange(filtrostartdate, filtroenddate)) //{ // var date23h = date.AddHours(23); // var existeMasterRoute= (from a in dblim.Tb_Planning where ((a.Departure >= date && a.Departure <=date23h) && a.Warehouse != company_bodega) select a).Take(1).ToList(); // if (existeMasterRoute.Count > 0) { // rutaslst.AddRange(existeMasterRoute); // } //} //// //} //else { // rutaslst = (from a in dblim.Tb_Planning where (a.Departure >= filtrostartdate && a.Departure <= filtroenddate && a.Warehouse == company_bodega) select a).ToList(); //} //var rtids = rutaslst.Select(c => c.ID_Route).ToArray(); ////Cargamos todos los datos maestros a utilizar ////Nuevo filtro por bodega //var solist = (from j in dblim.Tb_PlanningSO where (rtids.Contains(j.ID_Route)) select new { IDinterno = j.ID_salesorder, SAPDOC = j.SAP_docnum, IDRoute=j.ID_Route, amount=j.Amount, customerName=j.Customer_name }).ToList(); //var solMaestro = solist.Select(c => c.IDinterno).ToArray(); ////Nuevo filtro por bodega(AQUI NO APLICAR) //var detallesMaestroSo = (from f in dblim.Tb_PlanningSO_details where (solMaestro.Contains(f.ID_salesorder)) select f).ToList(); //foreach (var item in rutaslst) //{ // Routes_calendar rt = new Routes_calendar(); // rt.title = item.ID_Route + " - " + item.Route_name; // rt.url = ""; // rt.start = item.Departure.ToString("yyyy-MM-dd"); // //rt.end = item.Departure.AddDays(1).ToString("yyyy-MM-dd"); // rt.route_leader = item.Routeleader_name.ToUpper(); // rt.className = ".fc-event"; // rt.driver = item.Driver_name.ToUpper(); // rt.driver_WHS = item.Driver_name_whs.ToUpper(); // rt.truck = item.Truck_name; // rt.truck_WHS = item.Truck_name_whs; // rt.departure = item.Departure.ToShortTimeString(); // rt.Warehouse = item.Warehouse; // try { // var extra = (from a in dblim.Tb_Planning_extra where (a.ID_Route == item.ID_Route) select a); // if (extra.Count() > 0) { // rt.extra = extra.Sum(x => x.Value).ToString(); // } // else // { // rt.extra = "0.00"; // } // } // catch { // rt.extra = "0.00"; // } // //INFO UOM // var listafinalSO = solist.Where(c => c.IDRoute == item.ID_Route).ToList(); // var sol = listafinalSO.Select(c => c.IDinterno).ToArray(); // //Verificamos detalles para sacar CASE y EACH totales y luego promediar todal de EACH en base a CASES // var detallesSo = (from f in detallesMaestroSo where (sol.Contains(f.ID_salesorder)) select f).ToList(); // var totalCantEach = 0; // var totalCantCases = 0; // var totalCantPack = 0; // var totalCantLbs = 0; // decimal promedioEachxCases = 0; // //Para calcular el promedio lo hacemos diviendo // try // { // if (detallesSo.Count() > 0) // { // totalCantEach = detallesSo.Where(c => c.UomCode.Contains("EACH")).Count(); // totalCantCases = detallesSo.Where(c => c.UomCode.Contains("CASE")).Count(); // totalCantPack = detallesSo.Where(c => c.UomCode.Contains("PACK")).Count(); // totalCantLbs = detallesSo.Where(c => c.UomCode.Contains("LBS")).Count(); // foreach (var soitem in listafinalSO) // { // //devolvemos ID externo // var docnum = Convert.ToInt32(soitem.SAPDOC); // //Devolvemos todos los detalles(itemcode) de esa SO // var itemscode = detallesSo.Where(c => c.ID_salesorder == soitem.IDinterno).Select(c => c.ItemCode).ToArray(); // //Buscamos en la vista creada 9/24/2019 // var sumatotal = dlipro.PlanningUoMInfo.Where(a => itemscode.Contains(a.ItemCode) && a.DocNum == docnum && a.Quantity >0 && !a.unitMsr.Contains("LBS")).Sum(c => c.TotalCases); // if (sumatotal > 0 && sumatotal != null) // { // promedioEachxCases += Convert.ToDecimal(sumatotal); // } // } // } // else // { // totalCantEach = 0; // totalCantCases = 0; // totalCantPack = 0; // totalCantLbs = 0; // promedioEachxCases = 0; // } // } // catch // { // totalCantEach = 0; // totalCantCases = 0; // totalCantPack = 0; // totalCantLbs = 0; // promedioEachxCases = 0; // } // /// // rt.totalEach = totalCantEach.ToString(); // rt.totalCase = totalCantCases.ToString(); // rt.totalPack = totalCantPack.ToString(); // rt.totalLbs = totalCantLbs.ToString(); // rt.AVGEach = promedioEachxCases.ToString(); // if (item.isfinished == true) { rt.isfinished = "Y"; } else { rt.isfinished = "N"; } // var sum = (from e in solist where (e.IDRoute == item.ID_Route) select e); // if (sum != null) // { // try // { // rt.amount = sum.Select(c => c.amount).Sum().ToString(); // } // catch { // rt.amount = "0.0"; // } // rt.customerscount = sum.Select(c => c.customerName).Distinct().Count().ToString(); // rt.orderscount = sum.Count().ToString(); // } // else // { // rt.amount = "0.0"; // rt.customerscount = ""; // rt.orderscount = ""; // } // rutas.Add(rt); //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(rutas.ToArray()); ViewBag.calroutes = result; /// //SELECTS var drivers = dlipro.C_DRIVERS.Where(a=>a.U_Whs==company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListDrivers = new ArrayList(); myArrListDrivers.AddRange((from p in drivers select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.drivers = JsonConvert.SerializeObject(myArrListDrivers); //DRIVERS OTRAS BODEGAS var driversOTROS = dlipro.C_DRIVERS.Where(a => a.U_Whs != company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListDriversOTROS = new ArrayList(); myArrListDriversOTROS.AddRange((from p in driversOTROS select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.driversOtros = JsonConvert.SerializeObject(myArrListDriversOTROS); //LISTADO DE Routes Leader var routeleader = dlipro.C_HELPERS.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListrouteleader = new ArrayList(); myArrListrouteleader.AddRange((from p in routeleader select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.routeleaders = JsonConvert.SerializeObject(myArrListrouteleader); //LISTADO DE Trucks var trucks = dlipro.C_TRUCKS.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListtruck = new ArrayList(); myArrListtruck.AddRange((from p in trucks select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.trucks = JsonConvert.SerializeObject(myArrListtruck); var trucksOTRASBODEGAS = dlipro.C_TRUCKS.Where(a => a.U_Whs != company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListtruckOTRAS = new ArrayList(); myArrListtruckOTRAS.AddRange((from p in trucksOTRASBODEGAS select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.trucksOtros = JsonConvert.SerializeObject(myArrListtruckOTRAS); //LISTADO DE Rutas var mainroutes = dlipro.C_DROUTE.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListmainroutes = new ArrayList(); myArrListmainroutes.AddRange((from p in mainroutes select new { id = p.Code, text = p.Name }).ToList()); ViewBag.mainroutes = JsonConvert.SerializeObject(myArrListmainroutes); //Session["opensalesOrders"] = (from obj in dlipro.OpenSalesOrders select new OpenSO{ NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToList(); ViewBag.warehousesel = company_bodega; //FIN HEADER return View(); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public ActionResult PlanningRoutes(string whssel, string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Planning"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //FILTROS VARIABLES DateTime filtrostartdate; DateTime filtroenddate; ////filtros de fecha (SEMANAL 2 semanas por la planeacion de Viernes a Lunes) var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); var saturday = sunday.AddDays(13).AddHours(23); //filtros de fecha //MENSUAL //var sunday = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); //var saturday = sunday.AddMonths(1).AddDays(-1); if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); //////// var company_bodega = "0"; if (whssel == null || whssel == "") { if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } } else { company_bodega = whssel; } /////////////////////////////// //List<Tb_Planning> rutaslst = new List<Tb_Planning>(); //Nuevo filtro por bodega List<Routes_calendarPlanning> rutas = new List<Routes_calendarPlanning>(); rutas = cls_planning.GetRoutes(company_bodega, filtrostartdate, filtroenddate); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(rutas.ToArray()); ViewBag.calroutes = result; /// //SELECTS var drivers = dlipro.C_DRIVERS.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListDrivers = new ArrayList(); myArrListDrivers.AddRange((from p in drivers select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.drivers = JsonConvert.SerializeObject(myArrListDrivers); //DRIVERS OTRAS BODEGAS var driversOTROS = dlipro.C_DRIVERS.Where(a => a.U_Whs != company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListDriversOTROS = new ArrayList(); myArrListDriversOTROS.AddRange((from p in driversOTROS select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.driversOtros = JsonConvert.SerializeObject(myArrListDriversOTROS); //LISTADO DE Routes Leader var routeleader = dlipro.C_HELPERS.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListrouteleader = new ArrayList(); myArrListrouteleader.AddRange((from p in routeleader select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.routeleaders = JsonConvert.SerializeObject(myArrListrouteleader); //LISTADO DE Trucks var trucks = dlipro.C_TRUCKS.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListtruck = new ArrayList(); myArrListtruck.AddRange((from p in trucks select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.trucks = JsonConvert.SerializeObject(myArrListtruck); var trucksOTRASBODEGAS = dlipro.C_TRUCKS.Where(a => a.U_Whs != company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListtruckOTRAS = new ArrayList(); myArrListtruckOTRAS.AddRange((from p in trucksOTRASBODEGAS select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.trucksOtros = JsonConvert.SerializeObject(myArrListtruckOTRAS); //LISTADO DE Rutas var mainroutes = dlipro.C_DROUTE.Where(a => a.U_Whs == company_bodega).ToList(); //Convertimos la lista a array ArrayList myArrListmainroutes = new ArrayList(); myArrListmainroutes.AddRange((from p in mainroutes select new { id = p.Code, text = p.Name }).ToList()); ViewBag.mainroutes = JsonConvert.SerializeObject(myArrListmainroutes); //Session["opensalesOrders"] = (from obj in dlipro.OpenSalesOrders select new OpenSO{ NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToList(); ViewBag.warehousesel = company_bodega; //FIN HEADER return View(); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public class OpenSO { public int NumSO { get; set; } public string CardCode { get; set; } public string CustomerName { get; set; } public string DeliveryRoute { get; set; } public string SalesPerson { get; set; } public DateTime? SODate { get; set; } public decimal? TotalSO { get; set; } public decimal? OpenAmount { get; set; } public string Remarks { get; set; } public string Printed { get; set; } } public class MyObj_formtemplate { public string NumSO { get; set; } } public ActionResult Print_OpenSalesOrders(List<MyObj_formtemplate> objects) { try { List<string> list = new List<string>(); foreach (var item in objects) { var idact = item.NumSO.Substring(4); list.Add(idact); } List<Tb_planning_print> lsttosave = new List<Tb_planning_print>(); foreach (var save in list) { var docnum = Convert.ToInt32(save); Tb_planning_print print = new Tb_planning_print(); var order = (from a in dlipro.OpenSalesOrders where (a.NumSO == docnum) select a).FirstOrDefault(); print.IsRoute = false; print.Printed = false; print.Doc_key = save; print.Module = "OpenSalesOrders"; print.Printed_on = DateTime.UtcNow; var hh = 0; var mm = 0; hh = Convert.ToInt32(order.DocTime.ToString().Substring(0, 2)); mm = Convert.ToInt32(order.DocTime.ToString().Substring(2,2)); var datecreate = new DateTime(order.CreateDate.Value.Year, order.CreateDate.Value.Month, order.CreateDate.Value.Day, hh, mm, 0); print.Created_on = datecreate; lsttosave.Add(print); } dblim.BulkInsert(lsttosave); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult OpenSalesOrders(string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Open Sales Orders"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER DateTime filtrostartdate; DateTime filtroenddate; //filtros de fecha //SEMANAL //var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); //var saturday = sunday.AddDays(6).AddHours(23); //filtros de fecha //MENSUAL //var sunday = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); //var saturday = sunday.AddMonths(1).AddDays(-1); //filtros de fecha (DIARIO) //var sunday = DateTime.Today; //var saturday = sunday.AddDays(1); //filtros de fecha (ANUAL) int year = DateTime.Now.Year; var sunday = new DateTime(year, 1, 1); var saturday = new DateTime(year, 12, 31); //FILTROS************** if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } //if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = DateTime.ParseExact(fstartd, "MM/dd/yyyy", CultureInfo.InvariantCulture); } //if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = DateTime.ParseExact(fendd, "MM/dd/yyyy", CultureInfo.InvariantCulture).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); //FIN FILTROS******************* var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } IEnumerable<OpenSalesOrders> SalesOrder; //SalesOrder = (from b in dlipro.OpenSalesOrders select b).Take(10); SalesOrder = (from b in dlipro.OpenSalesOrders where (b.SODate >= filtrostartdate && b.SODate <= filtroenddate) select b); return View(SalesOrder); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public ActionResult Freezers(string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Freezers"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //FILTROS VARIABLES DateTime filtrostartdate; DateTime filtroenddate; ////filtros de fecha (DIARIO) var sunday = DateTime.Today; var saturday = sunday.AddDays(1).AddHours(20); if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); //////// var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } var getfrezzers = (from a in dblim.Tb_logContainers where(a.inRoute==true) select a); return View(getfrezzers); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public ActionResult QualityControl_planning(string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Quality Control"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //FILTROS VARIABLES DateTime filtrostartdate; DateTime filtroenddate; ////filtros de fecha (DIARIO) var sunday = DateTime.Today; var saturday = sunday.AddDays(1).AddHours(20); if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); //////// var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } List<QualityControl_SO> lstPlanning = new List<QualityControl_SO>(); //Verificamos Freezers 07/13/2020 var lstfreezersinroute = (from a in dblim.Tb_logContainers where (a.inRoute == true) select a).ToList(); if (company_bodega == "01") { lstPlanning = (from a in dblim.Tb_Planning where (a.Departure >= filtrostartdate && a.Departure <= filtroenddate) select new QualityControl_SO { ID_Route = a.ID_Route, Route_name = a.Route_name, ID_driver = a.ID_driver, Driver_name = a.Driver_name, ID_routeleader = a.ID_routeleader, Routeleader_name = a.Routeleader_name, ID_truck = a.ID_truck, Truck_name = a.Truck_name, Departure = a.Departure, isfinished = a.isfinished, ID_SAPRoute = a.ID_SAPRoute, query1 = a.query1, query2 = a.query2, query3 = a.query3, query4 = "", query5 = "", query6 = 0, Date = a.Date, Invoiced = a.Invoiced, DateCheckIn = a.DateCheckIn, DateCheckOut = a.DateCheckOut, ID_userValidate = a.ID_userValidate, Warehouse = a.Warehouse, transferred = 0, existendeOtraBodega = 0, freezers = (from y in dblim.Tb_logContainers where (y.ID_Route == a.ID_Route) select new lst_Freezer { id=y.ID_container, name=y.Container }).ToList() }).ToList(); } else { lstPlanning = (from a in dblim.Tb_Planning where (a.Departure >= filtrostartdate && a.Departure <= filtroenddate && a.Warehouse == company_bodega) select new QualityControl_SO { ID_Route = a.ID_Route, Route_name = a.Route_name, ID_driver = a.ID_driver, Driver_name = a.Driver_name, ID_routeleader = a.ID_routeleader, Routeleader_name = a.Routeleader_name, ID_truck = a.ID_truck, Truck_name = a.Truck_name, Departure = a.Departure, isfinished = a.isfinished, ID_SAPRoute = a.ID_SAPRoute, query1 = a.query1, query2 = a.query2, query3 = a.query3, query4 = "", query5 = "", query6 = 0, Date = a.Date, Invoiced = a.Invoiced, DateCheckIn = a.DateCheckIn, DateCheckOut = a.DateCheckOut, ID_userValidate = a.ID_userValidate, Warehouse = a.Warehouse, transferred = 0, existendeOtraBodega = 0, freezers = (from y in dblim.Tb_logContainers where (y.ID_Route == a.ID_Route) select new lst_Freezer { id = y.ID_container, name = y.Container }).ToList() }).ToList(); } var ArrayPlanning = lstPlanning.Select(a => a.ID_Route).ToArray(); List<Tb_PlanningSO> SalesOrder = new List<Tb_PlanningSO>(); SalesOrder = (from b in dblim.Tb_PlanningSO where (ArrayPlanning.Contains(b.ID_Route)) select b).ToList(); //SalesOrder = (from b in dblim.Tb_PlanningSO where (ArrayPlanning.Contains(b.ID_Route)) select b).ToList(); //ESTADISTICA DE RUTAS POR ESTADO DE VISITAS decimal totalRutas = lstPlanning.Count(); decimal totalRutas_bodega = lstPlanning.Count(); foreach (var rutait in lstPlanning) { var arrso = SalesOrder.Where(c => c.ID_Route == rutait.ID_Route).Select(c => c.ID_salesorder).ToArray(); var count = SalesOrder.Where(c => c.ID_Route == rutait.ID_Route).Select(c => c).Count(); var allvalidated = (from f in SalesOrder where (f.isfinished == true && f.ID_Route == rutait.ID_Route) select f).Count(); //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && e.isvalidated == true && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.QC_count == e.QC_totalCount) select e).Count(); //DATOS EN OTRA BODEGA decimal finishedorCanceled_bodega = 0; var existendeOtraBodega = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.QC_count != e.QC_totalCount && e.Warehouse != company_bodega) select e).Count(); ViewBag.existendeOtraBodega = existendeOtraBodega; rutait.existendeOtraBodega = existendeOtraBodega; var existemibodega = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && !e.type.Contains("I") && e.Warehouse == company_bodega) select e).Count(); if (company_bodega == "01") { finishedorCanceled_bodega = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && e.isvalidated == true && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.Warehouse == company_bodega && e.QC_totalCount != e.QC_count) select e).Count(); } else { finishedorCanceled_bodega = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && e.isvalidated == true && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.Warehouse != company_bodega && e.QC_totalCount != e.QC_count) select e).Count(); } int trans = 0; //sabes si ya estan transferidas if (company_bodega == "01") { trans = SalesOrder.Where(a => a.Warehouse != company_bodega && a.Transferred == 1 && a.ID_Route == rutait.ID_Route).Count(); if (trans > 0) { rutait.transferred = 1; } trans = 0; trans = SalesOrder.Where(a => a.Warehouse != company_bodega && a.Transferred == 2 && a.ID_Route == rutait.ID_Route).Count(); if (trans > 0) { rutait.transferred = 2; } } totalRutas = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.QC_count == e.QC_totalCount) select e).Count(); if (company_bodega == "01") { totalRutas_bodega = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.Warehouse == company_bodega && e.QC_totalCount != e.QC_count) select e).Count(); } else { totalRutas_bodega = (from e in dblim.Tb_PlanningSO_details where (arrso.Contains(e.ID_salesorder) && !e.query1.Contains("DEL") && e.Quantity > 0 && !e.type.Contains("I") && e.Warehouse != company_bodega && e.QC_totalCount != e.QC_count) select e).Count(); } if (totalRutas != 0) { if (finishedorCanceled != 0) { rutait.query1 = (((Convert.ToDecimal(finishedorCanceled) / totalRutas) * 100)).ToString(); } else { rutait.query1 = (Convert.ToDecimal(0)).ToString(); } rutait.query2 = "(" + finishedorCanceled + " / " + totalRutas + ")"; } else { rutait.query1 = "0"; rutait.query2 = "(0 / 0)"; } if (totalRutas_bodega != 0) { if (finishedorCanceled_bodega != 0) { rutait.query4 = (((Convert.ToDecimal(finishedorCanceled_bodega) / totalRutas_bodega) * 100)).ToString(); } else { rutait.query4 = (Convert.ToDecimal(0)).ToString(); } rutait.query5 = "(" + finishedorCanceled_bodega + " / " + totalRutas_bodega + ")"; if (company_bodega == "01") { rutait.query6 = existemibodega; } else { rutait.query6 = totalRutas_bodega; } } else { rutait.query4 = "0"; rutait.query5 = "(0 / 0)"; if (company_bodega == "01") { rutait.query6 = existemibodega; } else { rutait.query6 = 0; } } if (count == allvalidated && totalRutas_bodega == 0) { rutait.query3 = 1; } } //Verificamos si rutas estan finalizadas en bodega distinta(eliminado) //Se verificara si todas las rutas cumplen el porcentaje de finalizacion var mostrarbilloflading = 0; var rutas = ""; if (company_bodega == "01") { var lstotrabod = lstPlanning.Where(a => a.Warehouse != company_bodega && a.transferred == 0).ToList(); rutas = String.Join(",", lstotrabod.Select(o => o.ID_Route.ToString()).ToArray()); foreach (var subruta in lstotrabod) { mostrarbilloflading = 0; if (Convert.ToDecimal(subruta.query4) >= 100) { mostrarbilloflading = 1; } } } ViewBag.rutasids = rutas; ViewBag.mostrarBOF = mostrarbilloflading; //ViewBag.lstPlanning = lstPlanning; ViewBag.company = company_bodega; //Routes //Convertimos la lista a array ArrayList myArrListRoutes = new ArrayList(); myArrListRoutes.AddRange((from p in lstPlanning select new { id = p.ID_Route, text = p.Route_name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.routes = JsonConvert.SerializeObject(myArrListRoutes); //Convertimos la lista a array var getfrezzers = cls_Frezzers.GetFrezzers(); var freezersinroute = lstfreezersinroute.Select(c => c.ID_container).ToArray(); ArrayList myArrListFrezzers = new ArrayList(); if (getfrezzers != null) { if (getfrezzers.data != null) { myArrListFrezzers.AddRange((from p in getfrezzers.data where (!freezersinroute.Contains(p.code)) select new { id = p.code, text = p.name.ToUpper().Replace("'", ""), }).ToList()); } } ViewBag.frezzers = JsonConvert.SerializeObject(myArrListFrezzers); return View(lstPlanning); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public class ConsolidatedChild { public int ID_salesOrder { get; set; } public string ID_storage { get; set; } public string Storage { get; set; } public string data1 { get; set; } public string data2 { get; set; } public string Picker { get; set; } public int delete { get; set; } } public ActionResult Print_route(int id) { try { Tb_planning_print print = new Tb_planning_print(); print.IsRoute = true; print.Printed = false; print.Doc_key = id.ToString(); print.Module = "QualityControl"; dblim.Tb_planning_print.Add(print); dblim.SaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("Error", JsonRequestBehavior.AllowGet); } //return RedirectToAction("QualityControl_planning","Invoices"); } public ActionResult Print_so(int id, int docentry ) { try { Tb_planning_print print = new Tb_planning_print(); var order = (from a in dlipro.OpenSalesOrders where (a.NumSO == docentry) select a).FirstOrDefault(); print.IsRoute = false; print.Printed = false; print.Doc_key = docentry.ToString(); print.Module = "QualityControl"; print.Printed_on = DateTime.UtcNow; var hh = 0; var mm = 0; if (order.DocTime.ToString().Length == 3) { hh = Convert.ToInt32(order.DocTime.ToString().Substring(0)); mm = Convert.ToInt32(order.DocTime.ToString().Substring(1,2)); } else { hh = Convert.ToInt32(order.DocTime.ToString().Substring(0,1)); mm = Convert.ToInt32(order.DocTime.ToString().Substring(2, 3)); } var datecreate = new DateTime(order.CreateDate.Value.Year,order.CreateDate.Value.Month,order.CreateDate.Value.Day, hh,mm,0); print.Created_on = datecreate; dblim.Tb_planning_print.Add(print); dblim.SaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json("Error: " +ex.Message, JsonRequestBehavior.AllowGet); } } public ActionResult QualityControl(int id) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Quality Control"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } List<Tb_PlanningSO> lstSalesOrders = new List<Tb_PlanningSO>(); if (company_bodega == "01") { lstSalesOrders = (from a in dblim.Tb_PlanningSO where (a.ID_Route == id) select a).OrderBy(a => a.Customer_name).ThenBy(a => a.ID_customer).ToList(); } else { lstSalesOrders = (from a in dblim.Tb_PlanningSO where (a.ID_Route == id && a.Warehouse == company_bodega) select a).OrderBy(a => a.Customer_name).ThenBy(a => a.ID_customer).ToList(); } var Arry = lstSalesOrders.Where(a => a.Warehouse == company_bodega).Select(a => a.ID_salesorder).ToArray(); List<Tb_PlanningSO_details> lstDetails = new List<Tb_PlanningSO_details>(); if (company_bodega == "01") { var Arry_Bodega = lstSalesOrders.Where(a => a.Warehouse != company_bodega).Select(a => a.ID_salesorder).ToArray(); lstDetails = (from b in dblim.Tb_PlanningSO_details where (Arry.Contains(b.ID_salesorder) && b.Quantity > 0 && !b.type.Contains("I")) select b).ToList(); var detallesdifbod = (from b in dblim.Tb_PlanningSO_details where (Arry_Bodega.Contains(b.ID_salesorder) && b.Quantity > 0 && !b.type.Contains("I") && b.Warehouse == company_bodega && b.QC_totalCount != b.QC_count) select b).ToList(); if (detallesdifbod.Count > 0) { lstDetails.AddRange(detallesdifbod); } } else { lstDetails = (from b in dblim.Tb_PlanningSO_details where (Arry.Contains(b.ID_salesorder) && b.Quantity > 0 && !b.type.Contains("I") && b.Warehouse == company_bodega) select b).ToList(); } //ESTADISTICA DE SALES ORDERS POR ESTADO DE DETALLES decimal totalRutas = lstDetails.Count(); foreach (var rutait in lstSalesOrders) { //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled = (from e in lstDetails where ((e.isvalidated == true) && e.ID_salesorder == rutait.ID_salesorder && !e.query1.Contains("DEL")) select e).Count(); totalRutas = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesorder && !e.query1.Contains("DEL")) select e).Count(); if (totalRutas != 0) { if (finishedorCanceled != 0) { rutait.query1 = (((Convert.ToDecimal(finishedorCanceled) / totalRutas) * 100)).ToString(); } else { rutait.query1 = (Convert.ToDecimal(0)).ToString(); } rutait.query2 = "(" + finishedorCanceled + " / " + totalRutas + ")"; } else { rutait.query1 = "0"; rutait.query2 = "(0/ 0)"; } } var consolidatedChildren = (from c in lstDetails group c by new { c.ID_salesorder, c.ID_storagetype, c.Storage_type } into gcs select new ConsolidatedChild() { ID_salesOrder = gcs.Key.ID_salesorder, ID_storage = gcs.Key.ID_storagetype, Storage = gcs.Key.Storage_type, data1 = "", data2 = "", Picker = "", delete = 0 }).ToList(); var pickers = dlipro.C_PICKERS.Where(a => a.U_Whs == company_bodega && a.U_Active=="Y").ToList(); //Convertimos la lista a array ArrayList myArrListPickers = new ArrayList(); myArrListPickers.AddRange((from p in pickers select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.pickers = JsonConvert.SerializeObject(myArrListPickers); //ESTADISTICA DE DETALLE STORAGE TYPE EN SALES ORDERS decimal totalDet = consolidatedChildren.Count(); var flag = 0; int salesant = 0; List<ConsolidatedChild> arrytodel = new List<ConsolidatedChild>(); foreach (var rutait in consolidatedChildren) { if (rutait.ID_salesOrder == 302) { var h = 0; } if (salesant != rutait.ID_salesOrder) { flag = 0; } //NUEVO PARA UNIR COOLER Y FREEZER if (rutait.ID_storage == "COOLER" || rutait.ID_storage == "FREEZER") { if (salesant == rutait.ID_salesOrder && flag == 1) { flag = 1; } else { flag = 0; } if (flag == 0) { //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled2 = (from e in lstDetails where ((e.isvalidated == true) && e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER")) select e).Count(); totalRutas = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER")) select e).Count(); if (totalRutas != 0) { if (finishedorCanceled2 != 0) { rutait.data1 = (((Convert.ToDecimal(finishedorCanceled2) / totalRutas) * 100)).ToString(); } else { rutait.data1 = (Convert.ToDecimal(0)).ToString(); } rutait.data2 = "(" + finishedorCanceled2 + " / " + totalRutas + ")"; var dtl = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER")) select e).FirstOrDefault(); if (dtl != null) { rutait.Picker = dtl.Picker_name; } } else { rutait.data1 = "0"; } flag = 1; arrytodel.Add(rutait); } else { flag = 0; } } else { //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled2 = (from e in lstDetails where ((e.isvalidated == true) && e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage) select e).Count(); totalRutas = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage) select e).Count(); if (totalRutas != 0) { if (finishedorCanceled2 != 0) { rutait.data1 = (((Convert.ToDecimal(finishedorCanceled2) / totalRutas) * 100)).ToString(); } else { rutait.data1 = (Convert.ToDecimal(0)).ToString(); } rutait.data2 = "(" + finishedorCanceled2 + " / " + totalRutas + ")"; var dtl = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage) select e).FirstOrDefault(); if (dtl != null) { rutait.Picker = dtl.Picker_name; } } else { rutait.data1 = "0"; } arrytodel.Add(rutait); } salesant = rutait.ID_salesOrder; } ViewBag.lstSO = lstSalesOrders; ViewBag.lstSO_children = arrytodel; return View(); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public ActionResult QualityControl_storagetype(int id) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Operations"; ViewData["Page"] = "Quality Control"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } List<Tb_PlanningSO> lstSalesOrders = new List<Tb_PlanningSO>(); lstSalesOrders = (from a in dblim.Tb_PlanningSO where (a.ID_Route == id && a.QC_count >1) select a).OrderBy(a => a.Customer_name).ThenBy(a => a.ID_customer).ToList(); var Arry = lstSalesOrders.Select(a => a.ID_salesorder).ToArray(); List<Tb_PlanningSO_details> lstDetails = new List<Tb_PlanningSO_details>(); lstDetails = (from b in dblim.Tb_PlanningSO_details where (Arry.Contains(b.ID_salesorder) && b.Quantity > 0 && !b.type.Contains("I") && b.Warehouse != company_bodega) select b).ToList(); //ESTADISTICA DE SALES ORDERS POR ESTADO DE DETALLES decimal totalRutas = lstDetails.Count(); foreach (var rutait in lstSalesOrders) { //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled = (from e in lstDetails where ((e.isvalidated == true) && e.ID_salesorder == rutait.ID_salesorder && !e.query1.Contains("DEL")) select e).Count(); totalRutas = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesorder && !e.query1.Contains("DEL")) select e).Count(); if (totalRutas != 0) { if (finishedorCanceled != 0) { rutait.query1 = (((Convert.ToDecimal(finishedorCanceled) / totalRutas) * 100)).ToString(); } else { rutait.query1 = (Convert.ToDecimal(0)).ToString(); } rutait.query2 = "(" + finishedorCanceled + " / " + totalRutas + ")"; } else { rutait.query1 = "0"; rutait.query2 = "(0/ 0)"; } } var consolidatedChildren = (from c in lstDetails group c by new { c.ID_salesorder, c.ID_storagetype, c.Storage_type } into gcs select new ConsolidatedChild() { ID_salesOrder = gcs.Key.ID_salesorder, ID_storage = gcs.Key.ID_storagetype, Storage = gcs.Key.Storage_type, data1 = "", data2 = "", Picker = "", delete=0 }).ToList(); var pickers = dlipro.C_PICKERS.Where(a => a.U_Whs == company_bodega && a.U_Active == "Y").ToList(); //Convertimos la lista a array ArrayList myArrListPickers = new ArrayList(); myArrListPickers.AddRange((from p in pickers select new { id = p.Code, text = p.Name.ToUpper().Replace("'", ""), }).ToList()); ViewBag.pickers = JsonConvert.SerializeObject(myArrListPickers); //ESTADISTICA DE DETALLE STORAGE TYPE EN SALES ORDERS decimal totalDet = consolidatedChildren.Count(); var flag = 0; int salesant = 0; List<ConsolidatedChild> arrytodel = new List<ConsolidatedChild>(); foreach (var rutait in consolidatedChildren) { if (rutait.ID_salesOrder == 302) { var h = 0; } if (salesant != rutait.ID_salesOrder) { flag = 0; } //NUEVO PARA UNIR COOLER Y FREEZER if (rutait.ID_storage == "COOLER" || rutait.ID_storage == "FREEZER") { if (salesant == rutait.ID_salesOrder && flag == 1) { flag = 1; } else { flag = 0; } if (flag == 0) { //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled2 = (from e in lstDetails where ((e.isvalidated == true) && e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER")) select e).Count(); totalRutas = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER")) select e).Count(); var eliminados = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER") && e.Transferred==2) select e).Count(); if (eliminados > 0) { rutait.delete = 1; } if (totalRutas != 0) { if (finishedorCanceled2 != 0) { rutait.data1 = (((Convert.ToDecimal(finishedorCanceled2) / totalRutas) * 100)).ToString(); } else { rutait.data1 = (Convert.ToDecimal(0)).ToString(); } rutait.data2 = "(" + finishedorCanceled2 + " / " + totalRutas + ")"; var dtl = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && (e.ID_storagetype == "COOLER" || e.ID_storagetype == "FREEZER")) select e).FirstOrDefault(); if (dtl != null) { rutait.Picker = dtl.Picker_nameWHS; } } else { rutait.data1 = "0"; } flag = 1; arrytodel.Add(rutait); } else { flag = 0; } } else { //int finishedorCanceled = (from e in visitas where ((e.ID_visitstate == 4 || e.ID_visitstate==1) && e.ID_route == rutait.ID_route) select e).Count(); decimal finishedorCanceled2 = (from e in lstDetails where ((e.isvalidated == true) && e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage) select e).Count(); totalRutas = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage) select e).Count(); var eliminados = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage && e.Transferred == 2) select e).Count(); if (eliminados > 0) { rutait.delete = 1; } if (totalRutas != 0) { if (finishedorCanceled2 != 0) { rutait.data1 = (((Convert.ToDecimal(finishedorCanceled2) / totalRutas) * 100)).ToString(); } else { rutait.data1 = (Convert.ToDecimal(0)).ToString(); } rutait.data2 = "(" + finishedorCanceled2 + " / " + totalRutas + ")"; var dtl = (from e in lstDetails where (e.ID_salesorder == rutait.ID_salesOrder && !e.query1.Contains("DEL") && e.ID_storagetype == rutait.ID_storage) select e).FirstOrDefault(); if (dtl != null) { rutait.Picker = dtl.Picker_nameWHS; } } else { rutait.data1 = "0"; } arrytodel.Add(rutait); } salesant = rutait.ID_salesOrder; } ViewBag.lstSO = lstSalesOrders; ViewBag.lstSO_children = arrytodel; return View(); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public class RoutesInfo { public int ID_Route { get; set; } public string Route_name { get; set; } public string ID_driver { get; set; } public string Driver_name { get; set; } public string ID_routeleader { get; set; } public string Routeleader_name { get; set; } public string ID_truck { get; set; } public string Truck_name { get; set; } public System.DateTime Departure { get; set; } public bool isfinished { get; set; } public string ID_SAPRoute { get; set; } public string query1 { get; set; } public string query2 { get; set; } public decimal query3 { get; set; } public System.DateTime Date { get; set; } public System.DateTime DatetoInvoice { get; set; } public bool Invoiced { get; set; } } public ActionResult GetRouteData(string id) { try { int idr = Convert.ToInt32(id); var lstRoutes = (from a in dblim.Tb_Planning where (a.ID_Route == idr) select new RoutesInfo { ID_Route = a.ID_Route, Route_name = a.Route_name, ID_driver = a.ID_driver, Driver_name = a.Driver_name, ID_routeleader = a.ID_routeleader, Routeleader_name = a.Routeleader_name, ID_truck = a.ID_truck, Truck_name = a.Truck_name, Departure = a.Departure, isfinished = a.isfinished, ID_SAPRoute = a.ID_SAPRoute, query1 = a.query1, query2 = a.query2, query3 = a.query3, Date = a.Date, Invoiced = a.Invoiced, DatetoInvoice = a.DatetoInvoice }); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstRoutes.ToList()); return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult GetExtraData(string id) { try { int idr = Convert.ToInt32(id); var lstExtra = (from a in dblim.Tb_Planning_extra where (a.ID_Route == idr) select a); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(lstExtra.ToList()); return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult GetEvents(DateTime startf, DateTime endf) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } List<Tb_Planning> lstRoutes = new List<Tb_Planning>(); if (company_bodega == "01") { lstRoutes = dblim.Tb_Planning.Where(dc => dc.Departure >= startf && dc.Departure <= endf).OrderByDescending(dc => dc.ID_Route).ToList(); foreach (DateTime date in GetDateRange(startf, endf)) { var existeMasterRoute = (from a in dblim.Tb_Planning where (a.Departure == date && a.Warehouse != company_bodega) select a).Take(1).ToList(); if (existeMasterRoute.Count > 0) { lstRoutes.AddRange(existeMasterRoute); } } } else { lstRoutes = dblim.Tb_Planning.Where(dc => dc.Departure >= startf && dc.Departure <= endf && dc.Warehouse == company_bodega).OrderByDescending(dc => dc.ID_Route).ToList(); } List<Routes_calendar> rutaslst = new List<Routes_calendar>(); var rtids = lstRoutes.Select(c => c.ID_Route).ToArray(); //Cargamos todos los datos maestros a utilizar var solist = (from j in dblim.Tb_PlanningSO where (rtids.Contains(j.ID_Route)) select new { IDinterno = j.ID_salesorder, SAPDOC = j.SAP_docnum, IDRoute = j.ID_Route, amount = j.Amount, customerName = j.Customer_name }).ToList(); var solMaestro = solist.Select(c => c.IDinterno).ToArray(); var detallesMaestroSo = (from f in dblim.Tb_PlanningSO_details where (solMaestro.Contains(f.ID_salesorder)) select f).ToList(); List<Routes_calendar> rutas = new List<Routes_calendar>(); foreach (var item in lstRoutes) { Routes_calendar rt = new Routes_calendar(); rt.title = item.ID_Route + " - " + item.Route_name; rt.url = ""; rt.start = item.Departure.ToString("yyyy-MM-dd"); //rt.end = item.Departure.AddDays(1).ToString("yyyy-MM-dd"); rt.route_leader = item.Routeleader_name.ToUpper(); rt.className = ".fc-event"; rt.driver = item.Driver_name.ToUpper(); rt.truck = item.Truck_name; rt.departure = item.Departure.ToShortTimeString(); rt.Warehouse = item.Warehouse; if (item.isfinished == true) { rt.isfinished = "Y"; } else { rt.isfinished = "N"; } try { var extra = (from a in dblim.Tb_Planning_extra where (a.ID_Route == item.ID_Route) select a); if (extra.Count() > 0) { rt.extra = extra.Sum(x => x.Value).ToString(); } else { rt.extra = "0.00"; } } catch { rt.extra = "0.00"; } //INFO UOM var listafinalSO = solist.Where(c => c.IDRoute == item.ID_Route).ToList(); var sol = listafinalSO.Select(c => c.IDinterno).ToArray(); //Verificamos detalles para sacar CASE y EACH totales y luego promediar todal de EACH en base a CASES var detallesSo = (from f in detallesMaestroSo where (sol.Contains(f.ID_salesorder)) select f).ToList(); var totalCantEach = 0; var totalCantCases = 0; var totalCantPack = 0; var totalCantLbs = 0; decimal promedioEachxCases = 0; //Para calcular el promedio lo hacemos diviendo try { if (detallesSo.Count() > 0) { totalCantEach = detallesSo.Where(c => c.UomCode.Contains("EACH")).Count(); totalCantCases = detallesSo.Where(c => c.UomCode.Contains("CASE")).Count(); totalCantPack = detallesSo.Where(c => c.UomCode.Contains("PACK")).Count(); totalCantLbs = detallesSo.Where(c => c.UomCode.Contains("LBS")).Count(); foreach (var soitem in listafinalSO) { //devolvemos ID externo var docnum = Convert.ToInt32(soitem.SAPDOC); //Devolvemos todos los detalles(itemcode) de esa SO var itemscode = detallesSo.Where(c => c.ID_salesorder == soitem.IDinterno).Select(c => c.ItemCode).ToArray(); //Buscamos en la vista creada 9/24/2019 var sumatotal = dlipro.PlanningUoMInfo.Where(a => itemscode.Contains(a.ItemCode) && a.DocNum == docnum && a.Quantity > 0 && !a.unitMsr.Contains("LBS")).Sum(c => c.TotalCases); if (sumatotal > 0 && sumatotal != null) { promedioEachxCases += Convert.ToDecimal(sumatotal); } } } else { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; promedioEachxCases = 0; } } catch { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; promedioEachxCases = 0; } /// rt.totalEach = totalCantEach.ToString(); rt.totalCase = totalCantCases.ToString(); rt.totalPack = totalCantPack.ToString(); rt.totalLbs = totalCantLbs.ToString(); rt.AVGEach = Math.Round(promedioEachxCases, 2, MidpointRounding.ToEven).ToString(); var sum = (from e in solist where (e.IDRoute == item.ID_Route) select e); if (sum != null && sum.Count() >0) { rt.amount = sum.Select(c => c.amount).Sum().ToString(); rt.customerscount = sum.Select(c => c.customerName).Distinct().Count().ToString(); rt.orderscount = sum.Count().ToString(); } else { rt.amount = "0.0"; rt.customerscount = ""; rt.orderscount = ""; } rutaslst.Add(rt); } //} JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(rutaslst); return Json(result, JsonRequestBehavior.AllowGet); } catch(Exception ex) { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult closeSO(string id_sales) { try { var ID = Convert.ToInt32(id_sales); Tb_PlanningSO selSO = dblim.Tb_PlanningSO.Find(ID); selSO.isfinished = true; selSO.DateCheckOut = DateTime.UtcNow; dblim.Entry(selSO).State = EntityState.Modified; dblim.SaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult deleteSO(int id_salesorder) { try { Tb_PlanningSO selSO = dblim.Tb_PlanningSO.Find(id_salesorder); if (selSO.query5 == "Invoice") { //Actualizamos PUT_Invoices_api newput = new PUT_Invoices_api(); newput.stateSd = 8; var response2 = cls_invoices.PutInvoice(Convert.ToInt32(selSO.DocEntry), newput); } var detailstodel = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == selSO.ID_salesorder) select a).ToList(); dblim.Tb_PlanningSO_details.BulkDelete(detailstodel); dblim.SaveChanges(); dblim.Tb_PlanningSO.Remove(selSO); dblim.SaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult closeRoute(string id_route) { try { var ID = Convert.ToInt32(id_route); Tb_Planning route = dblim.Tb_Planning.Find(ID); route.isfinished = true; route.DateCheckOut = DateTime.UtcNow; dblim.Entry(route).State = EntityState.Modified; dblim.SaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult closeAllSalesOrders(string id_route) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var ID = Convert.ToInt32(id_route); var headerroute= dblim.Tb_Planning.Where(a => a.ID_Route == ID).Select(a => a).FirstOrDefault(); headerroute.DateCheckOut = DateTime.UtcNow; dblim.Entry(headerroute).State = EntityState.Modified; var route = dblim.Tb_PlanningSO.Where(a=> a.ID_Route==ID).Select(a=>a).ToList(); foreach (var item in route) { item.isfinished = true; if (activeuser != null) { item.ID_userValidate = activeuser.ID_User; } item.DateCheckOut = DateTime.UtcNow; dblim.Entry(item).State = EntityState.Modified; } dblim.BulkSaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult addContainer(int id_route, string containers) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; List<string> idContainers = containers.Split(',').ToList(); var route = (from a in dblim.Tb_Planning where (a.ID_Route == id_route) select a).FirstOrDefault(); if (route != null) { foreach (var item in idContainers) { var container = cls_Frezzers.GetFrezze(item).data; if (container != null) { Tb_logContainers newlog = new Tb_logContainers(); newlog.ID_container = container.code; newlog.Whs = container.whs; newlog.AssignerUser = activeuser.Name + " " + activeuser.Lastname; newlog.ReceivedUser = ""; newlog.DateAssigned = DateTime.UtcNow; newlog.DateReceived = DateTime.UtcNow; newlog.Barcode = container.code; newlog.Route = route.Route_name; newlog.Driver = route.Driver_name; newlog.Truck = route.Truck_name; newlog.ID_Route = id_route; newlog.inRoute = true; newlog.Comments = ""; newlog.Img = ""; newlog.Container = container.name; newlog.Status = 0; dblim.Tb_logContainers.Add(newlog); } } dblim.SaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } else { return Json("error", JsonRequestBehavior.AllowGet); } } catch(Exception ex) { return Json("Error: " + ex.Message, JsonRequestBehavior.AllowGet); } } public ActionResult transferItems(string id_route) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } List<int> TagIds = id_route.Split(',').Select(int.Parse).ToList(); var soedit = dblim.Tb_PlanningSO.Where(a => TagIds.Contains(a.ID_Route) && a.Transferred==0 && a.QC_count>1).Select(a => a).ToList(); var so_list = soedit.Select(a => a.ID_salesorder).ToArray(); foreach (var so in soedit) { so.Transferred= 1; dblim.Entry(so).State = EntityState.Modified; } var item_list = dblim.Tb_PlanningSO_details.Where(b => so_list.Contains(b.ID_salesorder) && b.Warehouse == company_bodega && !b.query1.Contains("DEL")).ToList(); foreach (var item in item_list) { item.isvalidated = false; item.Transferred = 1; item.QC_totalCount = item.QC_totalCount + 1; dblim.Entry(item).State = EntityState.Modified; } dblim.BulkSaveChanges(); return Json("success", JsonRequestBehavior.AllowGet); } catch { return Json("error", JsonRequestBehavior.AllowGet); } } public ActionResult GetSalesOrders(string id, DateTime date) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } int idr = Convert.ToInt32(id); //var salesOrders = new List<Tb_PlanningSO>(); DateTime selDate = Convert.ToDateTime(date).AddDays(1); DateTime filterdate = DateTime.Today.AddDays(-31); var tbplanningSO = (from obj in dblim.Tb_PlanningSO where (obj.SAP_docdate > filterdate && obj.Warehouse == company_bodega) select obj).ToList(); var rt = (from a in dblim.Tb_Planning where (a.ID_Route == idr && a.Warehouse == company_bodega) select new { id = a.ID_Route, isfinished = a.isfinished, transf = (from c in dblim.Tb_PlanningSO where (c.ID_Route == idr && c.Transferred > 0) select c).Count() }).ToList(); //Solo IDSO interno var solist = (from j in dblim.Tb_PlanningSO where (j.ID_Route == idr && j.Warehouse == company_bodega) select j.ID_salesorder).ToList(); //Verificamos detalles para sacar CASE y EACH totales y luego promediar todal de EACH en base a CASES var detallesSo = (from f in dblim.Tb_PlanningSO_details where (solist.Contains(f.ID_salesorder) && f.Warehouse == company_bodega) select f).ToList(); var totalCantEach = 0; var totalCantCases = 0; var totalCantPack = 0; var totalCantLbs = 0; decimal promedioEachxCases = 0; //Para calcular el promedio lo hacemos diviendo try { if (detallesSo.Count() > 0) { totalCantEach = detallesSo.Where(c => c.UomCode.Contains("EACH")).Count(); totalCantCases = detallesSo.Where(c => c.UomCode.Contains("CASE")).Count(); totalCantPack = detallesSo.Where(c => c.UomCode.Contains("PACK")).Count(); totalCantLbs = detallesSo.Where(c => c.UomCode.Contains("LBS")).Count(); foreach (var item in solist) { //devolvemos ID externo var docnum = Convert.ToInt32(dblim.Tb_PlanningSO.Where(j => j.ID_Route == idr && j.ID_salesorder == item && j.Warehouse == company_bodega).Select(c => c.SAP_docnum).FirstOrDefault()); //Devolvemos todos los detalles(itemcode) de esa SO var itemscode = detallesSo.Where(c => c.ID_salesorder == item).Select(c => c.ItemCode).ToArray(); //Buscamos en la vista creada 9/24/2019 var sumatotal = dlipro.PlanningUoMInfo.Where(a => itemscode.Contains(a.ItemCode) && a.DocNum == docnum && a.Quantity > 0 && !a.unitMsr.Contains("LBS")).Sum(c => c.TotalCases); promedioEachxCases += Math.Round(Convert.ToDecimal(sumatotal), 2, MidpointRounding.ToEven); } } else { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; promedioEachxCases = 0; } } catch { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; promedioEachxCases = 0; } //salesOrders = (from obj in dbcmk.VisitsM where (obj.ID_route == idr) select obj).ToList(); var lst = (from obj in dblim.Tb_PlanningSO where (obj.ID_Route == idr && obj.Warehouse == company_bodega) select new { id = obj.ID_salesorder, NumSO = obj.SAP_docnum, CardCode = obj.ID_customer, CustomerName = obj.Customer_name, DeliveryRoute = obj.query2, SalesPerson = obj.Rep_name, SODate = obj.SAP_docdate, OpenAmount = obj.Amount, Weight = obj.Weight, Volume = obj.Volume, Printed = obj.Printed, Remarks = obj.Remarks, Order = obj.query3 }).OrderBy(c => c.Order).ToArray(); var lstArray = (from obj in lst select obj.NumSO).ToArray(); var totalextra = ""; try { var extra = (from a in dblim.Tb_Planning_extra where (a.ID_Route == idr) select a); if (extra.Count() > 0) { totalextra = extra.Sum(x => x.Value).ToString(); } else { totalextra = "0.00"; } } catch { totalextra = "0.00"; } if (rt[0].isfinished == true || rt[0].transf > 0) { var lstOpenSales = (from obj in dlipro.OpenSalesOrders where (obj.NumSO == 11938023) select new OpenSO { NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToArray(); //estaesbuenasinfiltro//var lstOpenSales = (from obj in dlipro.OpenSalesOrders select new OpenSO { NumSO=obj.NumSO,CardCode = obj.CardCode, CustomerName = obj.CustomerName , DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed= obj.Printed }).ToArray(); //var lstOpenSales = (List<OpenSO>)Session["opensalesOrders"]; var lstRoutes = (from a in lstOpenSales select a.DeliveryRoute).OrderBy(a => a).Distinct().ToArray(); var lstReps = (from a in lstOpenSales select a.SalesPerson).OrderBy(a => a).Distinct().ToArray(); var lstCustomers = (from a in lstOpenSales select new { CustomerName = a.CardCode + " - " + a.CustomerName }).OrderBy(a => a.CustomerName).Distinct().ToArray(); //var lstCustomers = (from a in lstOpenSales select new { CardCode=a.CardCode, CustomerName = a.CustomerName }).OrderBy(a=>a.CardCode).Distinct().ToArray(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result2 = javaScriptSerializer.Serialize(lst); string result3 = javaScriptSerializer.Serialize(lstOpenSales); string result4 = javaScriptSerializer.Serialize(lstRoutes); string result5 = javaScriptSerializer.Serialize(lstReps); string result6 = javaScriptSerializer.Serialize(lstCustomers); string result7 = javaScriptSerializer.Serialize(rt); decimal result8 = Convert.ToDecimal(totalextra); //RESULT 8-12 para UOM INFO var result = new { result = result2, result2 = result3, result3 = result4, result4 = result5, result5 = result6, result6 = result7, result7 = result8, result8 = totalCantEach.ToString(), result9 = totalCantCases, result10 = totalCantPack, result11 = totalCantLbs, result12 = promedioEachxCases }; return Json(result, JsonRequestBehavior.AllowGet); } else { var lstOpenSales = (from obj in dlipro.OpenSalesOrders where (obj.SODate > filterdate && obj.WareHouse == company_bodega) select new OpenSO { NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToArray(); List<int> myCollection = new List<int>(); foreach (var saleOrder in lstOpenSales) { decimal openO = Convert.ToDecimal(saleOrder.OpenAmount); var sapdoc = saleOrder.NumSO.ToString(); var existe = (from a in tbplanningSO where (a.Amount == openO && a.SAP_docnum == sapdoc && a.Warehouse == company_bodega) select a).FirstOrDefault(); if (existe != null) { myCollection.Add(Convert.ToInt32(sapdoc)); } } lstOpenSales = (from a in lstOpenSales where (!myCollection.Contains(a.NumSO)) select a).ToArray(); //estaesbuenasinfiltro//var lstOpenSales = (from obj in dlipro.OpenSalesOrders select new OpenSO { NumSO=obj.NumSO,CardCode = obj.CardCode, CustomerName = obj.CustomerName , DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed= obj.Printed }).ToArray(); //var lstOpenSales = (List<OpenSO>)Session["opensalesOrders"]; var lstRoutes = (from a in lstOpenSales select a.DeliveryRoute).OrderBy(a => a).Distinct().ToArray(); var lstReps = (from a in lstOpenSales select a.SalesPerson).OrderBy(a => a).Distinct().ToArray(); var lstCustomers = (from a in lstOpenSales select new { CustomerName = a.CardCode + " - " + a.CustomerName }).OrderBy(a => a.CustomerName).Distinct().ToArray(); //var lstCustomers = (from a in lstOpenSales select new { CardCode=a.CardCode, CustomerName = a.CustomerName }).OrderBy(a=>a.CardCode).Distinct().ToArray(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result2 = javaScriptSerializer.Serialize(lst); string result3 = javaScriptSerializer.Serialize(lstOpenSales); string result4 = javaScriptSerializer.Serialize(lstRoutes); string result5 = javaScriptSerializer.Serialize(lstReps); string result6 = javaScriptSerializer.Serialize(lstCustomers); string result7 = javaScriptSerializer.Serialize(rt); decimal result8 = Convert.ToDecimal(totalextra); var result = new { result = result2, result2 = result3, result3 = result4, result4 = result5, result5 = result6, result6 = result7, result7 = result8, result8 = totalCantEach.ToString(), result9 = totalCantCases, result10 = totalCantPack, result11 = totalCantLbs, result12 = promedioEachxCases }; return Json(result, JsonRequestBehavior.AllowGet); } } public class sodocnum { public int id_salesorder { get; set; } public string docnum { get; set; } } public ActionResult Getextradetails(string id) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } int idr = Convert.ToInt32(id); //Solo IDSO interno var solist = (from j in dblim.Tb_PlanningSO where (j.ID_Route == idr && j.Warehouse==company_bodega) select new sodocnum { id_salesorder=j.ID_salesorder, docnum=j.SAP_docnum}).ToList(); var arrso = solist.Select(c => c.id_salesorder).ToArray(); //Verificamos detalles para sacar CASE y EACH totales y luego promediar todal de EACH en base a CASES var detallesSo = (from f in dblim.Tb_PlanningSO_details where (arrso.Contains(f.ID_salesorder) && f.Warehouse==company_bodega) select f).ToList(); var totalCantEach = 0; var totalCantCases = 0; var totalCantPack = 0; var totalCantLbs = 0; decimal promedioEachxCases = 0; //Para calcular el promedio lo hacemos diviendo try { if (detallesSo.Count() > 0) { totalCantEach = detallesSo.Where(c=>c.UomCode.Contains("EACH")).Count(); totalCantCases = detallesSo.Where(c=>c.UomCode.Contains("CASE")).Count(); totalCantPack = detallesSo.Where(c=>c.UomCode.Contains("PACK")).Count(); totalCantLbs = detallesSo.Where(c=>c.UomCode.Contains("LBS")).Count(); foreach (var item in solist) { //devolvemos ID externo // var docnum = Convert.ToInt32(dblim.Tb_PlanningSO.Where(j => j.ID_Route == idr && j.ID_salesorder==item && j.Warehouse==company_bodega).Select(c => c.SAP_docnum).FirstOrDefault()); var intdoc = Convert.ToInt32(item.docnum); //Devolvemos todos los detalles(itemcode) de esa SO var itemscode = detallesSo.Where(c=>c.ID_salesorder==item.id_salesorder).Select(c => c.ItemCode).ToArray(); //Buscamos en la vista creada 9/24/2019 var sumatotal = dlipro.PlanningUoMInfo.Where(a => itemscode.Contains(a.ItemCode) && a.DocNum == intdoc && a.Quantity > 0 && !a.unitMsr.Contains("LBS")).Sum(c => c.TotalCases); promedioEachxCases += Math.Round(Convert.ToDecimal(sumatotal),2, MidpointRounding.ToEven); } } else { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; promedioEachxCases = 0; } } catch { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; promedioEachxCases = 0; } var totalextra = "0.00"; JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); var result = new { result = Convert.ToDecimal(totalextra), totalEach = totalCantEach.ToString(), totalCases= totalCantCases, totalPack=totalCantPack, totalLBS=totalCantLbs, grantotal=promedioEachxCases}; return Json(result, JsonRequestBehavior.AllowGet); } public ActionResult GetSalesOrdersNew(string id, DateTime date) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } int idr = Convert.ToInt32(id); //var salesOrders = new List<Tb_PlanningSO>(); DateTime selDate = Convert.ToDateTime(date).AddDays(1); DateTime filterdate = DateTime.Today.AddDays(-31); //var tbplanningSO = (from obj in dblim.Tb_PlanningSO where (obj.SAP_docdate > filterdate && obj.Warehouse == company_bodega) select obj).ToList(); var rt = (from a in dblim.Tb_Planning where (a.ID_Route == idr && a.Warehouse == company_bodega) select new { id = a.ID_Route, isfinished = a.isfinished, transf = (from c in dblim.Tb_PlanningSO where (c.ID_Route == idr && c.Transferred > 0) select c).Count() }).ToList(); //Solo IDSO interno //var solist = (from j in dblim.Tb_PlanningSO where (j.ID_Route == idr && j.Warehouse == company_bodega) select j.ID_salesorder).ToList(); //Verificamos detalles para sacar CASE y EACH totales y luego promediar todal de EACH en base a CASES //var detallesSo = (from f in dblim.Tb_PlanningSO_details where (solist.Contains(f.ID_salesorder) && f.Warehouse == company_bodega) select f).ToList(); var totalCantEach = 0; var totalCantCases = 0; var totalCantPack = 0; var totalCantLbs = 0; decimal promedioEachxCases = 0; //Para calcular el promedio lo hacemos diviendo //try //{ // if (detallesSo.Count() > 0) // { // totalCantEach = detallesSo.Where(c => c.UomCode.Contains("EACH")).Count(); // totalCantCases = detallesSo.Where(c => c.UomCode.Contains("CASE")).Count(); // totalCantPack = detallesSo.Where(c => c.UomCode.Contains("PACK")).Count(); // totalCantLbs = detallesSo.Where(c => c.UomCode.Contains("LBS")).Count(); // foreach (var item in solist) // { // //devolvemos ID externo // var docnum = Convert.ToInt32(dblim.Tb_PlanningSO.Where(j => j.ID_Route == idr && j.ID_salesorder == item && j.Warehouse == company_bodega).Select(c => c.SAP_docnum).FirstOrDefault()); // //Devolvemos todos los detalles(itemcode) de esa SO // var itemscode = detallesSo.Where(c => c.ID_salesorder == item).Select(c => c.ItemCode).ToArray(); // //Buscamos en la vista creada 9/24/2019 // var sumatotal = dlipro.PlanningUoMInfo.Where(a => itemscode.Contains(a.ItemCode) && a.DocNum == docnum && a.Quantity > 0 && !a.unitMsr.Contains("LBS")).Sum(c => c.TotalCases); // promedioEachxCases += Math.Round(Convert.ToDecimal(sumatotal), 2, MidpointRounding.ToEven); // } // } // else // { // totalCantEach = 0; // totalCantCases = 0; // totalCantPack = 0; // totalCantLbs = 0; // promedioEachxCases = 0; // } //} //catch //{ // totalCantEach = 0; // totalCantCases = 0; // totalCantPack = 0; // totalCantLbs = 0; // promedioEachxCases = 0; //} //salesOrders = (from obj in dbcmk.VisitsM where (obj.ID_route == idr) select obj).ToList(); var lst = (from obj in dblim.Tb_PlanningSO where (obj.ID_Route == idr && obj.Warehouse == company_bodega && obj.query5!="Invoice") select new { id = obj.ID_salesorder, NumSO = obj.SAP_docnum, CardCode = obj.ID_customer, CustomerName = obj.Customer_name, DeliveryRoute = obj.query2, SalesPerson = obj.Rep_name, SODate = obj.SAP_docdate, OpenAmount = obj.Amount, Weight = obj.Weight, Volume = obj.Volume, Printed = obj.Printed, Remarks = obj.Remarks, Order = obj.query3 }).OrderBy(c => c.Order).ToArray(); var lstInvoices = (from obj in dblim.Tb_PlanningSO where (obj.ID_Route == idr && obj.Warehouse == company_bodega && obj.query5=="Invoice") select new { id = obj.ID_salesorder, NumSO = obj.SAP_docnum, CardCode = obj.ID_customer, CustomerName = obj.Customer_name, DeliveryRoute = obj.query2, SalesPerson = obj.Rep_name, SODate = obj.SAP_docdate, OpenAmount = obj.Amount, Weight = obj.Weight, Volume = obj.Volume, Printed = obj.Printed, Remarks = obj.Remarks, Order = obj.query3 }).OrderBy(c => c.Order).ToArray(); var lstArray = (from obj in lst select obj.NumSO).ToArray(); var totalextra = "0.00"; //try //{ // var extra = (from a in dblim.Tb_Planning_extra where (a.ID_Route == idr) select a); // if (extra.Count() > 0) // { // totalextra = extra.Sum(x => x.Value).ToString(); // } // else // { // totalextra = "0.00"; // } //} //catch //{ // totalextra = "0.00"; //} if (rt[0].isfinished == true || rt[0].transf > 0) { var lstOpenSales = (from obj in dlipro.OpenSalesOrders where (obj.NumSO == 11938023) select new OpenSO { NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToArray(); //estaesbuenasinfiltro//var lstOpenSales = (from obj in dlipro.OpenSalesOrders select new OpenSO { NumSO=obj.NumSO,CardCode = obj.CardCode, CustomerName = obj.CustomerName , DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed= obj.Printed }).ToArray(); //var lstOpenSales = (List<OpenSO>)Session["opensalesOrders"]; var lstRoutes = (from a in lstOpenSales select a.DeliveryRoute).OrderBy(a => a).Distinct().ToArray(); var lstReps = (from a in lstOpenSales select a.SalesPerson).OrderBy(a => a).Distinct().ToArray(); var lstCustomers = (from a in lstOpenSales select new { CustomerName = a.CardCode + " - " + a.CustomerName }).OrderBy(a => a.CustomerName).Distinct().ToArray(); //var lstCustomers = (from a in lstOpenSales select new { CardCode=a.CardCode, CustomerName = a.CustomerName }).OrderBy(a=>a.CardCode).Distinct().ToArray(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result2 = javaScriptSerializer.Serialize(lst); string result9 = javaScriptSerializer.Serialize(lstInvoices); string result3 = javaScriptSerializer.Serialize(lstOpenSales); string result4 = javaScriptSerializer.Serialize(lstRoutes); string result5 = javaScriptSerializer.Serialize(lstReps); string result6 = javaScriptSerializer.Serialize(lstCustomers); string result7 = javaScriptSerializer.Serialize(rt); decimal result8 = Convert.ToDecimal(totalextra); //RESULT 8-12 para UOM INFO var result = new { result = result2, result2 = result3, result3 = result4, result4 = result5, result5 = result6, result6 = result7, result7 = result8, result8 = totalCantEach.ToString(), result9 = totalCantCases, result10 = totalCantPack, result11 = totalCantLbs, result12 = promedioEachxCases, result13 = result9 }; return Json(result, JsonRequestBehavior.AllowGet); } else { var lstOpenSales = (from obj in dlipro.OpenSalesOrders where (obj.NumSO == 11938023) select new OpenSO { NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToArray(); //estaesbuenasinfiltro//var lstOpenSales = (from obj in dlipro.OpenSalesOrders select new OpenSO { NumSO=obj.NumSO,CardCode = obj.CardCode, CustomerName = obj.CustomerName , DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed= obj.Printed }).ToArray(); //var lstOpenSales = (List<OpenSO>)Session["opensalesOrders"]; var lstRoutes = (from a in lstOpenSales select a.DeliveryRoute).OrderBy(a => a).Distinct().ToArray(); var lstReps = (from a in lstOpenSales select a.SalesPerson).OrderBy(a => a).Distinct().ToArray(); var lstCustomers = (from a in lstOpenSales select new { CustomerName = a.CardCode + " - " + a.CustomerName }).OrderBy(a => a.CustomerName).Distinct().ToArray(); //var lstCustomers = (from a in lstOpenSales select new { CardCode=a.CardCode, CustomerName = a.CustomerName }).OrderBy(a=>a.CardCode).Distinct().ToArray(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result2 = javaScriptSerializer.Serialize(lst); string result9 = javaScriptSerializer.Serialize(lstInvoices); string result3 = javaScriptSerializer.Serialize(lstOpenSales); string result4 = javaScriptSerializer.Serialize(lstRoutes); string result5 = javaScriptSerializer.Serialize(lstReps); string result6 = javaScriptSerializer.Serialize(lstCustomers); string result7 = javaScriptSerializer.Serialize(rt); decimal result8 = Convert.ToDecimal(totalextra); var result = new { result = result2, result2 = result3, result3 = result4, result4 = result5, result5 = result6, result6 = result7, result7 = result8, result8 = totalCantEach.ToString(), result9 = totalCantCases, result10 = totalCantPack, result11 = totalCantLbs, result12 = promedioEachxCases, result13 = result9 }; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult GetOpenSOs() { DateTime filterdate = DateTime.Today.AddDays(-31); var lstOpenSales = (from obj in dlipro.OpenSalesOrders where(obj.SODate > filterdate) select new OpenSO { NumSO = obj.NumSO, CardCode = obj.CardCode, CustomerName = obj.CustomerName, DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed = obj.Printed }).ToArray(); //estaesbuenasinfiltro//var lstOpenSales = (from obj in dlipro.OpenSalesOrders select new OpenSO { NumSO=obj.NumSO,CardCode = obj.CardCode, CustomerName = obj.CustomerName , DeliveryRoute = obj.DeliveryRoute, SalesPerson = obj.SalesPerson, SODate = obj.SODate, TotalSO = obj.TotalSO, OpenAmount = obj.OpenAmount, Remarks = obj.Remarks, Printed= obj.Printed }).ToArray(); //var lstOpenSales = (List<OpenSO>)Session["opensalesOrders"]; var lstRoutes = (from a in lstOpenSales select a.DeliveryRoute).OrderBy(a => a).Distinct().ToArray(); var lstReps = (from a in lstOpenSales select a.SalesPerson).OrderBy(a => a).Distinct().ToArray(); var lstCustomers = (from a in lstOpenSales select new { CustomerName = a.CardCode + " - " + a.CustomerName }).OrderBy(a => a.CustomerName).Distinct().ToArray(); //var lstCustomers = (from a in lstOpenSales select new { CardCode=a.CardCode, CustomerName = a.CustomerName }).OrderBy(a=>a.CardCode).Distinct().ToArray(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result3 = javaScriptSerializer.Serialize(lstOpenSales); string result4 = javaScriptSerializer.Serialize(lstRoutes); string result5 = javaScriptSerializer.Serialize(lstReps); string result6 = javaScriptSerializer.Serialize(lstCustomers); var result = new { result2 = result3, result3 = result4, result4 = result5, result5 = result6, }; return Json(result, JsonRequestBehavior.AllowGet); } public class UomLst { public string UomCode { get; set; } public int UomEntry { get; set; } } public class detailsSO { public int ID_detail { get; set; } public int Line_num { get; set; } public string Bin_loc { get; set; } public decimal Quantity { get; set; } public string UomCode { get; set; } public string UomEntry { get; set; } public string ItemCode { get; set; } public string ItemName { get; set; } public string StockWhs01 { get; set; } public bool isvalidated { get; set; } public string ID_storagetype { get; set; } public string Storage_type { get; set; } public int ID_salesorder { get; set; } public string query1 { get; set; } public List<UomLst> lstuom { get; set; } } public ActionResult GetSalesOrdersDetails(string id, string id_storage) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } int idr = Convert.ToInt32(id); List<detailsSO> rt = new List<detailsSO>(); if (id_storage == "COOLER" || id_storage == "FREEZER") { rt = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idr && a.Quantity > 0 && (a.ID_storagetype == "COOLER" || a.ID_storagetype == "FREEZER") && a.Warehouse == company_bodega && !a.type.Contains("I")) select new detailsSO { ID_detail = a.ID_detail, Line_num = a.Line_num, Bin_loc = a.Bin_loc, Quantity = a.Quantity, UomCode = a.UomCode, UomEntry = a.UomEntry, ItemCode = a.ItemCode, ItemName = a.ItemName, StockWhs01 = a.StockWhs01, isvalidated = a.isvalidated, ID_storagetype = a.ID_storagetype, Storage_type = a.Storage_type, ID_salesorder = a.ID_salesorder, query1 = a.query1 }).OrderBy(a=>a.ID_detail).ToList(); } else { rt = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idr && a.Quantity > 0 && a.ID_storagetype == id_storage && !a.type.Contains("I") && a.Warehouse == company_bodega) select new detailsSO { ID_detail = a.ID_detail, Line_num = a.Line_num, Bin_loc = a.Bin_loc, Quantity = a.Quantity, UomCode = a.UomCode, UomEntry = a.UomEntry, ItemCode = a.ItemCode, ItemName = a.ItemName, StockWhs01 = a.StockWhs01, isvalidated = a.isvalidated, ID_storagetype = a.ID_storagetype, Storage_type = a.Storage_type, ID_salesorder = a.ID_salesorder, query1 = a.query1 }).OrderBy(a => a.ID_detail).ToList(); } foreach (var item in rt) { var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == item.ItemCode) select new UomLst { UomCode = a.UomCode, UomEntry = a.UomEntry }).ToList(); item.lstuom = lstava; } JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result2 = javaScriptSerializer.Serialize(rt); var result = new { result = result2 }; return Json(result, JsonRequestBehavior.AllowGet); } public ActionResult Routes_Report() { Sys_Users activeuser = Session["activeUser"] as Sys_Users; if (activeuser != null) { //HEADER //PAGINAS ACTIVAS ViewData["Menu"] = "Operations"; ViewData["Page"] = "Routes Report"; ViewBag.menunameid = "oper_menu"; ViewBag.submenunameid = "operrep_submenu"; List<string> d = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(d); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); ViewData["nameUser"] = activeuser.Name + " " + activeuser.Lastname; //NOTIFICATIONS DateTime now = DateTime.Today; List<Tb_Alerts> lstAlerts = (from a in dblim.Tb_Alerts where (a.ID_user == activeuser.ID_User && a.Active == true && a.Date == now) select a).OrderByDescending(x => x.Date).Take(5).ToList(); ViewBag.lstAlerts = lstAlerts; //FIN HEADER //Evaluamos si es supervisor o usuario normal para mostrar recursos o si es ambos o si es super admin return View(); } else { return RedirectToAction("Login", "Home", new { access = false }); } } [HttpPost] public JsonResult EditRoute(string id, string routeName, string lstDriverCode, string lstDriverName, string lstTruckCode, string lstTruckName, string lstRLeaderCode, string lstRLeaderName, DateTime departure, DateTime preparationdate) { try { int rdf = Convert.ToInt32(id); Tb_Planning tbpl = dblim.Tb_Planning.Find(rdf); tbpl.Route_name = routeName; tbpl.ID_driver = lstDriverCode; tbpl.Driver_name = lstDriverName; tbpl.ID_truck = lstTruckCode; tbpl.Truck_name = lstTruckName; tbpl.ID_routeleader = lstRLeaderCode; tbpl.Routeleader_name = lstRLeaderName; tbpl.Departure = departure; tbpl.DatetoInvoice = preparationdate; dblim.Entry(tbpl).State = EntityState.Modified; dblim.SaveChanges(); return Json("Success", JsonRequestBehavior.AllowGet); } catch { return Json("Error", JsonRequestBehavior.AllowGet); } } [HttpPost] public JsonResult AssignRoute(string id, string lstDriverCode, string lstDriverName, string lstTruckCode, string lstTruckName) { try { int rdf = Convert.ToInt32(id); Tb_Planning tbpl = dblim.Tb_Planning.Find(rdf); var route = dblim.Tb_Planning.Where(a => a.ID_Route == tbpl.ID_Route).FirstOrDefault(); var fecharuta = route.Departure; var fecharuta23 = fecharuta.AddHours(23); var rutasenfecha = dblim.Tb_Planning.Where(a => (a.Departure>=fecharuta && a.Departure<=fecharuta23) && a.Warehouse=="02").ToList(); foreach (var item in rutasenfecha) { item.ID_driver_whs = lstDriverCode; item.Driver_name_whs = lstDriverName; item.ID_truck_whs = lstTruckCode; item.Truck_name_whs = lstTruckName; } dblim.BulkUpdate(rutasenfecha); return Json("Success", JsonRequestBehavior.AllowGet); } catch { return Json("Error", JsonRequestBehavior.AllowGet); } } private dbLimenaEntities AddToContext(dbLimenaEntities context, Tb_PlanningSO_details entity, int count, int commitCount, bool recreateContext) { context.Set<Tb_PlanningSO_details>().Add(entity); if (count % commitCount == 0) { context.SaveChanges(); if (recreateContext) { context.Dispose(); context = new dbLimenaEntities(); context.Configuration.AutoDetectChangesEnabled = false; } } return context; } public ActionResult CreateRoutePlanning(string routeName, string lstMasterCode, string lstMasterName, string lstDriverCode, string lstDriverName, string lstTruckCode, string lstTruckName, string lstRLeaderCode, string lstRLeaderName, DateTime departure, DateTime preparationdate, string otherwhs) { try { if (generalClass.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } dblim.Configuration.AutoDetectChangesEnabled = false; dblim.Configuration.ValidateOnSaveEnabled = false; Tb_Planning newPlanning = new Tb_Planning(); newPlanning.Route_name = routeName; newPlanning.ID_SAPRoute = lstMasterCode; newPlanning.ID_driver = lstDriverCode; newPlanning.Driver_name = lstDriverName; newPlanning.ID_truck = lstTruckCode; newPlanning.Truck_name = lstTruckName; newPlanning.ID_routeleader = lstRLeaderCode; newPlanning.Routeleader_name = lstRLeaderName; newPlanning.Departure = departure; newPlanning.isfinished = false; newPlanning.query1 = ""; if (otherwhs == "YES") { newPlanning.query1 = "from"; } newPlanning.query2 = ""; newPlanning.query3 = 0; newPlanning.Invoiced = false; newPlanning.Date = departure.Date; newPlanning.DateCheckIn = DateTime.UtcNow; newPlanning.DateCheckOut = DateTime.UtcNow; newPlanning.ID_userValidate = 0; //Nueva propiedad para bodega newPlanning.Warehouse = company_bodega; newPlanning.ID_driver_whs = ""; newPlanning.Driver_name_whs = ""; newPlanning.ID_truck_whs = ""; newPlanning.Truck_name_whs = ""; newPlanning.DatetoInvoice = preparationdate; dblim.Tb_Planning.Add(newPlanning); dblim.SaveChanges(); DateTime filterdate = DateTime.Today.AddDays(-31); var lstArray = (from obj in dblim.Tb_PlanningSO where (obj.SAP_docdate > filterdate) select obj.SAP_docnum).ToArray(); //var lstArray = (from obj in dblim.Tb_PlanningSO where (obj.isfinished == false && obj.DocEntry == "") select obj.SAP_docnum).ToArray(); List<int> myCollection = new List<int>(); foreach (var item in lstArray) { myCollection.Add(Convert.ToInt32(item)); } var salesOrders = (from a in dlipro.OpenSalesOrders where (a.DeliveryRoute == lstMasterName && !myCollection.Contains(a.NumSO) && a.SODate > filterdate) select a).ToList(); var avaSO = (from a in salesOrders select a.NumSO).ToArray(); if (salesOrders.Count > 0) { //ORDER BY AREA, SUBAREA, UoMFilter, PrintOrder, U_BinLocation, T1.ItemCode var dtSO_details = (from c in dlipro.OpenSalesOrders_Details where (avaSO.Contains(c.DocNum) && !c.TreeType.Contains("I")) select c).OrderBy(c => c.AREA).ThenBy(c => c.SUBAREA).ThenBy(c => c.UoMFilter).ThenBy(c => c.PrintOrder).ThenBy(c => c.U_BinLocation).ThenBy(c => c.ItemCode).ToList(); try { var count = 0; foreach (var saleOrder in salesOrders) { if (saleOrder.OpenAmount == saleOrder.TotalSO) { decimal openO = Convert.ToDecimal(saleOrder.OpenAmount); var sapdoc = saleOrder.NumSO.ToString(); var existe = (from a in dblim.Tb_PlanningSO where (a.Amount == openO && a.SAP_docnum == sapdoc) select a).FirstOrDefault(); if (existe == null) { Tb_PlanningSO newSO = new Tb_PlanningSO(); newSO.SAP_docnum = saleOrder.NumSO.ToString(); newSO.SAP_docdate = Convert.ToDateTime(saleOrder.SODate); newSO.ID_customer = saleOrder.CardCode; newSO.Customer_name = saleOrder.CustomerName.ToUpper(); newSO.ID_rep = saleOrder.IDSalesPerson.ToString(); newSO.Rep_name = saleOrder.SalesPerson.ToUpper(); newSO.ID_SAPRoute = newPlanning.ID_SAPRoute; newSO.Amount = Convert.ToDecimal(saleOrder.OpenAmount); newSO.isfinished = false; newSO.query1 = ""; newSO.query2 = saleOrder.DeliveryRoute; newSO.query3 = 0; //newSO.query3 = count; newSO.query4 = ""; newSO.query5 = ""; newSO.Weight = ""; newSO.Volume = ""; newSO.Printed = saleOrder.Printed; newSO.ID_Route = newPlanning.ID_Route; newSO.DocEntry = ""; newSO.DateCheckIn = DateTime.UtcNow; newSO.DateCheckOut = DateTime.UtcNow; newSO.ID_userValidate = 0; newSO.Warehouse = saleOrder.WareHouse; newSO.Transferred = 0; newSO.QC_count = Convert.ToInt32(saleOrder.NoWhs); newSO.MensajeError = ""; newSO.Error = 0; if (saleOrder.Remarks == null) { newSO.Remarks = ""; } else { newSO.Remarks = saleOrder.Remarks; } dblim.Tb_PlanningSO.Add(newSO); dblim.SaveChanges(); count++; var detailslst = (from a in dtSO_details where (a.DocNum == saleOrder.NumSO) select a).ToList(); if (detailslst.Count > 0) { List<Tb_PlanningSO_details> lsttosave = new List<Tb_PlanningSO_details>(); foreach (var dt in detailslst) { Tb_PlanningSO_details newDtl = new Tb_PlanningSO_details(); newDtl.Line_num = dt.LineNum; if (dt.U_BinLocation == null) { newDtl.Bin_loc = ""; } else { newDtl.Bin_loc = dt.U_BinLocation; } newDtl.Quantity = Convert.ToDecimal(dt.Quantity); if (dt.UomEntry == null) { newDtl.UomEntry = ""; } else { newDtl.UomEntry = dt.UomEntry.ToString(); } if (dt.UomCode == null) { newDtl.UomCode = ""; } else { newDtl.UomCode = dt.UomCode; } newDtl.NumPerMsr = Convert.ToDecimal(dt.NumPerMsr); newDtl.ItemCode = dt.ItemCode; newDtl.AREA = dt.AREA.ToString(); newDtl.SUBAREA = dt.SUBAREA.ToString(); newDtl.UomFilter = dt.UoMFilter.ToString(); newDtl.PrintOrder = dt.PrintOrder.ToString(); newDtl.ItemName = dt.ItemName; newDtl.StockWhs01 = ""; newDtl.isvalidated = false; if (dt.U_Storage == null) { newDtl.ID_storagetype = ""; } else { newDtl.ID_storagetype = dt.U_Storage; } if (dt.U_Storage == null) { newDtl.Storage_type = ""; } else { newDtl.Storage_type = dt.U_Storage; } newDtl.ID_salesorder = newSO.ID_salesorder; newDtl.query1 = ""; newDtl.query2 = dt.CambioPrecio.ToString(); newDtl.ID_picker = ""; newDtl.Picker_name = ""; newDtl.ID_pickerWHS = ""; newDtl.Picker_nameWHS = ""; newDtl.DateCheckIn = DateTime.UtcNow; newDtl.DateCheckOut = DateTime.UtcNow; newDtl.ID_userValidate = 0; newDtl.ID_ValidationDetails = 0; newDtl.ValidationDetails = ""; newDtl.type = dt.TreeType; newDtl.parent = ""; newDtl.childrendefqty = 0; newDtl.Transferred = 0; newDtl.Warehouse = dt.Whs; newDtl.QC_count = Convert.ToInt32(dt.NoWhs); if (newSO.Warehouse == dt.Whs) { newDtl.QC_totalCount = Convert.ToInt32(dt.NoWhs); } else { newDtl.QC_totalCount = 1; } lsttosave.Add(newDtl); //Si tiene hijos o es propiedad S, agregamos if (dt.TreeType == "S") { int countLineNum = dt.LineNum + 1; var kit_childs = (from d in dlipro.ITT1 where (d.Father == dt.ItemCode) select d).OrderBy(d => d.ChildNum).ToList(); if (kit_childs.Count > 0) { foreach (var hijo in kit_childs) { var childinfo = (from ad in dlipro.BI_Dim_Products where (ad.id == hijo.Code) select ad).FirstOrDefault(); var itemnamechild = ""; if (childinfo != null) { itemnamechild = childinfo.item_name; } Tb_PlanningSO_details newDtlHijo = new Tb_PlanningSO_details(); newDtlHijo.Line_num = countLineNum; if (dt.U_BinLocation == null) { newDtlHijo.Bin_loc = ""; } else { newDtlHijo.Bin_loc = dt.U_BinLocation; } newDtlHijo.Quantity = Convert.ToInt32(hijo.Quantity); if (dt.UomEntry == null) { newDtlHijo.UomEntry = ""; } else { newDtlHijo.UomEntry = dt.UomEntry.ToString(); } if (dt.UomCode == null) { newDtlHijo.UomCode = ""; } else { newDtlHijo.UomCode = dt.UomCode; } newDtlHijo.NumPerMsr = 0; newDtlHijo.ItemCode = hijo.Code; newDtlHijo.AREA = dt.AREA.ToString(); newDtlHijo.SUBAREA = dt.SUBAREA.ToString(); newDtlHijo.UomFilter = dt.UoMFilter.ToString(); newDtlHijo.PrintOrder = dt.PrintOrder.ToString(); newDtlHijo.ItemName = itemnamechild; newDtlHijo.StockWhs01 = ""; newDtlHijo.isvalidated = false; if (dt.U_Storage == null) { newDtlHijo.ID_storagetype = ""; } else { newDtlHijo.ID_storagetype = dt.U_Storage; } if (dt.U_Storage == null) { newDtlHijo.Storage_type = ""; } else { newDtlHijo.Storage_type = dt.U_Storage; } newDtlHijo.ID_salesorder = newSO.ID_salesorder; newDtlHijo.query1 = ""; newDtlHijo.query2 = ""; newDtlHijo.ID_picker = ""; newDtlHijo.Picker_name = ""; newDtlHijo.ID_pickerWHS = ""; newDtlHijo.Picker_nameWHS = ""; newDtlHijo.DateCheckIn = DateTime.UtcNow; newDtlHijo.DateCheckOut = DateTime.UtcNow; newDtlHijo.ID_userValidate = 0; newDtlHijo.ID_ValidationDetails = 0; newDtlHijo.ValidationDetails = ""; newDtlHijo.type = "I"; newDtlHijo.parent = dt.ItemCode; newDtlHijo.childrendefqty = Convert.ToInt32(hijo.Quantity); newDtlHijo.Transferred = 0; newDtlHijo.Warehouse = dt.Whs; newDtlHijo.QC_count = Convert.ToInt32(dt.NoWhs); if (newSO.Warehouse == dt.Whs) { newDtlHijo.QC_totalCount = Convert.ToInt32(dt.NoWhs); } else { newDtlHijo.QC_totalCount = 1; } lsttosave.Add(newDtlHijo); countLineNum++; } } } } dblim.BulkInsert(lsttosave); } } } } } catch { } } //List<Routes_calendar> rutaslst = new List<Routes_calendar>(); //Routes_calendar rt = new Routes_calendar(); //rt.title = newPlanning.ID_Route + " - " + newPlanning.Route_name; //rt.url = ""; //rt.start = newPlanning.Departure.ToString("yyyy-MM-dd"); ////rt.end = item.Departure.AddDays(1).ToString("yyyy-MM-dd"); //rt.route_leader = newPlanning.Routeleader_name; //rt.className = ".fc-event"; //rt.driver = newPlanning.Driver_name; //rt.truck = newPlanning.Truck_name; //rt.departure = newPlanning.Departure.ToShortTimeString(); //if (newPlanning.isfinished == true) { rt.isfinished = "Y"; } else { rt.isfinished = "N"; } //var sum = (from e in dblim.Tb_PlanningSO where (e.ID_Route == newPlanning.ID_Route && e.Warehouse==company_bodega) select e); //if (sum != null && sum.Count() > 0) //{ // rt.amount = sum.Select(c => c.Amount).Sum().ToString(); // rt.customerscount = sum.Select(c => c.Customer_name).Distinct().Count().ToString(); // rt.orderscount = sum.Count().ToString(); //} //else //{ // rt.amount = "0.0"; // rt.customerscount = ""; // rt.orderscount = ""; //} //rutaslst.Add(rt); //JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); //string result = javaScriptSerializer.Serialize(rutaslst); return Json("success", JsonRequestBehavior.AllowGet); } return Json("Error trying saving new route", JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json("Error: " + ex.Message, JsonRequestBehavior.AllowGet); } } public ActionResult deleteAssignedFreezer(int id_reg) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var log = (from a in dblim.Tb_logContainers where (a.ID_reg == id_reg) select a).FirstOrDefault(); log.inRoute = false; log.Comments = "Deleted by " + activeuser.ID_User + "-" + activeuser.Name + " " + activeuser.Lastname + " on " + DateTime.UtcNow; dblim.Entry(log).State = EntityState.Modified; dblim.SaveChanges(); var rrresult = "success"; return Json(rrresult, JsonRequestBehavior.AllowGet); } catch (Exception ex) { string result = "Error: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult receiveAssignedFreezer(string code, string comments) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var log = (from a in dblim.Tb_logContainers where (a.ID_container == code && a.inRoute==true) select a).FirstOrDefault(); if (log != null) { log.inRoute = false; if (comments == "" || comments == null) { comments = ""; } log.Comments = comments; log.ReceivedUser = activeuser.Name + " " + activeuser.Lastname; log.DateReceived = DateTime.UtcNow; dblim.Entry(log).State = EntityState.Modified; dblim.SaveChanges(); var rrresult = "success"; return Json(rrresult, JsonRequestBehavior.AllowGet); } else { var rrresult = "Freezer not found"; return Json(rrresult, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { string result = "Error: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult deleteRoute(string id_route) { try { var id = Convert.ToInt32(id_route); var route = dblim.Tb_Planning.Where(c => c.ID_Route == id).Select(c => c).FirstOrDefault(); if (route != null) { var vp = dblim.Tb_PlanningSO.Where(a => a.ID_Route == id); var todelete = (from f in vp select f.ID_salesorder).ToArray(); var vpdet = dblim.Tb_PlanningSO_details.Where(a => todelete.Contains(a.ID_salesorder)); //dblim.Tb_PlanningSO_details.RemoveRange(vpdet); dblim.BulkDelete(vpdet); dblim.Tb_PlanningSO.RemoveRange(vp); dblim.SaveChanges(); dblim.Tb_Planning.Remove(route); var vp_extra = dblim.Tb_Planning_extra.Where(a => a.ID_Route == id); dblim.Tb_Planning_extra.RemoveRange(vp_extra); dblim.SaveChanges(); var rrresult = "SUCCESS"; return Json(rrresult, JsonRequestBehavior.AllowGet); } else { string result = "NO DATA FOUND"; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { string result = "ERROR: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult SaveSalesOrders(string[] salesOrders, string id_route) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } if (salesOrders == null) { //var id = Convert.ToInt32(id_route); //var vp = dblim.Tb_PlanningSO.Where(a => a.ID_Route == id); //var todelete = (from f in vp select f.ID_salesorder).ToArray(); //var vpdet = dblim.Tb_PlanningSO_details.Where(a => todelete.Contains(a.ID_salesorder)); ////dblim.Tb_PlanningSO_details.RemoveRange(vpdet); //dblim.BulkDelete(vpdet); //dblim.Tb_PlanningSO.RemoveRange(vp); //dblim.SaveChanges(); var rrresult = "SUCCESS"; return Json(rrresult, JsonRequestBehavior.AllowGet); } else { if (salesOrders.Length > 0 || salesOrders != null) { var id = Convert.ToInt32(id_route); var soexist = (from f in dblim.Tb_PlanningSO where (f.ID_Route == id ) select f.SAP_docnum).ToArray(); var fincoll = (from a in soexist where (!salesOrders.Contains(a)) select a).ToArray(); Tb_Planning planning = new Tb_Planning(); planning = dblim.Tb_Planning.Find(id); if (fincoll.Length > 0) { //var todelete = (from f in dblim.Tb_PlanningSO where (f.ID_Route == id && fincoll.Contains(f.SAP_docnum)) select f.ID_salesorder).ToArray(); //var vpdet = dblim.Tb_PlanningSO_details.Where(a => todelete.Contains(a.ID_salesorder)); //dblim.Tb_PlanningSO_details.RemoveRange(vpdet); //dblim.BulkDelete(vpdet); //var vp = dblim.Tb_PlanningSO.Where(a => a.ID_Route == id && fincoll.Contains(a.SAP_docnum)); //dblim.Tb_PlanningSO.RemoveRange(vp); //dblim.SaveChanges(); } salesOrders = (from a in salesOrders where (!soexist.Contains(a)) select a).ToArray(); List<int> myCollection = new List<int>(); foreach (var item in salesOrders) { myCollection.Add(Convert.ToInt32(item)); } var dtSO = (from c in dlipro.OpenSalesOrders where (myCollection.Contains(c.NumSO)) select c).ToList(); var dtSO_details = (from c in dlipro.OpenSalesOrders_Details where (myCollection.Contains(c.DocNum) && !c.TreeType.Contains("I")) select c).OrderBy(c => c.AREA).ThenBy(c => c.SUBAREA).ThenBy(c => c.UoMFilter).ThenBy(c => c.PrintOrder).ThenBy(c => c.U_BinLocation).ThenBy(c => c.ItemCode).ToList(); foreach (string value in salesOrders) { var idso = Convert.ToInt32(value); var saleOrder = (from a in dtSO where (a.NumSO == idso) select a).First(); decimal openO = Convert.ToDecimal(saleOrder.OpenAmount); var sapdoc = saleOrder.NumSO.ToString(); var existe = (from a in dblim.Tb_PlanningSO where (a.Amount == openO && a.SAP_docnum == sapdoc) select a).FirstOrDefault(); if (existe == null) { Tb_PlanningSO newSO = new Tb_PlanningSO(); newSO.SAP_docnum = saleOrder.NumSO.ToString(); newSO.SAP_docdate = Convert.ToDateTime(saleOrder.SODate); newSO.ID_customer = saleOrder.CardCode; newSO.Customer_name = saleOrder.CustomerName.ToUpper(); newSO.ID_rep = saleOrder.IDSalesPerson.ToString(); newSO.Rep_name = saleOrder.SalesPerson.ToUpper(); newSO.ID_SAPRoute = planning.ID_SAPRoute; newSO.Amount = Convert.ToDecimal(saleOrder.OpenAmount); newSO.isfinished = false; newSO.query1 = ""; newSO.query2 = saleOrder.DeliveryRoute; newSO.query3 = 0; newSO.query4 = ""; newSO.query5 = ""; newSO.Weight = ""; newSO.Volume = ""; newSO.Printed = saleOrder.Printed; newSO.ID_Route = planning.ID_Route; newSO.DocEntry = ""; newSO.DateCheckIn = DateTime.UtcNow; newSO.DateCheckOut = DateTime.UtcNow; newSO.ID_userValidate = 0; newSO.Transferred = 0; newSO.Warehouse = saleOrder.WareHouse; newSO.MensajeError = ""; newSO.Error = 0; newSO.QC_count = Convert.ToInt32(saleOrder.NoWhs); if (saleOrder.Remarks == null) { newSO.Remarks = ""; } else { newSO.Remarks = saleOrder.Remarks; } dblim.Tb_PlanningSO.Add(newSO); dblim.SaveChanges(); //List<Tb_PlanningSO_details> lstsave = new List<Tb_PlanningSO_details>(); var detailslst2 = (from a in dtSO_details where (a.DocNum == saleOrder.NumSO) select a).ToList(); if (detailslst2.Count > 0) { List<Tb_PlanningSO_details> lsttosave = new List<Tb_PlanningSO_details>(); foreach (var dt in detailslst2) { Tb_PlanningSO_details newDtl = new Tb_PlanningSO_details(); newDtl.Line_num = dt.LineNum; if (dt.U_BinLocation == null) { newDtl.Bin_loc = ""; } else { newDtl.Bin_loc = dt.U_BinLocation; } newDtl.Quantity = Convert.ToDecimal(dt.Quantity); if (dt.UomEntry == null) { newDtl.UomEntry = ""; } else { newDtl.UomEntry = dt.UomEntry.ToString(); } if (dt.UomCode == null) { newDtl.UomCode = ""; } else { newDtl.UomCode = dt.UomCode; } newDtl.NumPerMsr = Convert.ToDecimal(dt.NumPerMsr); newDtl.ItemCode = dt.ItemCode; newDtl.AREA = dt.AREA.ToString(); newDtl.SUBAREA = dt.SUBAREA.ToString(); newDtl.UomFilter = dt.UoMFilter.ToString(); newDtl.PrintOrder = dt.PrintOrder.ToString(); newDtl.ItemCode = dt.ItemCode; newDtl.ItemName = dt.ItemName; newDtl.StockWhs01 = ""; newDtl.isvalidated = false; if (dt.U_Storage == null) { newDtl.ID_storagetype = ""; } else { newDtl.ID_storagetype = dt.U_Storage; } if (dt.U_Storage == null) { newDtl.Storage_type = ""; } else { newDtl.Storage_type = dt.U_Storage; } newDtl.ID_salesorder = newSO.ID_salesorder; newDtl.query1 = ""; newDtl.query2 = dt.CambioPrecio.ToString(); newDtl.ID_picker = ""; newDtl.Picker_name = ""; newDtl.ID_pickerWHS = ""; newDtl.Picker_nameWHS = ""; newDtl.DateCheckIn = DateTime.UtcNow; newDtl.DateCheckOut = DateTime.UtcNow; newDtl.ID_userValidate = 0; newDtl.ID_ValidationDetails = 0; newDtl.ValidationDetails = ""; newDtl.type = dt.TreeType; newDtl.parent = ""; newDtl.childrendefqty = 0; newDtl.Warehouse = dt.Whs; newDtl.Transferred = 0; //Evaluamos si se haran 2 conteos o 1 //02=Louisville, KY ----- WHS=01-Nashville, TN //Se haran 2 conteos si la orden es solicitada en KY pero el detalle sale de TN newDtl.QC_count = Convert.ToInt32(dt.NoWhs); if (newSO.Warehouse == dt.Whs) { newDtl.QC_totalCount = Convert.ToInt32(dt.NoWhs); } else { newDtl.QC_totalCount = 1; } lsttosave.Add(newDtl); //dblim.Tb_PlanningSO_details.Add(newDtl); //Si tiene hijos o es propiedad S, agregamos if (dt.TreeType == "S") { int countLineNum = dt.LineNum + 1; var kit_childs = (from d in dlipro.ITT1 where (d.Father == dt.ItemCode) select d).OrderBy(d => d.ChildNum).ToList(); if (kit_childs.Count > 0) { foreach (var hijo in kit_childs) { var childinfo = (from ad in dlipro.BI_Dim_Products where (ad.id == hijo.Code) select ad).FirstOrDefault(); var itemnamechild = ""; if (childinfo != null) { itemnamechild = childinfo.item_name; } Tb_PlanningSO_details newDtlHijo = new Tb_PlanningSO_details(); newDtlHijo.Line_num = countLineNum; if (dt.U_BinLocation == null) { newDtlHijo.Bin_loc = ""; } else { newDtlHijo.Bin_loc = dt.U_BinLocation; } newDtlHijo.Quantity = Convert.ToDecimal(hijo.Quantity); if (dt.UomEntry == null) { newDtlHijo.UomEntry = ""; } else { newDtlHijo.UomEntry = dt.UomEntry.ToString(); } if (dt.UomCode == null) { newDtlHijo.UomCode = ""; } else { newDtlHijo.UomCode = dt.UomCode; } newDtlHijo.NumPerMsr = 0; newDtlHijo.ItemCode = hijo.Code; newDtlHijo.AREA = dt.AREA.ToString(); newDtlHijo.SUBAREA = dt.SUBAREA.ToString(); newDtlHijo.UomFilter = dt.UoMFilter.ToString(); newDtlHijo.PrintOrder = dt.PrintOrder.ToString(); newDtlHijo.ItemName = itemnamechild; newDtlHijo.StockWhs01 = ""; newDtlHijo.isvalidated = false; if (dt.U_Storage == null) { newDtlHijo.ID_storagetype = ""; } else { newDtlHijo.ID_storagetype = dt.U_Storage; } if (dt.U_Storage == null) { newDtlHijo.Storage_type = ""; } else { newDtlHijo.Storage_type = dt.U_Storage; } newDtlHijo.ID_salesorder = newSO.ID_salesorder; newDtlHijo.query1 = ""; newDtlHijo.query2 = ""; newDtlHijo.ID_picker = ""; newDtlHijo.Picker_name = ""; newDtlHijo.ID_pickerWHS = ""; newDtlHijo.Picker_nameWHS = ""; newDtlHijo.DateCheckIn = DateTime.UtcNow; newDtlHijo.DateCheckOut = DateTime.UtcNow; newDtlHijo.ID_userValidate = 0; newDtlHijo.ID_ValidationDetails = 0; newDtlHijo.ValidationDetails = ""; newDtlHijo.type = "I"; newDtlHijo.parent = dt.ItemCode; newDtlHijo.childrendefqty = Convert.ToInt32(hijo.Quantity); newDtlHijo.Warehouse = dt.Whs; newDtlHijo.QC_count = Convert.ToInt32(dt.NoWhs); if (newSO.Warehouse == dt.Whs) { newDtlHijo.QC_totalCount = Convert.ToInt32(dt.NoWhs); ; } else { newDtlHijo.QC_totalCount = 1; } newDtlHijo.Transferred = 0; lsttosave.Add(newDtlHijo); countLineNum++; } } } } dblim.BulkInsert(lsttosave); } } } string ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } else { string result = "NO DATA"; return Json(result, JsonRequestBehavior.AllowGet); } } } catch (Exception ex) { string result = "ERROR: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult SaveInvoices(string[] invoices, string id_route) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } if (invoices.Length > 0 || invoices != null) { var id = Convert.ToInt32(id_route); var soexist = (from f in dblim.Tb_PlanningSO where (f.ID_Route == id && f.query5=="Invoice") select f.SAP_docnum).ToArray(); var fincoll = (from a in soexist where (!invoices.Contains(a)) select a).ToArray(); Tb_Planning planning = new Tb_Planning(); planning = dblim.Tb_Planning.Find(id); invoices = (from a in invoices where (!soexist.Contains(a)) select a).ToArray(); List<int> myCollection = new List<int>(); foreach (var item in invoices) { myCollection.Add(Convert.ToInt32(item)); } foreach (string value in invoices) { int inv = Convert.ToInt32(value); var invoice = cls_invoices.GetInvoice(0, inv, false).data[0]; if (invoice != null) { Tb_PlanningSO newSO = new Tb_PlanningSO(); newSO.SAP_docnum = invoice.docNum.ToString(); newSO.SAP_docdate = Convert.ToDateTime(invoice.docDate); newSO.ID_customer = invoice.cardCode; newSO.Customer_name = invoice.cardName.ToUpper(); newSO.ID_rep = invoice.slpCode.ToString(); newSO.Rep_name = invoice.slpName.ToUpper(); newSO.ID_SAPRoute = planning.ID_SAPRoute; newSO.Amount = Convert.ToDecimal(invoice.docTotal); newSO.isfinished = false; newSO.query1 = ""; newSO.query2 = invoice.deliveryRoute; newSO.query3 = 0; newSO.query4 = ""; newSO.query5 = "Invoice"; //Se agrego pra validar facturas retornadas newSO.Weight = ""; newSO.Volume = ""; newSO.Printed = "Y"; //Ya que es factura newSO.ID_Route = planning.ID_Route; newSO.DocEntry = invoice.docEntry.ToString(); newSO.DateCheckIn = DateTime.UtcNow; newSO.DateCheckOut = DateTime.UtcNow; newSO.ID_userValidate = 0; newSO.Transferred = 0; newSO.Warehouse = "01"; newSO.MensajeError = ""; newSO.Error = 0; newSO.QC_count = 1; newSO.Remarks = ""; dblim.Tb_PlanningSO.Add(newSO); dblim.SaveChanges(); //Actualizamos invoice PUT_Invoices_api newput = new PUT_Invoices_api(); newput.idDriver = planning.ID_driver; newput.idHelper = planning.ID_routeleader; newput.idTruck = planning.ID_truck; newput.deliveryDate = planning.Departure; newput.stateSd = 1; newput.id_Delivery = planning.ID_Route.ToString(); var response2 = cls_invoices.PutInvoice(invoice.docEntry, newput); } } string ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } else { string result = "NO DATA"; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { string result = "ERROR: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult SortSalesOrders(string[] salesOrders, string id_route) { try { if (salesOrders != null) { if (salesOrders.Length > 0) { var id = Convert.ToInt32(id_route); var sodb = (from f in dblim.Tb_PlanningSO where (f.ID_Route == id ) select f); var total = sodb.Count(); var count = 0; if (total > 0) { foreach (var item in salesOrders) //Ordenamos en base al orden que trae la cadena { //var idsoin = Convert.ToInt32(item); var saUp = (from a in sodb where (a.SAP_docnum == item) select a).FirstOrDefault(); saUp.query3 = count; dblim.Entry(saUp).State = EntityState.Modified; count++; } dblim.BulkSaveChanges(); } string ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } } string result = "NO DATA"; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { string result = "ERROR: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult Save_order(List<orderSO> objects) { try { if (objects != null) { if (objects.Count > 0) { var count = 0; foreach (var item in objects) //Ordenamos en base al orden que trae la cadena { if (item.comment == null) { item.comment = ""; } //var idsoin = Convert.ToInt32(item); var saUp = (from a in dblim.Tb_PlanningSO where (a.ID_salesorder == item.num) select a).FirstOrDefault(); saUp.query3 = item.sort; saUp.query4 = item.comment; dblim.Entry(saUp).State = EntityState.Modified; //Actualizamos orden en ruta try { //PUT_Invoices_api newput = new PUT_Invoices_api(); //newput.ord = 8; //var response2 = cls_invoices.PutInvoice(Convert.ToInt32(selSO.DocEntry), newput); } catch { } count++; } dblim.BulkSaveChanges(); string ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } } string result = "NO DATA"; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { string result = "ERROR: " + ex.Message; return Json(result, JsonRequestBehavior.AllowGet); } } public class MyObj_extra { public string Description { get; set; } public decimal Value { get; set; } } [HttpPost] public ActionResult SaveExtras(string id, List<MyObj_extra> objects) { string ttresult = ""; try { var idf = Convert.ToInt32(id); var listtodelete = (from a in dblim.Tb_Planning_extra where (a.ID_Route == idf) select a); dblim.BulkDelete(listtodelete); List<Tb_Planning_extra> lsttosave = new List<Tb_Planning_extra>(); foreach (var items in objects) { Tb_Planning_extra newDet = new Tb_Planning_extra(); newDet.Description = items.Description; newDet.Value = items.Value; newDet.ID_Route = idf; newDet.query1 = ""; lsttosave.Add(newDet); } dblim.BulkInsert(lsttosave); ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } catch (Exception ex) { ttresult = "ERROR: " + ex.Message; return Json(ttresult, JsonRequestBehavior.AllowGet); } } public class MyObj { public int lineNumber { get; set; } public string validated { get; set; } public string quantity { get; set; } public string uom { get; set; } public string ItemCode { get; set; } public string ItemName { get; set; } public string deleted { get; set; } } [HttpPost] public ActionResult Save_SODetails(string id, List<MyObj> objects, string idPicker, string pickername) { string ttresult = ""; try { var idf = Convert.ToInt32(id); List<Tb_PlanningSO_details> lsttosave = new List<Tb_PlanningSO_details>(); List<Tb_PlanningSO_details> lsttodelete = new List<Tb_PlanningSO_details>(); var allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I")) select a); Sys_Users activeuser = Session["activeUser"] as Sys_Users; foreach (var items in objects) { Tb_PlanningSO_details newDet = (from a in allDet where (a.Line_num == items.lineNumber && a.ItemCode == items.ItemCode) select a).FirstOrDefault(); if (newDet.query2.Contains("3")) {//Es una bonificacion //var productonormal = dblim.Tb_PlanningSO_details.Where(a => a.ID_salesorder==idf && a.ItemCode == newDet.ItemCode && !a.query2.Contains("3")).FirstOrDefault(); //if (productonormal != null) { //newDet.isvalidated = newDet.isvalidated; //newDet.query1 = productonormal.query1; newDet.Quantity = Convert.ToDecimal(items.quantity); if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; //Se agrego linea de comando para eliminar bonificaciones u otro tipo de producto //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1}", idf, items.ItemCode); } else { newDet.query1 = ""; } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_picker = idPicker; newDet.Picker_name = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; lsttosave.Add(newDet); //} } else { //newDet.ID_UOM = items.uom; //newDet.UOM = items.uom; if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; //Se agrego linea de comano para eliminar bonificaciones u otro tipo de producto dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); } else { newDet.query1 = ""; } //Evaluamos si la cantidad es menor a lo que colocaron, si es asi mandar propiedad DEL if (!newDet.query2.Contains("0")) { if (newDet.UomCode.Contains("LBS")) { } else { if (Convert.ToDecimal(items.quantity) < newDet.Quantity) { newDet.query1 = "DEL"; //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); if (newDet.type == "S") { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and parent={1}", idf, items.ItemCode); } } } } if (items.quantity == "") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else if (items.quantity == "0") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else { newDet.Quantity = Convert.ToDecimal(items.quantity); } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_picker = idPicker; newDet.Picker_name = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; //Evaluamos si es kit para actualizar sus hijos if (newDet.type == "S") { //llamamos los hijos var hijos = (from b in dblim.Tb_PlanningSO_details where (b.parent == newDet.ItemCode && b.type == "I" && b.ID_salesorder == idf) select b).ToList(); if (hijos.Count > 0) { foreach (var item in hijos) { item.query1 = newDet.query1; item.isvalidated = newDet.isvalidated; item.Quantity = Convert.ToDecimal(newDet.Quantity * item.childrendefqty); item.ID_picker = newDet.ID_picker; item.Picker_name = newDet.Picker_name; item.ID_userValidate = newDet.ID_userValidate; item.DateCheckOut = newDet.DateCheckOut; item.QC_totalCount = newDet.QC_totalCount; item.Transferred = newDet.Transferred; } dblim.BulkUpdate(hijos); } } lsttosave.Add(newDet); } //Evaluamos si el producto se eliminio para actualizar todo despues if (items.deleted == "DEL") { lsttodelete.Add(newDet); } } dblim.BulkUpdate(lsttosave); //Eliminamos por producto try { foreach (var itemdel in lsttodelete) { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, itemdel.ItemCode); } } catch { } ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } catch(Exception ex) { ttresult = "ERROR: " + ex.Message; return Json(ttresult, JsonRequestBehavior.AllowGet); } } //public int lineNumber { get; set; } //public string validated { get; set; } //public string quantity { get; set; } //public string uom { get; set; } //public string ItemCode { get; set; } //public string ItemName { get; set; } //public string deleted { get; set; } [HttpPost] public ActionResult Save_SODetailsByStorage(string id, string storage, string idPicker, string pickername) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } string ttresult = ""; try { var idf = Convert.ToInt32(id); List<MyObj> objects = new List<MyObj>(); if (storage == "COOLER") { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "FREEZER") && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "YES", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = a.query1 }).ToList(); } else if (storage == "FREEZER") { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "COOLER") && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "YES", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = a.query1 }).ToList(); } else { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && a.ID_storagetype == storage && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "YES", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = a.query1 }).ToList(); } List<Tb_PlanningSO_details> lsttosave = new List<Tb_PlanningSO_details>(); List<Tb_PlanningSO_details> lsttodelete = new List<Tb_PlanningSO_details>(); IQueryable<Tb_PlanningSO_details> allDet; if (storage == "COOLER") { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "FREEZER")) select a); } else if (storage == "FREEZER") { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "COOLER")) select a); } else { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && a.ID_storagetype == storage) select a); } foreach (var items in objects) { Tb_PlanningSO_details newDet = (from a in allDet where (a.Line_num == items.lineNumber && a.ItemCode == items.ItemCode) select a).FirstOrDefault(); if (newDet.query2.Contains("3")) {//Es una bonificacion //var productonormal = dblim.Tb_PlanningSO_details.Where(a => a.ID_salesorder==idf && a.ItemCode == newDet.ItemCode && !a.query2.Contains("3")).FirstOrDefault(); //if (productonormal != null) { //newDet.isvalidated = newDet.isvalidated; //newDet.query1 = productonormal.query1; newDet.Quantity = Convert.ToDecimal(items.quantity); if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; newDet.isvalidated = false; //Se agrego linea de comando para eliminar bonificaciones u otro tipo de producto //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1}", idf, items.ItemCode); } else { newDet.query1 = ""; } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_pickerWHS = idPicker; newDet.Picker_nameWHS = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; lsttosave.Add(newDet); //} } else { //newDet.ID_UOM = items.uom; //newDet.UOM = items.uom; if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; newDet.isvalidated = false; //Se agrego linea de comano para eliminar bonificaciones u otro tipo de producto dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); } else { newDet.query1 = ""; } //Evaluamos si la cantidad es menor a lo que colocaron, si es asi mandar propiedad DEL if (!newDet.query2.Contains("0")) { if (newDet.UomCode.Contains("LBS")) { } else { if (Convert.ToDecimal(items.quantity) < newDet.Quantity) { newDet.query1 = "DEL"; //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); if (newDet.type == "S") { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and parent={1}", idf, items.ItemCode); } } } } if (items.quantity == "") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else if (items.quantity == "0") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else { newDet.Quantity = Convert.ToDecimal(items.quantity); } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_pickerWHS = idPicker; newDet.Picker_nameWHS = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; //Evaluamos si es kit para actualizar sus hijos if (newDet.type == "S") { //llamamos los hijos var hijos = (from b in dblim.Tb_PlanningSO_details where (b.parent == newDet.ItemCode && b.type == "I" && b.ID_salesorder == idf) select b).ToList(); if (hijos.Count > 0) { foreach (var item in hijos) { item.query1 = newDet.query1; item.isvalidated = newDet.isvalidated; item.Quantity = Convert.ToDecimal(newDet.Quantity * item.childrendefqty); item.ID_picker = newDet.ID_picker; item.Picker_name = newDet.Picker_name; item.ID_userValidate = newDet.ID_userValidate; item.DateCheckOut = newDet.DateCheckOut; item.QC_totalCount = newDet.QC_totalCount; item.Transferred = newDet.Transferred; } dblim.BulkUpdate(hijos); } } lsttosave.Add(newDet); } //Evaluamos si el producto se eliminio para actualizar todo despues if (items.deleted == "DEL") { lsttodelete.Add(newDet); } } dblim.BulkUpdate(lsttosave); //Eliminamos por producto try { foreach (var itemdel in lsttodelete) { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, itemdel.ItemCode); } } catch { } ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } catch (Exception ex) { ttresult = "ERROR: " + ex.Message; return Json(ttresult, JsonRequestBehavior.AllowGet); } } [HttpPost] public ActionResult Delete_SODetailsByStorage(string id, string storage, string idPicker, string pickername) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } string ttresult = ""; try { var idf = Convert.ToInt32(id); List<MyObj> objects = new List<MyObj>(); if (storage == "COOLER") { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "FREEZER") && a.Transferred==2 && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "NO", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = "DEL" }).ToList(); } else if (storage == "FREEZER") { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "COOLER") && a.Transferred == 2 && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "NO", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = "DEL" }).ToList(); } else { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && a.ID_storagetype == storage && a.Transferred == 2 && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "NO", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = "DEL" }).ToList(); } List<Tb_PlanningSO_details> lsttosave = new List<Tb_PlanningSO_details>(); List<Tb_PlanningSO_details> lsttodelete = new List<Tb_PlanningSO_details>(); IQueryable<Tb_PlanningSO_details> allDet; if (storage == "COOLER") { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "FREEZER") && a.Transferred == 2) select a); } else if (storage == "FREEZER") { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "COOLER") && a.Transferred == 2) select a); } else { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && a.ID_storagetype == storage && a.Transferred == 2) select a); } foreach (var items in objects) { Tb_PlanningSO_details newDet = (from a in allDet where (a.Line_num == items.lineNumber && a.ItemCode == items.ItemCode) select a).FirstOrDefault(); if (newDet.query2.Contains("3")) {//Es una bonificacion //var productonormal = dblim.Tb_PlanningSO_details.Where(a => a.ID_salesorder==idf && a.ItemCode == newDet.ItemCode && !a.query2.Contains("3")).FirstOrDefault(); //if (productonormal != null) { //newDet.isvalidated = newDet.isvalidated; //newDet.query1 = productonormal.query1; newDet.Quantity = Convert.ToDecimal(items.quantity); if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; newDet.isvalidated = false; //Se agrego linea de comando para eliminar bonificaciones u otro tipo de producto //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1}", idf, items.ItemCode); } else { newDet.query1 = ""; } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_picker = idPicker; newDet.Picker_name = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; lsttosave.Add(newDet); //} } else { //newDet.ID_UOM = items.uom; //newDet.UOM = items.uom; if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; newDet.isvalidated = false; //Se agrego linea de comano para eliminar bonificaciones u otro tipo de producto dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); } else { newDet.query1 = ""; } //Evaluamos si la cantidad es menor a lo que colocaron, si es asi mandar propiedad DEL if (!newDet.query2.Contains("0")) { if (newDet.UomCode.Contains("LBS")) { } else { if (Convert.ToDecimal(items.quantity) < newDet.Quantity) { newDet.query1 = "DEL"; //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); if (newDet.type == "S") { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and parent={1}", idf, items.ItemCode); } } } } if (items.quantity == "") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else if (items.quantity == "0") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else { newDet.Quantity = Convert.ToDecimal(items.quantity); } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_picker = idPicker; newDet.Picker_name = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; //Evaluamos si es kit para actualizar sus hijos if (newDet.type == "S") { //llamamos los hijos var hijos = (from b in dblim.Tb_PlanningSO_details where (b.parent == newDet.ItemCode && b.type == "I") select b).ToList(); if (hijos.Count > 0) { foreach (var item in hijos) { item.query1 = newDet.query1; item.isvalidated = newDet.isvalidated; item.Quantity = Convert.ToDecimal(newDet.Quantity * item.childrendefqty); item.ID_picker = newDet.ID_picker; item.Picker_name = newDet.Picker_name; item.ID_userValidate = newDet.ID_userValidate; item.DateCheckOut = newDet.DateCheckOut; item.QC_totalCount = newDet.QC_totalCount; item.Transferred = newDet.Transferred; } dblim.BulkUpdate(hijos); } } lsttosave.Add(newDet); } //Evaluamos si el producto se eliminio para actualizar todo despues if (items.deleted == "DEL") { lsttodelete.Add(newDet); } } dblim.BulkUpdate(lsttosave); //Eliminamos por producto try { foreach (var itemdel in lsttodelete) { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, itemdel.ItemCode); } } catch { } ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } catch (Exception ex) { ttresult = "ERROR: " + ex.Message; return Json(ttresult, JsonRequestBehavior.AllowGet); } } [HttpPost] public ActionResult Restore_SODetailsByStorage(string id, string storage, string idPicker, string pickername) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; var company_bodega = "0"; if (activeuser.ID_Company == 1) { company_bodega = "01"; } else if (activeuser.ID_Company == 2) { company_bodega = "02"; } string ttresult = ""; try { var idf = Convert.ToInt32(id); List<MyObj> objects = new List<MyObj>(); if (storage == "COOLER") { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "FREEZER") && a.Transferred == 2 && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "NO", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = "" }).ToList(); } else if (storage == "FREEZER") { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "COOLER") && a.Transferred == 2 && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "NO", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = "" }).ToList(); } else { objects = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && a.Warehouse != company_bodega && a.ID_storagetype == storage && a.Transferred == 2 && !a.type.Contains("I")) select new MyObj { ItemCode = a.ItemCode, ItemName = a.ItemName, lineNumber = a.Line_num, validated = "NO", quantity = a.Quantity.ToString(), uom = a.UomCode, deleted = "" }).ToList(); } List<Tb_PlanningSO_details> lsttosave = new List<Tb_PlanningSO_details>(); List<Tb_PlanningSO_details> lsttodelete = new List<Tb_PlanningSO_details>(); IQueryable<Tb_PlanningSO_details> allDet; if (storage == "COOLER") { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "FREEZER") && a.Transferred == 2) select a); } else if (storage == "FREEZER") { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && (a.ID_storagetype == storage || a.ID_storagetype == "COOLER") && a.Transferred == 2) select a); } else { allDet = (from a in dblim.Tb_PlanningSO_details where (a.ID_salesorder == idf && !a.type.Contains("I") && a.Warehouse != company_bodega && a.ID_storagetype == storage && a.Transferred == 2) select a); } foreach (var items in objects) { Tb_PlanningSO_details newDet = (from a in allDet where (a.Line_num == items.lineNumber && a.ItemCode == items.ItemCode) select a).FirstOrDefault(); if (newDet.query2.Contains("3")) {//Es una bonificacion //var productonormal = dblim.Tb_PlanningSO_details.Where(a => a.ID_salesorder==idf && a.ItemCode == newDet.ItemCode && !a.query2.Contains("3")).FirstOrDefault(); //if (productonormal != null) { //newDet.isvalidated = newDet.isvalidated; //newDet.query1 = productonormal.query1; newDet.Quantity = Convert.ToDecimal(items.quantity); if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; newDet.isvalidated = false; //Se agrego linea de comando para eliminar bonificaciones u otro tipo de producto //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1}", idf, items.ItemCode); } else { newDet.query1 = ""; } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_picker = idPicker; newDet.Picker_name = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; lsttosave.Add(newDet); //} } else { //newDet.ID_UOM = items.uom; //newDet.UOM = items.uom; if (items.validated == "YES") { newDet.isvalidated = true; } else { newDet.isvalidated = false; } if (items.deleted == "DEL") { newDet.query1 = "DEL"; newDet.isvalidated = false; //Se agrego linea de comano para eliminar bonificaciones u otro tipo de producto dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); } else { newDet.query1 = ""; } //Evaluamos si la cantidad es menor a lo que colocaron, si es asi mandar propiedad DEL if (!newDet.query2.Contains("0")) { if (newDet.UomCode.Contains("LBS")) { //No se evalua ya que la cantidad puede tender a fallar por los decimales } else { if (Convert.ToDecimal(items.quantity) < newDet.Quantity) { newDet.query1 = "DEL"; //dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, items.ItemCode); if (newDet.type == "S") { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and parent={1}", idf, items.ItemCode); } } } } if (items.quantity == "") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else if (items.quantity == "0") { newDet.Quantity = 0; newDet.query1 = "DEL"; } else { newDet.Quantity = Convert.ToDecimal(items.quantity); } var lstava = (from a in dlipro.OpenSalesOrders_DetailsUOM where (a.ItemCode == items.ItemCode && a.UomCode == items.uom) select a).FirstOrDefault(); if (lstava != null) { newDet.UomCode = lstava.UomCode; newDet.UomEntry = lstava.UomEntry.ToString(); newDet.NumPerMsr = Convert.ToDecimal(lstava.Units); } newDet.ID_picker = idPicker; newDet.Picker_name = pickername; if (activeuser != null) { newDet.ID_userValidate = activeuser.ID_User; } newDet.DateCheckOut = DateTime.UtcNow; //Evaluamos si es kit para actualizar sus hijos if (newDet.type == "S") { //llamamos los hijos var hijos = (from b in dblim.Tb_PlanningSO_details where (b.parent == newDet.ItemCode && b.type == "I") select b).ToList(); if (hijos.Count > 0) { foreach (var item in hijos) { item.query1 = newDet.query1; item.isvalidated = newDet.isvalidated; item.Quantity = Convert.ToDecimal(newDet.Quantity * item.childrendefqty); item.ID_picker = newDet.ID_picker; item.Picker_name = newDet.Picker_name; item.ID_userValidate = newDet.ID_userValidate; item.DateCheckOut = newDet.DateCheckOut; item.QC_totalCount = newDet.QC_totalCount; item.Transferred = newDet.Transferred; } dblim.BulkUpdate(hijos); } } lsttosave.Add(newDet); } //Evaluamos si el producto se eliminio para actualizar todo despues if (items.deleted == "DEL") { lsttodelete.Add(newDet); } } dblim.BulkUpdate(lsttosave); //Eliminamos por producto try { foreach (var itemdel in lsttodelete) { dblim.Database.ExecuteSqlCommand("update Tb_PlanningSO_details set query1='DEL' where ID_salesorder={0} and ItemCode={1} and Quantity > 0", idf, itemdel.ItemCode); } } catch { } ttresult = "SUCCESS"; return Json(ttresult, JsonRequestBehavior.AllowGet); } catch (Exception ex) { ttresult = "ERROR: " + ex.Message; return Json(ttresult, JsonRequestBehavior.AllowGet); } } public ActionResult Print_Roadmap(int? id) { var header = (from b in dblim.Tb_Planning where (b.ID_Route == id) select b).FirstOrDefault(); //var details = dblim.Tb_PlanningSO.Where(g => g.ID_Route==id).GroupBy(x => x.Customer_name).Select(g => g.FirstOrDefault()).OrderBy(c=>c.query3); var details = dblim.Tb_PlanningSO.Where(g => g.ID_Route==id).OrderBy(c=>c.query3).ToList(); details = details.GroupBy(x => x.Customer_name).Select(g => g.FirstOrDefault()).OrderBy(c => c.query3).ToList(); foreach (var item in details) { //Agregamos el payment method var customer = (from a in dlipro.BI_Dim_Customer where (a.id_Customer == item.ID_customer) select a).FirstOrDefault(); if (customer != null) { item.query5 = customer.PymntGroup; } } //INFO UOM var listafinalSO = details.ToList(); var sol = listafinalSO.Select(c => c.ID_salesorder).ToArray(); //Verificamos detalles para sacar CASE y EACH totales y luego promediar todal de EACH en base a CASES var detallesSo = (from f in dblim.Tb_PlanningSO_details where (sol.Contains(f.ID_salesorder)) select f).ToList(); var totalCantEach = 0; var totalCantCases = 0; var totalCantPack = 0; var totalCantLbs = 0; //Para calcular el promedio lo hacemos diviendo try { if (detallesSo.Count() > 0) { totalCantEach = detallesSo.Where(c => c.UomCode.Contains("EACH")).Count(); totalCantCases = detallesSo.Where(c => c.UomCode.Contains("CASE")).Count(); totalCantPack = detallesSo.Where(c => c.UomCode.Contains("PACK")).Count(); totalCantLbs = detallesSo.Where(c => c.UomCode.Contains("LBS")).Count(); } else { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; } } catch { totalCantEach = 0; totalCantCases = 0; totalCantPack = 0; totalCantLbs = 0; } ReportDocument rd = new ReportDocument(); rd.Load(Path.Combine(Server.MapPath("~/Reports"), "rptRoadmap.rpt")); rd.SetDataSource(details); rd.SetParameterValue("Route", header.Route_name.ToUpper()); rd.SetParameterValue("Driver", header.Driver_name); rd.SetParameterValue("Route_leader", header.Routeleader_name); rd.SetParameterValue("Truck", header.Truck_name); rd.SetParameterValue("Date", header.Date.ToLongDateString().ToUpper()); rd.SetParameterValue("totalEach", totalCantEach.ToString()); rd.SetParameterValue("totalCase", totalCantCases.ToString()); rd.SetParameterValue("totalPack", totalCantPack.ToString()); rd.SetParameterValue("totalLBS", totalCantLbs.ToString()); //rd.SetParameterValue("idorder", header.ID_OrderDSD); //rd.SetParameterValue("comment", header.Comment); var filePathOriginal = Server.MapPath("/Reports/pdf"); Response.Buffer = false; Response.ClearContent(); Response.ClearHeaders(); //PARA VISUALIZAR Response.AppendHeader("Content-Disposition", "inline; filename=" + "RoadMap.pdf; "); Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); stream.Seek(0, SeekOrigin.Begin); return File(stream, System.Net.Mime.MediaTypeNames.Application.Pdf); } public ActionResult Route_WHSInvoices(string activityname) { // retrieve byte array here List<byte[]> myStream = TempData["Output"] as List<byte[]>; //var filePathOriginal = Server.MapPath("/Reports/pdf"); //var path2 = Path.Combine(filePathOriginal, "Route_WHSInvoices.pdf"); var report = concatAndAddContent(myStream); if (report != null) { //Con eso se descarga //Response.AddHeader("Content-Disposition", "attachment; filename=" + "Route_WHSInvoices.pdf"); return File(report, System.Net.Mime.MediaTypeNames.Application.Pdf); } else { return new EmptyResult(); } } public ActionResult DailyPaymentCrossDock(string activityname) { // retrieve byte array here List<byte[]> myStream = TempData["Output"] as List<byte[]>; //var filePathOriginal = Server.MapPath("/Reports/pdf"); //var path2 = Path.Combine(filePathOriginal, "Route_WHSInvoices.pdf"); var report = concatAndAddContent(myStream); if (report != null) { //Con eso se descarga //Response.AddHeader("Content-Disposition", "attachment; filename=" + "Route_WHSInvoices.pdf"); return File(report, System.Net.Mime.MediaTypeNames.Application.Pdf); } else { return new EmptyResult(); } } public ActionResult Print_routeWHS(int id_route) { try { //Se actualizo formato de reporte el 07/23/2020 var so = (from a in dblim.Tb_PlanningSO where (a.ID_Route == id_route && a.DocEntry !="--") select a).ToList(); //var quemadosSO = new List<string>(); //quemadosSO.Add("78492"); //quemadosSO.Add("78497"); if (so.Count > 0) { //Aca iria ciclo foreach MemoryStream finalStream = new MemoryStream(); //PdfCopyFields copy = new PdfCopyFields(finalStream); List<byte[]> listafinal = new List<byte[]>(); foreach (var item in so) { //Buscamos datos en la vista maestra de facturas var sqlQueryText = dlipro.sp_genericInvoice(item.DocEntry.ToString()).ToList(); //var sqlQueryText = dlipro.sp_genericInvoiceV2(item.DocEntry.ToString()).ToList(); //List<sp_genericInvoiceV2_kit_Result> lstkit = new List<sp_genericInvoiceV2_kit_Result>(); foreach (var iteminterno in sqlQueryText) { iteminterno.UomCode = ""; //var sqlQuerySubReport = dlipro.sp_genericInvoiceV2_kit(item.DocEntry.ToString(), iteminterno.ItemCode).ToList(); //if (sqlQuerySubReport.Count > 0) //{ // lstkit.AddRange(sqlQuerySubReport); //} } //Buscamos en subreporte kit (07/23/2020) ReportDocument rd = new ReportDocument(); //rd.Load(Path.Combine(Server.MapPath("~/Reports"), "Invoces Nuevo.rpt")); rd.Load(Path.Combine(Server.MapPath("~/Reports"), "Invoice Storage Type (RR).rpt")); rd.DataSourceConnections.Clear(); //rd.Subreports[0].SetDataSource(lstkit); rd.SetDataSource(sqlQueryText); //ConnectionInfo connectInfo = new ConnectionInfo() //{ // //ServerName = ".", // //DatabaseName = "DLI_PRO", // //UserID = "sa", // //Password = "sa123" // ServerName = "192.168.1.14", // DatabaseName = "PEPPERI_TEST", // UserID = "sa", // Password = "DiLimen@2018" //}; //rd.SetDatabaseLogon("sa", "DiLimen@2018", "192.168.1.14", "PEPPERI_TEST"); //foreach (Table tbl in rd.Database.Tables) //{ // tbl.LogOnInfo.ConnectionInfo = connectInfo; // tbl.ApplyLogOnInfo(tbl.LogOnInfo); //} //var filePathOriginal = Server.MapPath("/Reports/pdf"); Response.Buffer = false; Response.ClearContent(); Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", "inline; filename=Route_WHSInvoices.pdf;"); byte[] getBytes = null; Stream ms = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); ms.Seek(0, SeekOrigin.Begin); getBytes = ReadFully(ms); listafinal.Add(getBytes); //para sacar la copia listafinal.Add(getBytes); ms.Dispose(); //var path2 = Path.Combine(filePathOriginal, id_route + "Route_WHSInvoices.pdf"); //rd.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, path2); //var ms1 = new MemoryStream(getBytes); //ms1.Position = 0; //copy.AddDocument(new PdfReader(ms1)); //ms1.Dispose(); //PARA VISUALIZAR //Response.AppendHeader("Content-Disposition", "inline; filename=Route_WHSInvoices.pdf;"); //Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); //stream.Seek(0, SeekOrigin.Begin); //stream.Position = 0; //copy.AddDocument(new PdfReader(stream)); //stream.Dispose(); } //Nueva descarga TempData["Output"] = listafinal; //return Json(urlcontent); return Json("Success", JsonRequestBehavior.AllowGet); } else { return Json("CountError", JsonRequestBehavior.AllowGet); } } catch (Exception ex) { //return Json(urlcontent); return Json("Error: " + ex.Message, JsonRequestBehavior.AllowGet); } } public ActionResult Print_WHSDailyPayment(int id_route) { try { var so = (from a in dblim.Tb_Planning where (a.ID_Route == id_route) select a).FirstOrDefault(); //var quemadosSO = new List<string>(); //quemadosSO.Add("78492"); //quemadosSO.Add("78497"); if (so !=null) { //Aca iria ciclo foreach MemoryStream finalStream = new MemoryStream(); //PdfCopyFields copy = new PdfCopyFields(finalStream); List<byte[]> listafinal = new List<byte[]>(); //Buscamos datos en la vista maestra de facturas var dateshor = so.Departure.ToShortDateString(); var sqlQueryText = dlipro.sp_genericDailyPaymentsCrossDock(so.ID_truck, dateshor).ToList(); foreach (var item in sqlQueryText) { if (item.RouteLeader == null) { item.RouteLeader = ""; } if (item.Driver == null) { item.Driver = ""; } } ReportDocument rd = new ReportDocument(); rd.Load(Path.Combine(Server.MapPath("~/Reports"), "Daily Payments Add Copies - Whs 01 & 02.rpt")); rd.SetDataSource(sqlQueryText); rd.SetParameterValue("Date", so.Departure.ToShortDateString()); rd.SetParameterValue("Truck", so.ID_truck); Response.Buffer = false; Response.ClearContent(); Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", "inline; filename=DailyPaymentCrossDock.pdf;"); byte[] getBytes = null; Stream ms = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); ms.Seek(0, SeekOrigin.Begin); getBytes = ReadFully(ms); listafinal.Add(getBytes); //para sacar la copia //listafinal.Add(getBytes); ms.Dispose(); //Nueva descarga TempData["Output"] = listafinal; //return Json(urlcontent); return Json("Success", JsonRequestBehavior.AllowGet); } else { return Json("CountError", JsonRequestBehavior.AllowGet); } } catch (Exception ex) { //return Json(urlcontent); return Json("Error: " + ex.Message, JsonRequestBehavior.AllowGet); } } public ActionResult Print_DPCD(int id_route) { var so = (from a in dblim.Tb_Planning where (a.ID_Route == id_route) select a).FirstOrDefault(); if (so !=null) { var dateshor = so.Departure.ToShortDateString(); var sqlQueryText = dlipro.sp_genericDailyPaymentsCrossDock(so.ID_truck, dateshor).ToList(); var containers = (from c in dblim.Tb_logContainers where (c.ID_Route == so.ID_Route) select c.ID_container).ToArray(); var result = string.Join(",", containers); if (sqlQueryText.Count > 0) { foreach (var item in sqlQueryText) { if (item.RouteLeader == null) { item.RouteLeader = ""; } if (item.Driver == null) { item.Driver = ""; } } ReportDocument rd = new ReportDocument(); rd.Load(Path.Combine(Server.MapPath("~/Reports"), "Daily Payments Add Copies - Whs 01 & 02.rpt")); rd.SetDataSource(sqlQueryText); rd.Database.Tables[0].SetDataSource(sqlQueryText); var filePathOriginal = Server.MapPath("/Reports/pdfReports"); Response.Buffer = false; Response.ClearContent(); Response.ClearHeaders(); //PARA VISUALIZAR Response.AppendHeader("Content-Disposition", "inline; filename=" + "DailyPaymentCrossDock.pdf; "); rd.SetParameterValue("Date", so.Departure); rd.SetParameterValue("Containers", result); rd.SetParameterValue("Truck", so.ID_truck); rd.SetParameterValue("DRoute", so.Route_name); rd.SetParameterValue("IDrouteazure", so.ID_Route); rd.SetParameterValue("DateString", so.Departure.ToShortDateString()); Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); stream.Seek(0, SeekOrigin.Begin); return File(stream, System.Net.Mime.MediaTypeNames.Application.Pdf); } else { TempData["advertencia"] = "No details found."; return RedirectToAction("QualityControl_planning", "Invoices", null); } } else { TempData["advertencia"] = "No data found."; return RedirectToAction("QualityControl_planning", "Invoices", null); } } public static byte[] ReadFully(Stream input) { using (MemoryStream ms = new MemoryStream()) { input.CopyTo(ms); return ms.ToArray(); } } private static Byte[] ConvertList(List<Byte[]> list) { List<Byte> tmpList = new List<byte>(); foreach (Byte[] byteArray in list) foreach (Byte singleByte in byteArray) tmpList.Add(singleByte); return tmpList.ToArray(); } public static byte[] concatAndAddContent(List<byte[]> pdf) { byte[] all; using (MemoryStream ms = new MemoryStream()) { Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, ms); doc.SetPageSize(PageSize.LETTER); doc.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; PdfReader reader; foreach (byte[] p in pdf) { reader = new PdfReader(p); int pages = reader.NumberOfPages; // loop over document pages for (int i = 1; i <= pages; i++) { doc.SetPageSize(PageSize.LETTER); doc.NewPage(); page = writer.GetImportedPage(reader, i); cb.AddTemplate(page, 0, 0); } } doc.Close(); all = ms.GetBuffer(); ms.Flush(); ms.Dispose(); } return all; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AmmoCounter : MonoBehaviour { public Text ammoDisplay; public GameObject arm; private Weapon WeaponClip; void Awake() { WeaponClip = arm.GetComponent<Weapon>(); } // Update is called once per frame private void FixedUpdate() { ammoDisplay.text = (WeaponClip.clipSize).ToString() + "/" + (WeaponClip.clipSizeReal).ToString(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Simon.Controls; using Simon.Helpers; using Simon.Models; using Simon.ServiceHandler; using Simon.ViewModel; using Xamarin.Forms; using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; using Application = Xamarin.Forms.Application; namespace Simon.Views { public partial class LandingPage : GradientColorStack { private LandingViewModel ViewModel = null; public LandingPage() { InitializeComponent(); } protected async override void OnAppearing() { base.OnAppearing(); App.ReadUnread = "null"; App.OrderByText = Constants.LastPostDateText; App.SelectedTitle = string.Empty; var leftSwipeGesture = new SwipeGestureRecognizer { Direction = SwipeDirection.Left }; if (Application.Current.Properties.ContainsKey("NAME")) { var name = Convert.ToString(Application.Current.Properties["NAME"]); txtName.Text = App.SelectedUserData.name; } //_headerList.Add(new LandingModel { Date = "Date", Borrower = "Borrower", Amount = "Amount" }); //headerList.ItemsSource = _headerList; ViewModel = new LandingViewModel(); this.BindingContext = ViewModel; if (NetworkCheck.IsInternet()) { await ViewModel.FetchClosingData(); //await ViewModel.FetchDecisionDueData(); } else { await DisplayAlert("Simon", "No network is available.", "OK"); } } private void onDealBtnClicked(object sender, EventArgs e) { Navigation.PushAsync(new DealsPage()); } private void onApproveBtnClicked(object sender, EventArgs e) { Navigation.PushAsync(new AssentMainPage()); } private void onPortfolioBtnClicked(object sender, EventArgs e) { // Navigation.PushAsync(new MessageThreadPage()); } private void onMessagesBtnClicked(object sender, EventArgs e) { Navigation.PushAsync(new MessagesPage()); } private void onAlertBtnClicked(object sender, EventArgs e) { // Navigation.PushAsync(new MessageMainPage()); } void SwipeGestureRecognizer_Swiped(System.Object sender, Xamarin.Forms.SwipedEventArgs e) { ViewModel.FooterNavigation(SessionService.BaseFooterItems[1]); } } }
namespace School.Tests { using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using School.Models; using School.Contracts; [TestClass] public class SchoolTest { [TestMethod] public void SchoolConstructor_ShouldMakeInstanceOf_CollectionOfCourses() { var school = new School("name"); Assert.IsInstanceOfType(school.CoursesList, typeof(List<ICourse>)); } [TestMethod] public void SchoolConstructor_ShouldMakeInstanceOf_CollectionOfStudents() { var school = new School("name"); Assert.IsInstanceOfType(school.StudentsInSchoolList, typeof(List<IStudent>)); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void School_WithNameNull_ShouldThrowAnException() { var school = new School(null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void School_WithNameStringEmpty_ShoulThrowAnException() { var school = new School(""); } [TestMethod] public void School_ShouldProperlySetName() { var expected = "EG Best School ever"; var school = new School(expected); Assert.AreEqual(expected, school.SchoolName); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void AddingStudentsWithSameNumberShouldThrow() { var school = new School("PMG Vasil Levski"); var student1 = new Student("Ceko Cekov", 10001); var student2 = new Student("Boiko Borisov", 10001); school.AddStudent(student1); school.AddStudent(student2); } } }
using System; namespace certificacao_csharp_programming { class Program { static void Main(string[] args) { TiposDeValor tipos = new TiposDeValor(); // tipos.Executar(); Inteiros inteiros = new Inteiros(); // inteiros.Executar(); PontoFlutuante pontoFlutuante = new PontoFlutuante(); // pontoFlutuante.Executar(); Decimal dec = new Decimal(); // dec.Executar(); Booleanos booleanos = new Booleanos(); // booleanos.Executar(); Estruturas estruturas = new Estruturas(); // estruturas.Executar(); Enumeracoes enumeracoes = new Enumeracoes(); // enumeracoes.Executar(); TiposDeReferencia tiposDeReferencia = new TiposDeReferencia(); // tiposDeReferencia.Executar(); Classes classes = new Classes(); // classes.Executar(); Interfaces interfaces = new Interfaces(); // interfaces.Executar(); Delegates delegates = new Delegates(); // delegates.Executar(); Objetos objetos = new Objetos(); // objetos.Executar(); Dinamicos dinamicos = new Dinamicos(); // dinamicos.Executar(); Strings strings = new Strings(); strings.Executar(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace db_project { public static class Extentions { public static bool IsNumber(this string s) { if (s.Length == 0) return false; for (int i = 0; i < s.Length; i++) if (s[i] < '0' || s[i] > '9') return false; return true; } } }
using Euler_Logic.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem70 : ProblemBase { private PrimeSieve _primes; public override string ProblemName { get { return "70: Totient permutation"; } } /* According to the wiki on euler's totient function (https://en.wikipedia.org/wiki/Euler%27s_totient_function), if the prime factors of (n) are (p1, p2, p3...pr), then the totient value can be calculated: n(1 - (1/p1))(1 - (1/p2))...(1 - (1/pr)). So what I do is create a starting fraction for all numbers up to 1000000. Then I loop through all prime numbers, and for each prime number, I multiply all of its composites by (p - 1)/p. That will give me the totient value for all numbers. I then just loop through them all to find which ones return a permutation, and of those return the one with the lowest value n/t(n). */ public override string GetAnswer() { ulong max = 10000000; _primes = new PrimeSieve(max); BuildFractions(max); FindTotients(max); return FindLowestPermutation(max).ToString(); } private Dictionary<ulong, Fraction> _fractions = new Dictionary<ulong, Fraction>(); private void BuildFractions(ulong max) { for (ulong num = 2; num <= max; num++) { _fractions.Add(num, new Fraction(num, 1)); } } private void FindTotients(ulong max) { foreach (var prime in _primes.Enumerate) { for (ulong composite = 1; composite * prime <= max; composite++) { _fractions[composite * prime].Multiply(prime - 1, prime); } } } private ulong FindLowestPermutation(ulong max) { ulong lowestNum = 0; decimal lowestValue = decimal.MaxValue; for (ulong num = 4; num <= max; num++) { var fract = _fractions[num]; if (IsPermutation(num, fract.X)) { decimal value = (decimal)num / (decimal)fract.X; if (value < lowestValue) { lowestValue = value; lowestNum = num; } } } return lowestNum; } private bool IsPermutation(ulong num1, ulong num2) { string x = num1.ToString(); string y = num2.ToString(); for (int index = 0; index < x.Length; index++) { if (x.Replace(x.Substring(index, 1), "").Length != y.Replace(x.Substring(index, 1), "").Length) { return false; } } return true; } } }
using System; using System.Collections.Generic; using System.Text; using Hayaa.BaseModel; using Hayaa.CacheKeyStatic; using Hayaa.Redis.Client; using Hayaa.Security.Service.Config; using Hayaa.Security.Service.Dao; namespace Hayaa.Security.Service.Core { public partial class LoginServer { private string Encryption(string pwd) { return pwd; } private string GetToken() { return Guid.NewGuid().ToString().Replace("-", ""); } /// <summary> /// TODO /// 获取jobid /// </summary> /// <param name="userId"></param> /// <returns></returns> private int GetJobId(int userId) { return 1; } } }
using System; using System.Collections.Generic; using System.Text; namespace alg.src.leetcode._900 { class Lc903_Valid_Permutations_for_DI_Sequence { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Genesys.WebServicesClient { public class OpenFailedException : Exception { public OpenFailedException(string message, Exception innerException) : base(message, innerException) { } public OpenFailedException(string message) : this(message, null) { } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace SmartHome.Model { public class User { [JsonProperty("userId")] public string userId { get; set; } [JsonProperty("apps")] public List<Apps> apps { get; set; } [JsonProperty("houses")] public List<House> houses { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("scopes")] public List<Scopes> scopes { get; set; } [JsonProperty("deviceId")] public string deviceId { get; set; } [JsonProperty("tenantId")] public string tenantId { get; set; } [JsonProperty("username")] public string username { get; set; } [JsonProperty("password")] public string password { get; set; } [JsonProperty("mobile")] public string mobile { get; set; } [JsonProperty("email")] public string email { get; set; } [JsonProperty("address")] public string address { get; set; } [JsonProperty("active")] public bool active { get; set; } [JsonProperty("accessToken")] public string accessToken { get; set; } } }
using System.Diagnostics; using Android.Content; using Theatre.Droid.DependecyServices; using Theatre.Services; using Xamarin.Forms; using System; using System.Net.Http; using System.Threading.Tasks; using Java.IO; [assembly: Dependency(typeof(CostomLoadPDF))] namespace Theatre.Droid.DependecyServices { public class CostomLoadPDF : IFileWorker { public void DownloadPDF(string name, byte[] pfdArray) { //var directory = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; //directory = System.IO.Path.Combine(directory, Android.OS.Environment.DirectoryDownloads); var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads); string filePath = System.IO.Path.Combine(directory.ToString(), name); System.IO.File.WriteAllBytes(filePath, pfdArray); //using (System.IO.StreamWriter writer = System.IO.File.WriteAllBytes(filePath)) //{ // await writer.wr(pfdArray); //} var localImage = new Java.IO.File(filePath); if (localImage.Exists()) { global::Android.Net.Uri uri = global::Android.Net.Uri.FromFile(localImage); var intent = new Intent(Intent.ActionView, uri); intent.SetDataAndType(global::Android.Net.Uri.FromFile(localImage), "application/pdf"); Forms.Context.StartActivity(intent); } } public async void ShowPdfFile() { string value = ("http://www.axmag.com/download/pdfurl-guide.pdf"); Uri baseUri = new Uri(value); HttpClientHandler clientHandler = new HttpClientHandler(); // clientHandler.CookieContainer.Add (baseUri, new Cookie ("Cookie", cookie)); HttpClient httpClient = new HttpClient(clientHandler); httpClient.BaseAddress = baseUri; byte[] imageBytes = await httpClient.GetByteArrayAsync(baseUri); string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string localFilename = "aa.pdf"; string localPath = System.IO.Path.Combine(documentsPath, localFilename); System.IO.File.WriteAllBytes(localPath, imageBytes); // writes to local storage var localImage = new Java.IO.File(localPath); if (localImage.Exists()) { global::Android.Net.Uri uri = global::Android.Net.Uri.FromFile(localImage); var intent = new Intent(Intent.ActionView, uri); // intent.SetType ("application/pdf"); intent.SetDataAndType(global::Android.Net.Uri.FromFile(localImage), "application/pdf"); Forms.Context.StartActivity(intent); } //Debug.WriteLine("TYT"); //var fileLocation = "file.pdf"; //var file = new File(fileLocation); //if (!file.Exists()) //{ // Debug.WriteLine("NET"); // return; //} //var intent = DisplayPdf(file); //Forms.Context.StartActivity(intent); } public Intent DisplayPdf(File file) { //Debug.WriteLine("AAA"); //var intent = new Intent(Intent.ActionView); //var filepath = Uri.FromFile(file); //intent.SetDataAndType(filepath, "application/pdf"); //intent.SetFlags(ActivityFlags.ClearTop); //return intent; return null; } } }
using UnityEngine; namespace DChild.Gameplay.Physics { [System.Serializable] public class LinearDrag : ILinearDrag { [SerializeField] [Range(0f, 1f)] private float m_x; [SerializeField] [Range(0f, 1f)] private float m_y; public float x { get { return m_x; } set { m_x = Restrict(value); } } public float y { get { return m_y; } set { m_y = Restrict(value); } } public float SetX { set { m_x = value; } } public float SetY { set { m_y = value; } } public void AddDrag(float x = float.NaN, float y = float.NaN) { if (!float.IsNaN(x)) { m_x = Mathf.Min(1, m_x + x); } if (!float.IsNaN(y)) { m_y = Mathf.Min(1, m_y + y); } } public void ReduceDrag(float x = float.NaN, float y = float.NaN) { if (!float.IsNaN(x)) { m_x = Mathf.Max(0, m_x - x); } if (!float.IsNaN(y)) { m_y = Mathf.Max(0, m_y - y); } } public Vector2 ApplyDrag(Vector2 velocity) { velocity.x -= velocity.x * m_x; velocity.y -= velocity.y * m_y; return velocity; } private float Restrict(float value) => Mathf.Max(0, Mathf.Min(1, value)); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using Pathfinding.Serialization.JsonFx; using System.IO; using System.Text; using System.Linq; using System; using System.Text.RegularExpressions; public class GameDatabase : Singleton<GameDatabase> { [System.Serializable] public enum CharacterName { Felix, Garet, Jenna, Gnome, Rat } [System.Serializable] public enum LocationName { None, WorldMap, ShamanVillage, TownB, DungeonAAA, DungeonB } [System.Serializable] public class FullDatabase { public List<UseableItem> UseableItem; public List<Equipment> Equipment; public List<GameCharacter> Character; public List<Monster> Monster; public List<Location> Location; } [System.Serializable] public class Helmet { public string ItemName; public int ItemID; public string ItemDescription; public int ItemPrice; public int defend; } [System.Serializable] public class BodyArmor { public string ItemName; public int ItemID; public string ItemDescription; public int ItemPrice; public int defend; public int hpIncrement; } [System.Serializable] public class GameCharacter { public string CharacterName; public int CharacterID; public List<string> CharacterDialogList; public CharacterStatList CharacterStats; } [System.Serializable] public class CharacterStatList { public List<int> ExpToNextLevel; public List<int> Def; public List<int> MDef; public List<int> Hp; public List<int> Tp; public List<int> Str; public List<int> Int; public List<int> Stam; public List<int> Acc; public List<int> Eva; public List<int> Spd; public List<int> Luck; } [System.Serializable] public class Location { public string Name; public List<Shop> Shop; public List<int> Npc; public List<int> Monsters; } [System.Serializable] public class Shop { public int NpcID; public int ShopType; public List<int> Product; } [System.Serializable] public class CharacterStatPack { public int ExpToNextLevel; public int Def; public int MDef; public int Hp; public int Tp; public int Str; public int Int; public int Stam; public int Acc; public int Eva; public int Spd; public int Luck; public CharacterStatPack (int _expToNextLvl, int _def, int _mdef, int _hp, int _tp, int _str, int _int , int _stam, int _acc, int _eva, int _spd, int _luck) { ExpToNextLevel = _expToNextLvl; Def = _def; MDef = _mdef; Hp = _hp; Tp = _tp; Str = _str; Int = _int; Stam = _stam; Acc = _acc; Eva = _eva; Spd = _spd; Luck = _luck; } } public string fileName; public string txtString; public FullDatabase fullDatabase; public Dictionary<LocationName, string> locationSceneDictionary = new Dictionary<LocationName, string> { {LocationName.DungeonAAA,"Air's Rock"}, {LocationName.ShamanVillage,"Shaman Village"} }; // Use this for initialization void Start () { ReadDatabaseJsonText (); //foreach(HelmetInfo helmInfo in fullDatabase.ItemInfo[0].HelmetInfo) // Debug.Log(helmInfo.ItemName + helmInfo.ItemDescription + helmInfo.defend); //foreach(BodyArmorInfo bodyArmorInfo in fullDatabase.ItemInfo[0].BodyArmorInfo) // Debug.Log(bodyArmorInfo.ItemName + bodyArmorInfo.ItemDescription + bodyArmorInfo.defend + bodyArmorInfo.hpIncrement); fullDatabase = JsonReader.Deserialize<FullDatabase> (txtString); fullDatabase.Equipment = new List<Equipment> (); fullDatabase.UseableItem = new List<UseableItem> (); LoadItemDatabaseData (); PartyManager.Instance.StartPartyManager (); } void LoadItemDatabaseData () { loadHelmetData (); loadBodyArmorData (); loadUseableItemData (); } public TextAsset jsonStructure; // load json file into json format void ReadDatabaseJsonText () { try { string tempLine; // Create a new StreamReader, tell it which file to read and what encoding the file // was saved as StreamReader theReader = new StreamReader (fileName, Encoding.Default); // Immediately clean up the reader after this block of code is done. // You generally use the "using" statement for potentially memory-intensive objects // instead of relying on garbage collection. // (Do not confuse this with the using directive for namespace at the // beginning of a class!) using (theReader) { // While there's lines left in the text file, do this: do { tempLine = theReader.ReadLine (); tempLine = tempLine.Replace ("\t", ""); //Debug.Log(tempLine); if (tempLine != null) { // Do whatever you need to do with the text line, it's a string now // In this example, I split it into arguments based on comma // deliniators, then send that array to DoStuff() //string[] entries = line.Split(','); //if (entries.Length > 0) // DoStuff(entries); txtString += tempLine; } } while (tempLine != null); // Done reading, close the reader and return true to broadcast success theReader.Close (); return; } } // If anything broke in the try block, we throw an exception with information // on what didn't work catch (Exception e) { Console.WriteLine ("{0}\n", e.Message); return; } //txtString = jsonStructure.text; } public TextAsset helmetInfoCsv; void loadHelmetData () { string [] records = helmetInfoCsv.text.Split ('\n'); for (int i = 0; i < records.Length; i++) { if (i != 0) { string [] data = records [i].Split (','); string Name = data [1]; string Description = data [2]; int Id, Price, Def, MDef, Hp, Tp, Str, Int, Stam, Acc, Eva, Spd, Luck; int.TryParse (data [0], out Id); int.TryParse (data [3], out Price); int.TryParse (data [4], out Def); int.TryParse (data [5], out MDef); int.TryParse (data [6], out Hp); int.TryParse (data [7], out Tp); int.TryParse (data [8], out Str); int.TryParse (data [9], out Int); int.TryParse (data [10], out Stam); int.TryParse (data [11], out Acc); int.TryParse (data [12], out Eva); int.TryParse (data [13], out Spd); int.TryParse (data [14], out Luck); Equipment newEquipment = new Equipment (Id, Name, Description, Equipment.EquipmentType.Helmets, Price, Def, MDef , Hp, Tp, Str, Int, Stam, Acc, Eva, Spd, Luck); //fullDatabase.UseableItem[0].Helmet.Add(newHelmetInfo); fullDatabase.Equipment.Add (newEquipment); } } Debug.Log ("helmet info loaded"); } public TextAsset bodyArmorInfoCsv; void loadBodyArmorData () { string [] records = bodyArmorInfoCsv.text.Split ('\n'); for (int i = 0; i < records.Length; i++) { if (i != 0) { string [] data = records [i].Split (','); string Name = data [1]; string Description = data [2]; int Id, Price, Def, MDef, Hp, Tp, Str, Int, Stam, Acc, Eva, Spd, Luck; int.TryParse (data [0], out Id); int.TryParse (data [3], out Price); int.TryParse (data [4], out Def); int.TryParse (data [5], out MDef); int.TryParse (data [6], out Hp); int.TryParse (data [7], out Tp); int.TryParse (data [8], out Str); int.TryParse (data [9], out Int); int.TryParse (data [10], out Stam); int.TryParse (data [11], out Acc); int.TryParse (data [12], out Eva); int.TryParse (data [13], out Spd); int.TryParse (data [14], out Luck); Equipment newEquipment = new Equipment (Id, Name, Description, Equipment.EquipmentType.BodyArmors, Price, Def, MDef , Hp, Tp, Str, Int, Stam, Acc, Eva, Spd, Luck); //fullDatabase.UseableItem[0].BodyArmor.Add(newBodyArmorInfo); fullDatabase.Equipment.Add (newEquipment); } } Debug.Log ("bodyArmor info loaded"); } public TextAsset monsterInfoCsv; void loadMonsterData () { } public TextAsset useableItemInfoCsv; void loadUseableItemData () { string [] records = useableItemInfoCsv.text.Split ('\n'); for (int i = 0; i < records.Length; i++) { if (i != 0) { string [] data = records [i].Split (','); string Name = data [1]; string Description = data [2]; int Id, Price, EffectValue; int.TryParse (data [0], out Id); int.TryParse (data [3], out Price); int.TryParse (data [4], out EffectValue); UseableItem newUseableItem = new UseableItem (Id, Name, Description, Price, EffectValue); //fullDatabase.UseableItem[0].BodyArmor.Add(newBodyArmorInfo); fullDatabase.UseableItem.Add (newUseableItem); } } Debug.Log ("useable item info loaded"); } public static CharacterStat GetCharacterBaseStatsWithIdLevel (int _id, int _level) { //CharacterStats tempStat = charDatabase.CharacterInfo.First(x=> x.CharacterID == _id).CharacterStats; CharacterStatList tempStat = Instance.fullDatabase.Character.Single (x => x.CharacterID == _id).CharacterStats; int statLevelIndex = _level - 1; CharacterStat charStat = new CharacterStat(_level,tempStat.ExpToNextLevel[statLevelIndex] , tempStat.Hp [statLevelIndex] , tempStat.Tp [statLevelIndex] , tempStat.Str [statLevelIndex] , tempStat.Int [statLevelIndex] , tempStat.Stam [statLevelIndex] , tempStat.Acc [statLevelIndex] , tempStat.Eva [statLevelIndex] , tempStat.Spd [statLevelIndex] , tempStat.Luck [statLevelIndex]); return charStat; } public static int GetUseableItemIdWithName (string _itemName) { int useableItemId = Instance.fullDatabase.UseableItem.Single (x => x.ItemName == _itemName).ItemID; return useableItemId; } public static UseableItem GetUseableItemWithId (int _id) { UseableItem useableItem = Instance.fullDatabase.UseableItem.Single (x => x.ItemID == _id); return useableItem; } public static Equipment GetEquipmentWithId (int _id) { Equipment equipment = Instance.fullDatabase.Equipment.Single (x => x.ItemID == _id); return equipment; } public static Monster GetMonsterWithId (int _id) { Monster monster = Instance.fullDatabase.Monster.Single (x => x.CharacterId == _id); return monster; } public static List<string> GetNpcDialogWithId (int _id) { GameCharacter npcInfo = Instance.fullDatabase.Character.SingleOrDefault (x => x.CharacterID == _id); if (npcInfo != null) return npcInfo.CharacterDialogList; else return null; } }
using System; using System.Windows.Forms; namespace Phenix.Windows { internal partial class SheetNameSetDialog : Phenix.Core.Windows.DialogForm { private SheetNameSetDialog() { InitializeComponent(); } #region 工厂 public static bool Execute(ref string sheetName, ref bool saveSheetConfig) { using (SheetNameSetDialog dialog = new SheetNameSetDialog()) { dialog.OldSheetName = sheetName; dialog.SheetNameText = sheetName; dialog.SaveSheetConfig = saveSheetConfig; if (dialog.ShowDialog() == DialogResult.OK) { sheetName = dialog.SheetNameText; saveSheetConfig = dialog.SaveSheetConfig; return true; } return false; } } #endregion #region 属性 private string OldSheetName { get; set; } private string SheetNameText { get { return this.SheetNameTextEdit.Text; } set { this.SheetNameTextEdit.Text = value; } } private bool SaveSheetConfig { get { return this.SaveSheetConfigCheckEdit.Checked; } set { this.SaveSheetConfigCheckEdit.Checked = value; } } #endregion #region 方法 private void Humanistic() { if (String.CompareOrdinal(OldSheetName, SheetNameText) == 0) this.SheetNameTextEdit.Focus(); else this.okButton.Focus(); } private void ApplyRules() { this.okButton.Enabled = String.CompareOrdinal(OldSheetName, SheetNameText) != 0; } #endregion private void InputSheetNameDialog_Shown(object sender, EventArgs e) { ApplyRules(); Humanistic(); } private void SheetNameTextEdit_EditValueChanged(object sender, EventArgs e) { ApplyRules(); } } }
using ArticlesProject.DatabaseEntities; using ArticlesProject.Repository.Implementations; using ArticlesProject.Repository.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace ArticlesProject.Repository { public class UnitOfWork : IUnitOfWork { DatabaseContext _db; public UnitOfWork(DatabaseContext db) { //TO DO: _db = db; } private IRepository<Article> _articleRepo; public IRepository<Article> ArticleRepo { get { if (_articleRepo == null) _articleRepo = new Repository<Article>(_db); return _articleRepo; } } private IUserRepository _userRepo; public IUserRepository UserRepo { get { if (_userRepo == null) _userRepo = new UserRepository(_db); return _userRepo; } } private IRepository<Comment> _commentRepo; public IRepository<Comment> CommentRepo { get { if (_commentRepo == null) _commentRepo = new Repository<Comment>(_db); return _commentRepo; } } private IReplyRepository _replyRepo; public IReplyRepository ReplyRepo { get { if (_replyRepo == null) _replyRepo = new ReplyRepository(_db); return _replyRepo; } } public int SaveChanges() { return _db.SaveChanges(); } } }
using System; namespace SwapingValues { public class FlippingInt { public static string FlipTheValues(double A, double B) { if (A == B) { Console.WriteLine($"Value A ({A}) and Value B ({B})"); } Console.WriteLine($"A = {A}, B = {B}"); A = A + B; B = A - B; A = A - B; Console.WriteLine($"A = {A}, B = {B}"); return $"{A} and {B}"; } static void Main(string[] args) { Console.WriteLine("SwappingValues.FlippingInt.Main()"); FlipTheValues(9, 3); } } }
using System.Collections.Generic; using Uintra.Core.Feed.Services; using Uintra.Features.Navigation.Models; using Umbraco.Core.Models.PublishedContent; namespace Uintra.Features.CentralFeed.Services { public interface ICentralFeedContentService : IFeedContentService { IEnumerable<ActivityFeedTabModel> GetTabs(IPublishedContent currentPage); } }
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base; using Pe.Stracon.SGC.Infraestructura.Core.Context; using System; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual { /// <summary> /// Representa el objeto request de Flujo Aprobacion Participante /// </summary> /// <remarks> /// Creación : GMD 20150515 <br /> /// Modificación : <br /> /// </remarks> public class FlujoAprobacionParticipanteRequest : Filtro { /// <summary> /// Constructor de clase /// </summary> public FlujoAprobacionParticipanteRequest() { EstadoRegistro = DatosConstantes.EstadoRegistro.Activo; } /// <summary> /// Codigo Flujo Aprobacion Participante /// </summary> public string CodigoFlujoAprobacionParticipante { get; set; } /// <summary> /// Codigo Flujo Aprobacion Estadio /// </summary> public string CodigoFlujoAprobacionEstadio { get; set; } /// <summary> /// Codigo Trabajador /// </summary> public string CodigoTrabajador { get; set; } /// <summary> /// Codigo Tipo Participante /// </summary> public string CodigoTipoParticipante { get; set; } /// <summary> /// Estado de Registro /// </summary> public string EstadoRegistro { get; set; } /// <summary> /// Codigo Participante Original /// </summary> public string CodigoTrabajadorOriginal { get; set; } } }
using Euler_Logic.Helpers; using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems { public class Problem196 : ProblemBase { private PrimeSieve _primes; /* This turned out to be must easier than it looks. The numbers in row 7208785 are obviously very high. A primality test for each individual number is way too slow. However, row 7208785 only has 7208785 numbers. Thus, if I know all the prime numbers up to the square root of the maximum possible number in that row, I can use a prime seive to determine which numbers are prime. For example, the first number greater than or equal to 100 that is divisible by 7 is 105. Thus, I know every 7th number starting with 105 is not a prime number. So I create an array of booleans and mark true all the numbers that are composites of some prime number. If I'm trying to find S(x), then I do this for S(x - 2), S(x - 1), S(x), S(x + 1), and S(x + 2). Now it's just simply a matter of finding triplets. To make this easier, I append some blank values at the end of the smaller sets to I don't have to run a bunch of length checks. Loop through the entire row looking for prime numbers, then test if that number is in a prime triple, and if not test if any of its neighbors are. */ public override string ProblemName { get { return "196: Prime triplets"; } } public override string GetAnswer() { _primes = new PrimeSieve(10000000); var x = S(5678027); var y = S(7208785); return (x + y).ToString(); } private ulong S(ulong row) { ulong sum = 0; ulong num = (row * row / 2) - (row / 2) + 1; List<bool[]> sets = new List<bool[]>(); sets.Add(GetPrimes(row - 2, 2)); sets.Add(GetPrimes(row - 1, 1)); sets.Add(GetPrimes(row, 0)); sets.Add(GetPrimes(row + 1, 0)); sets.Add(GetPrimes(row + 2, 0)); for (int index = 0; index < sets[2].Count(); index++) { if (!sets[2][index]) { bool isPrimeTriplet = false; isPrimeTriplet = IsTriplet(index, sets[1], sets[2], sets[3]); if (!isPrimeTriplet && index > 0 && !sets[2][index - 1]) { isPrimeTriplet = IsTriplet(index - 1, sets[1], sets[2], sets[3]); } if (!isPrimeTriplet && !sets[2][index + 1]) { isPrimeTriplet = IsTriplet(index + 1, sets[1], sets[2], sets[3]); } if (!isPrimeTriplet && !sets[1][index]) { isPrimeTriplet = IsTriplet(index, sets[0], sets[1], sets[2]); } if (!isPrimeTriplet && index > 0 && !sets[1][index - 1]) { isPrimeTriplet = IsTriplet(index - 1, sets[0], sets[1], sets[2]); } if (!isPrimeTriplet && !sets[1][index + 1]) { isPrimeTriplet = IsTriplet(index + 1, sets[0], sets[1], sets[2]); } if (!isPrimeTriplet && !sets[3][index]) { isPrimeTriplet = IsTriplet(index, sets[2], sets[3], sets[4]); } if (!isPrimeTriplet && index > 0 && !sets[3][index - 1]) { isPrimeTriplet = IsTriplet(index - 1, sets[2], sets[3], sets[4]); } if (!isPrimeTriplet && !sets[3][index + 1]) { isPrimeTriplet = IsTriplet(index + 1, sets[2], sets[3], sets[4]); } if (isPrimeTriplet) { sum += num + (ulong)index; } } } return sum; } private bool IsTriplet(int index, bool[] setPrior, bool[] setCurrent, bool[] setNext) { int count = 0; if (index > 0) { count += (!setPrior[index - 1] ? 1 : 0); count += (!setCurrent[index - 1] ? 1 : 0); count += (!setNext[index - 1] ? 1 : 0); } count += (!setPrior[index] ? 1 : 0); count += (!setNext[index] ? 1 : 0); count += (!setPrior[index + 1] ? 1 : 0); count += (!setCurrent[index + 1] ? 1 : 0); count += (!setNext[index + 1] ? 1 : 0); return count >= 2; } private bool[] GetPrimes(ulong row, int blanksToAdd) { ulong num = (row * row / 2) - (row / 2) + 1; ulong max = num + row - 1; ulong maxPrime = (ulong)Math.Sqrt(max); var isNotPrime = new bool[(int)row + blanksToAdd]; foreach (var prime in _primes.Enumerate) { if (prime > maxPrime) { break; } ulong start = num; ulong mod = start % prime; if (mod != 0) { start += prime - mod; } for (ulong next = start - num; next < row; next += prime) { isNotPrime[(int)next] = true; } } for (int index = (int)row - 1; index < isNotPrime.Count(); index++) { isNotPrime[index] = true; } return isNotPrime; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.Generic; using System.Xaml; using System.Diagnostics; using System.IO; //for reading folders using System.Windows.Media.Imaging; //for bitmap images using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; namespace DEIMod { class CustomRibbon : IExternalApplication { string _path; //full path where this project is located public Result OnStartup(UIControlledApplication app) { string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); _path = Path.Combine(dir, "DEIMod.dll"); if (!File.Exists(_path)) { TaskDialog.Show("UIRibbon", "External command assembly not found: " + _path); return Result.Failed; } AddCustomRibbon(app); return Result.Succeeded; } public Result OnShutdown(UIControlledApplication app) { return Result.Succeeded; } public void AddCustomRibbon(UIControlledApplication app) { app.CreateRibbonTab("Custom"); RibbonPanel panel = app.CreateRibbonPanel("Custom", "Custom Commands"); //dynamically add buttons: //HelloWorld button PushButtonData buttonDataHello = new PushButtonData("PushButtonHello", "Hello World", _path, "DEIMod.HelloWorld"); PushButton buttonHello = panel.AddItem(buttonDataHello) as PushButton; buttonHello.ToolTip = "Displays 'Hello World!' in a dialog box"; //DBElement button PushButtonData buttonDataDB = new PushButtonData("PushButtonDB", "DB Element", _path, "DEIMod.DBElement"); PushButton buttonDB = panel.AddItem(buttonDataDB) as PushButton; buttonDB.ToolTip = "Displays basic info of a selected element"; //ElementFiltering button PushButtonData buttonDataFilter = new PushButtonData("PushButtonFilter", "Element Filtering", _path, "DEIMod.ElementFiltering"); PushButton buttonFilter = panel.AddItem(buttonDataFilter) as PushButton; buttonFilter.ToolTip = "Lists elements of the Electrical Fixtures Category"; //PlaceGroup button PushButtonData buttonDataPlace = new PushButtonData("PushButtonPlace", "Place Group", _path, "DEIMod.PlaceGroup"); PushButton buttonPlace = panel.AddItem(buttonDataPlace) as PushButton; buttonPlace.ToolTip = "Allows user to copy and place a group"; //LoadFamily button PushButtonData buttonDataLoad = new PushButtonData("PushButtonLoad", "Load Family", _path, "DEIMod.LoadFamily"); PushButton buttonLoad = panel.AddItem(buttonDataLoad) as PushButton; buttonLoad.ToolTip = "Loads the 'Balanced Power Connector' family from the US Imperial MEP Electrical library"; } } //BuiltInCategory. //OST_ElectricalFixtures //OST_CommunicationDevices //OST_DataDevices //OST_FireAlarmDevices //OST_LightingDevices //OST_NurseCallDevices //OST_SecurityDevices //OST_TelephoneDevices ???? //public Element getElement(BuiltInCategory cat) //{ // // FilteredElementCollector collector = new Filtered //} }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Reflection; using EBS.Infrastructure; using Autofac; using Autofac.Integration.Mvc; using System.Web.Mvc; using EBS.Infrastructure.Task; using EBS.Infrastructure.Log; using EBS.Admin.Services; using Dapper.DBContext; using FluentValidation; using EBS.Application; using EBS.Application.Facade; using EBS.Infrastructure.Queue; using PaySharp.Alipay; using PaySharp.Core; //using PaySharp.Core.Mvc; using PaySharp.Wechatpay; using EBS.Domain.Entity; using EBS.Domain; namespace EBS.Admin { public class AppConfig { public static void Start() { AppContext.Init(); var builder = new ContainerBuilder(); // ASP.NET MVC Autofac RegisterDependency Assembly webAssembly = Assembly.GetExecutingAssembly(); builder.RegisterControllers(webAssembly); // register admin service builder.RegisterType<AuthenticationService>().As<IAuthenticationService>().InstancePerLifetimeScope(); builder.RegisterType<ContextService>().As<IContextService>().InstancePerLifetimeScope(); // register database connection builder.RegisterType<DapperDBContext>().As<IDBContext>().WithParameter("connectionStringName", "masterDB"); builder.RegisterType<QueryService>().As<IQuery>().WithParameter("connectionStringName", "masterDB"); //注册销售单队列处理,单例 builder.RegisterType<PosSyncFacade>().As<IQueueHander<string>>(); builder.RegisterType<SimpleQueue<string>>().As<ISimpleQueue<string>>().SingleInstance(); // builder.RegisterInstance(new DapperDBContext(Configer.MasterDB)).As<IDBContext>().InstancePerLifetimeScope(); // builder.RegisterType<DapperDBContext>().WithParameter(Configer.MasterDB).As<IDBContext>().SingleInstance(); // builder.RegisterAssemblyTypes(webAssembly); // register validator //builder.RegisterType<NewsCategoryValidator>().As<IValidator<NewsCategoryModel>>(); //builder.RegisterType<NewsValidator>().As<IValidator<NewsModel>>(); builder.Update(AppContext.Container); // 注册支付组件 // RegisterPaySetting(); //ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AutofacValidatorFactory(AppContext.Container))); //DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; DependencyResolver.SetResolver(new AutofacDependencyResolver(AppContext.Container)); // start auto task //if (Configer.OpenTask) //{ // ScheduleContext.TaskConfigPath = HttpRuntime.AppDomainAppPath + "Task.Config"; // ScheduleContext.Start(); //} // setting validator local // 设置 FluentValidation 默认的资源文件提供程序 - 中文资源 ValidatorOptions.ResourceProviderType = typeof(FluentValidationResource); /* 比如验证用户名 not null、not empty、length(2,int.MaxValue) 时,链式验证时,如果第一个验证失败,则停止验证 */ ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure; // ValidatorOptions.CascadeMode 默认值为:CascadeMode.Continue // 配置 FluentValidation 模型验证为默认的 ASP.NET MVC 模型验证 // FluentValidationModelValidatorProvider.Configure(); } /// <summary> /// 组合成门店key /// </summary> /// <param name="keyName"></param> /// <param name="storeId"></param> /// <returns></returns> private static string StoreKey(string keyName,int storeId) { return keyName + "." + storeId.ToString(); } public static void RegisterPaySetting() { var builder = new ContainerBuilder(); var gateways = new Gateways(); var db = AppContext.Current.Resolve<IDBContext>(); // 注册所有配置 var allSettings = db.Table.FindAll<Setting>().ToList(); // 所有支付参数 builder.RegisterInstance(new SettingsCollection(allSettings)).As<Domain.ISettings>().SingleInstance(); // 注册支付配置 var settings = allSettings.Where(n=>n.KeyName.StartsWith("pay.")).ToList(); var normalSettings = settings.ToDictionary(n => StoreKey(n.KeyName,n.StoreId)); // key+ 门店ID 唯一 //按门店设置商户号参数 var storeSettings = settings.GroupBy(n => n.StoreId); var domainUrl = allSettings.FirstOrDefault(n => n.KeyName == SettingKeys.System_Domain).Value; foreach (var storeSettingGroup in storeSettings) { /// 支付宝配置 var alipaySetting = storeSettingGroup.Where(n => n.KeyName.StartsWith("pay.alipay")).ToList().ToDictionary(n => StoreKey(n.KeyName,n.StoreId)); var storeid = storeSettingGroup.Key; var alipayMerchant = new PaySharp.Alipay.Merchant { AppId = alipaySetting.ContainsKey(StoreKey(SettingKeys.Pay_Alipay_Appid,storeid)) ? alipaySetting[StoreKey(SettingKeys.Pay_Alipay_Appid, storeid)].Value : "", NotifyUrl = domainUrl+ (normalSettings.ContainsKey(StoreKey(SettingKeys.Pay_Notify_Url, storeid)) ? normalSettings[StoreKey(SettingKeys.Pay_Notify_Url, storeid)].Value : ""), ReturnUrl = domainUrl+ (normalSettings.ContainsKey(StoreKey(SettingKeys.Pay_Return_Url, storeid)) ? normalSettings[StoreKey(SettingKeys.Pay_Return_Url, storeid)].Value : ""), AlipayPublicKey = alipaySetting.ContainsKey(StoreKey(SettingKeys.Pay_Alipay_Public_Key, storeid)) ? alipaySetting[StoreKey(SettingKeys.Pay_Alipay_Public_Key, storeid)].Value : "", Privatekey = alipaySetting.ContainsKey(StoreKey(SettingKeys.Pay_Alipay_Private_Key, storeid)) ? alipaySetting[StoreKey(SettingKeys.Pay_Alipay_Private_Key, storeid)].Value : "", StoreId = storeid }; gateways.Add(new AlipayGateway(alipayMerchant) { GatewayUrl = "https://openapi.alipaydev.com" }); //微信配置 var wechatSetting = storeSettingGroup.Where(n => n.KeyName.StartsWith("pay.wechat")).ToList().ToDictionary(n => StoreKey(n.KeyName, n.StoreId)); var wechatpayMerchant = new PaySharp.Wechatpay.Merchant { AppId = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_Appid, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_Appid, storeid)].Value : "", MchId = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_MchId, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_MchId, storeid)].Value : "", Key = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_MchKey, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_MchKey, storeid)].Value : "", AppSecret = wechatSetting.ContainsKey(StoreKey(SettingKeys.Pay_Wechat_AppSecret, storeid)) ? wechatSetting[StoreKey(SettingKeys.Pay_Wechat_AppSecret, storeid)].Value : "", //SslCertPath = AppDomain.CurrentDomain.BaseDirectory + "Certs/apiclient_cert.p12", //SslCertPassword = "1233410002", NotifyUrl = domainUrl + (normalSettings.ContainsKey(StoreKey(SettingKeys.Pay_Notify_Url, storeid)) ? normalSettings[StoreKey(SettingKeys.Pay_Notify_Url, storeid)].Value : ""), StoreId = storeid }; gateways.Add(new WechatpayGateway(wechatpayMerchant)); } // builder.RegisterInstance(new DapperDBContext(Configer.MasterDB)).As<IDBContext>().InstancePerLifetimeScope(); builder.RegisterInstance(gateways).As<IGateways>().SingleInstance(); // 注册支付路由 PayServices.IPayRoute route = new PayServices.DefaultPayRoute(); route.InitRoute(); builder.RegisterInstance(route).As<PayServices.IPayRoute>().SingleInstance(); builder.Update(AppContext.Container); } } }