Example #1
0
 public static List <List <SalesReport> > GenerateSalesReportList(User user, ReportRequestData ord)
 {
     try
     {
         if (ord.Stores.Count == 0)
         {
             return(new List <List <SalesReport> >()
             {
                 new List <SalesReport>()
             });
         }
         else
         {
             List <List <SalesReport> > ret = new List <List <SalesReport> >();
             for (int i = 0; i < ord.Stores.Count; i++)
             {
                 ret.Add(_GenSalesReport(user, ord.Stores[i], ord.Weeks));
             }
             return(ret);
         }
     }
     catch (Exception e)
     {
         ProgramLog.LogError(user, "SalesRequestManager", "GenerateSalesReportList", e.Message);
         return(new List <List <SalesReport> >());
     }
 }
Example #2
0
        public static List <PoSummary> VerifyPoList(User user, IEnumerable <string> poList)
        {
            List <PoSummary> ret = new List <PoSummary>();

            try
            {
                string sCustomer  = user.Customer.SQLEscape();
                string sPartner   = user.ActivePartner.SQLEscape();
                var    connection = ConnectionsMgr.GetOCConnection(user, ECGB);
                {
                    using (var queryCurrent = connection.Select($"{UniqueKey},{PONumber}", SrcH850, $"WHERE {Customer}='{sCustomer}' AND {Partner}='{sPartner}' AND POStatus IN (0, 1) AND {PONumber} IN {poList.ToSqlValueList()}"))
                    {
                        while (queryCurrent.Read())
                        {
                            ret.Add(new PoSummary(queryCurrent.Field(0), queryCurrent.Field(1)));
                        }
                    }
                }
                connection.Close();
            }
            catch (Exception e)
            {
                ProgramLog.LogError(user, nameof(PdsManager), nameof(VerifyPoList), e.Message);
            }
            return(ret);
        }
Example #3
0
        protected void KickCompleted(SocketAsyncEventArgsExt argz)
        {
            try
            {
                if (argz.SocketError == SocketError.Success)
                {
                    if (argz.LastOperation == SocketAsyncOperation.Disconnect)
                    {
                        kickPool.Put(argz);
                        HandleError(SocketError.Disconnecting);
                    }
                    else
                    {
                        if (!socket.DisconnectAsync(argz))
                        {
                            kickPool.Put(argz);
                            HandleError(SocketError.Disconnecting);
                        }
                    }
                }
                else
                {
                    HandleError(argz.SocketError);
                    kickPool.Put(argz);
                }

//				kicking = false;
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Exception in connection disconnect callback");
            }
        }
        void OnLiquidFlow(ref HookContext ctx, ref HookArgs.LiquidFlowReceived args)
        {
            var player = ctx.Player;

            if (player == null || player.Name == null)
            {
                ProgramLog.Log("<Restrict> Invalid player in OnLiquidFlow.");
                ctx.SetResult(HookResult.IGNORE);
                return;
            }

            if (!restrictGuests)
            {
                return;
            }

            if (player.AuthenticatedAs == null)
            {
                ctx.SetResult(HookResult.RECTIFY);
                player.sendMessage("<Restrict> You are not allowed to alter the world as a guest.");
                player.sendMessage("<Restrict> Type \"/reg password\" to request registration.");
            }
            else if (IsRestrictedForUser(ctx.Player, LiquidFlow))
            {
                ctx.SetResult(HookResult.RECTIFY);
                player.sendMessage("<Restrict> You are not allowed to alter the world without permissions.");
            }
        }
Example #5
0
        public static ResponseType VerifyFile(User user, string xlFileName)
        {
            Application app  = null;
            Workbook    wb   = null;
            Worksheet   xlWS = null;

            try
            {
                app = new Application();
                app.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
                wb = app.Workbooks.Open(Filename: xlFileName, ReadOnly: true);
                if (wb.Worksheets.Count == 0)
                {
                    wb.Close();
                    return(ResponseType.ErrorAPOUnknown);
                }
                xlWS = wb.Worksheets[1];
                ResponseType result = CheckSheet(user, xlWS);
                return(result);
            }
            catch (Exception e)
            {
                ProgramLog.LogError(user, "POAcknowledgeManager", "VerifyFile", e.Message);
                return(ResponseType.ErrorAPOUnknown);
            }
            finally
            {
                if (app != null && wb != null)
                {
                    wb.Close();
                }
            }
        }
Example #6
0
 public static bool DecryptFileToFile(User user, string iFileName, string oFileName, string token)
 {
     try
     {
         if (!File.Exists(iFileName) || File.Exists(oFileName) || !IsTokenGood(token))
         {
             return(false);
         }
         byte[] keyArr = StringToByteArray(token.Substring(0, 32));
         byte[] ivArr  = StringToByteArray(token.Substring(32));
         if (!(keyArr.Length == ivArr.Length && keyArr.Length == 16))
         {
             return(false);
         }
         using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
         {
             aesProvider.KeySize = KeySizeBits;
             aesProvider.IV      = ivArr;
             aesProvider.Key     = keyArr;
             using (FileStream eiStream = File.OpenRead(iFileName))
                 using (FileStream doStream = File.Create(oFileName))
                     using (CryptoStream cryptoStream = new CryptoStream(eiStream, aesProvider.CreateDecryptor(), CryptoStreamMode.Read))
                     {
                         cryptoStream.CopyTo(doStream);
                     }
         }
         return(true);
     }
     catch (Exception e)
     {
         ProgramLog.LogError(user, "Crypt", "DecryptFileToFile", e.Message);
         return(false);
     }
 }
 private object[] CallSelf(string function, params object[] args)
 {
     try
     {
         if (_ctx != null)
         {
             var fnc = _ctx.GetFunction("export." + function);
             if (fnc != null)
             {
                 return(fnc.Call(this, args));
             }
         }
     }
     catch (NLua.Exceptions.LuaScriptException e)
     {
         try
         {
             if (e.IsNetException && e.InnerException != null)
             {
                 ProgramLog.Log(e.InnerException, String.Format("Plugin {0} crashed in hook {1}", this.Name, function));
             }
             else
             {
                 ProgramLog.Log(e, String.Format("Plugin {0} crashed in hook {1}", this.Name, function));
             }
         }
         catch
         {
         }
     }
     return(null);
 }
        /// <summary>
        /// Load the plugin located at the specified path.
        /// This only loads one plugin.
        /// </summary>
        /// <param name="PluginPath">Path to plugin</param>
        /// <returns>Instance of the successfully loaded plugin, otherwise null</returns>
        public static BasePlugin LoadPluginFromDLL(string PluginPath)
        {
            try
            {
                Assembly assembly = null;
                Type     type     = typeof(BasePlugin);

                using (FileStream fs = File.Open(PluginPath, FileMode.Open))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] buffer = new byte[1024];

                        int read = 0;

                        while ((read = fs.Read(buffer, 0, 1024)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }

                        assembly = Assembly.Load(ms.ToArray());
                    }
                }

                return(LoadPluginAssembly(assembly));
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Error loading plugin assembly " + PluginPath);
            }

            return(null);
        }
Example #9
0
        private static string GetFilterItem(User user, string sHeadUniqueKey850, Dictionary <string, string> sVals860)
        {
            List <string> cond = new List <string>();

            if (sVals860.ContainsKey(_Column.UPCNum))
            {
                cond.Add(string.Format("{0}='{1}'", _Column.UPCNum, sVals860[_Column.UPCNum]));
            }
            if (sVals860.ContainsKey(_Column.BuyerNum))
            {
                cond.Add(string.Format("{0}='{1}'", _Column.BuyerNum, sVals860[_Column.BuyerNum]));
            }
            if (sVals860.ContainsKey(_Column.VendorNum))
            {
                cond.Add(string.Format("{0}='{1}'", _Column.VendorNum, sVals860[_Column.VendorNum]));
            }
            if (cond.Count == 0)
            {
                ProgramLog.LogError(user, "ChangePOTracker", "GetFilterItem", string.Format("Item under POC key {0} could not be found in original PO by upc/buyer/vendor.", sHeadUniqueKey850));
                return("");
            }
            else
            {
                return(string.Format("WHERE {0}='{1}' AND ({2})", _Column.UniqueKey, sHeadUniqueKey850, string.Join(" OR ", cond)));
            }
        }
Example #10
0
        public static void AutoPurge(string WorldName)
        {
            var maxTime = Program.properties.PurgeBackupsMinutes;

            if (maxTime == 0)
            {
                return;
            }

            ProgramLog.Log("Performing backup purge...");
            var backups = GetBackups(WorldName);

            var expired = (from x in backups where (DateTime.Now - File.GetCreationTime(x)).TotalMinutes >= maxTime select x).ToArray();

            //var deleted = 0;
            foreach (var file in expired)
            {
                try
                {
                    File.Delete(file);
                    //deleted++;
                }
                catch { }
            }
        }
Example #11
0
        private static ResponseType PriceChange(DBConnect connection, User user, string sUnitPrice, string sFilterLineItem)
        {
            try
            {
                var sUpdateVals = new Dictionary <string, string>()
                {
                    { _Column.UnitPrice, sUnitPrice.SQLEscape() }
                }.ToNameValueCollection();

                var result = connection.Update(_Table.Detail850All, sUpdateVals, sFilterLineItem);

                if (result.AffectedRows > 0)
                {
                    return(ResponseType.SuccessCPO);
                }
                else
                {
                    return(ResponseType.ErrorCPOCouldNotApplyItemChange);
                }
            }
            catch (Exception e)
            {
                ProgramLog.LogError(user, "ChangePOTracker", "PriceChange", e.Message);
                return(ResponseType.ErrorCPOUnknown);
            }
        }
Example #12
0
        public static List <XrefRecord> GetXrefList(User user, FilterInfo filter)
        {
            List <XrefRecord> ret = new List <XrefRecord>();

            try
            {
                var connection = ConnectionsMgr.GetOCConnection(user, Home);
                {
                    var recCount = _GetRecordCount(user, connection, filter);
                    if (recCount > 0)
                    {
                        filter.ResultCount = recCount;
                        filter.MaxPage     = (int)(Math.Ceiling(recCount / (double)resultPageSize));
                    }

                    using (var queryCurrent = connection.Select("*", CatXref, $"WHERE {filter.ToFetchQueryString(user, searchCols, resultPageSize)}"))
                    {
                        while (queryCurrent.Read())
                        {
                            XrefRecord xr = new XrefRecord(queryCurrent);
                            ret.Add(xr);
                        }
                    }
                }
                connection.Close();
            }
            catch (Exception e)
            {
                ProgramLog.LogError(user, nameof(CatalogXrefManager), nameof(GetXrefList), e.Message);
            }
            return(ret);
        }
 protected void TxListClear()
 {
     //ProgramLog.Log ("Cleaning up txList of {0} ({1} bytes)", txList.Count, txListBytes);
     for (int i = 0; i < txList.Count; i++)
     {
         var seg = txList[i];
         if (seg.Array == txBuffer)
         {
             var count = seg.Count;
             //ProgramLog.Log ("Freeing {0} ({2}), {1}", txHead, count, txList[i].Offset);
             txHead      = (txHead + count) % txBuffer.Length;
             txCount    -= count;
             txPrepared -= count;
             if (txPrepared < 0 || txCount < 0)
             {
                 ProgramLog.Log("{0} {1}", txCount, txPrepared);
             }
         }
     }
     if (txCount == 0)
     {
         txHead = 0;
     }
     txList.Clear();
     txListBytes = 0;
 }
        /// <summary>
        /// Loads all packet handlers in the code base.
        /// </summary>
        private static IPacketHandler[] GetHandlers()
        {
            try
            {
                var max      = ((Packet[])Enum.GetValues(typeof(Packet))).Select(x => (byte)x).Max();
                var handlers = new IPacketHandler[max];

                //Load all instances of IPacketHandler
                var type = typeof(IPacketHandler);
                foreach (var messageType in typeof(PacketProcessor).Assembly
                         .GetTypesLoaded()
                         .Where(x => type.IsAssignableFrom(x) && x != type && !x.IsAbstract)
                         )
                {
                    var handler = (IPacketHandler)Activator.CreateInstance(messageType);
                    handlers[(int)handler.PacketId] = handler;
                }

                return(handlers);
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Failed to collect all packet handlers");
                return(null);
            }
        }
        public static void SaveAll()
        {
            if ((DateTime.Now - _lastSave).TotalSeconds >= 5)
            {
                //Don't perform any unnecessary writes
                var hasPlayers = Netplay.anyClients;
                if (!hasPlayers && !_hadPlayers && !EnsureSave)
                {
                    return;
                }

                EnsureSave = false;
                try
                {
                    foreach (var ply in Terraria.Main.player)
                    {
                        if (ply != null && ply.active)
                        {
                            SavePlayerData(ply);
                        }
                    }
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e);
                }

                _hadPlayers = hasPlayers;
                _lastSave   = DateTime.Now;
            }
        }
Example #16
0
        private const int OCSessionTimeOutSeconds = 60; //10 TIMED OUT OFTEN (SENDING TO 404 PAGE), TRYING 30 SECONDS. CHANGED TO 60 SECS BECAUSE OF TEMPORARY TIME DIFF BETWEEN THE TWO SERVERS

        /// <summary>
        /// Authenticates the given user.
        /// </summary>
        /// <param name="usUserName">The username to check.</param>
        /// <param name="usPassword">The password to check.</param>
        /// <returns>True if the login info is valid, false otherwise.</returns>
        public static bool AuthenticateUser(string usUserName, string usPassword)
        {
            string    sUserName   = usUserName.SQLEscape();
            string    sStoredHash = "";
            DBConnect connect     = new DBConnect();

            try
            {
                connect.Connect(ConnectionsMgr.GetAuthConnInfo());
                using (var queryUserAuthInfo = connect.Select(columnPassword, _Table.Users, string.Format("WHERE {0}='{1}'", columnUserName, sUserName)))
                {
                    if (queryUserAuthInfo.AffectedRows <= 0)
                    {
                        connect.Close();
                        return(false);
                    }
                    queryUserAuthInfo.Read();
                    sStoredHash = Encoding.UTF8.GetString((byte[])queryUserAuthInfo.Field2(0));
                }
                connect.Close();
                return(MD5Crypt.Verify(usPassword, sStoredHash));
            }
            catch (Exception ex)
            {
                ProgramLog.LogError(null, "Auth", "AuthenticateUser", ex.Message + " " + ex.StackTrace);
                connect.Close();
                return(false);
            }
        }
Example #17
0
        public static void StopServer(bool disconnect = true)
        {
            var ctx = new HookContext
            {
                Sender = HookContext.ConsoleSender
            };

            var args = new HookArgs.ServerStateChange
            {
                ServerChangeState = ServerState.Stopping
            };

            HookPoints.ServerStateChange.Invoke(ref ctx, ref args);

            //Statics.IsActive = Statics.keepRunning; //To keep console active & program alive upon restart;
            if (disconnect)
            {
                ProgramLog.Log("Disabling Plugins");
                PluginManager.DisablePlugins();
            }

            Console.Write("Saving world...");
            Terraria.IO.WorldFile.saveWorld(false);

            Thread.Sleep(5000);
            ProgramLog.Log("Closing Connections...");
            Netplay.disconnect = disconnect;

            Netplay.IsServerRunning = false;
        }
Example #18
0
        public LogViewer()
        {
            InitializeComponent();

            showMetrics  = metrics.Checked = GuiConfiguration.LogViewerShowMetrics;
            showDebug    = debug.Checked = GuiConfiguration.LogViewerShowDebug;
            showWarnings = warning.Checked = GuiConfiguration.LogViewerShowWarnings;
            showErrors   = error.Checked = GuiConfiguration.LogViewerShowErrors;

            metrics.CheckedChanged += delegate {
                showMetrics = GuiConfiguration.LogViewerShowMetrics = metrics.Checked;
                UpdateView();
            };

            debug.CheckedChanged += delegate {
                showDebug = GuiConfiguration.LogViewerShowDebug = debug.Checked;
                UpdateView();
            };

            warning.CheckedChanged += delegate {
                showWarnings = GuiConfiguration.LogViewerShowWarnings = warning.Checked;
                UpdateView();
            };

            error.CheckedChanged += delegate {
                showErrors = GuiConfiguration.LogViewerShowErrors = error.Checked;
                UpdateView();
            };

            log = ProgramLog.Default;

            UpdateView();
        }
Example #19
0
        //[Hook(HookOrder.NORMAL)]
        //void OnBanAddRequired(ref HookContext ctx, ref HookArgs.AddBan args)
        //{
        //    ctx.SetResult(HookResult.IGNORE);

        //    //Server.Bans.Add(args.RemoteAddress); //TODO see if port needs removing
        //}

        void ListenForCommands()
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            ProgramLog.Log("Ready for commands.");
            while (!Terraria.Netplay.disconnect /*|| Server.RestartInProgress*/)
            {
                try
                {
                    var ln = Console.ReadLine();
                    if (!String.IsNullOrEmpty(ln))
                    {
                        UserInput.CommandParser.ParseConsoleCommand(ln);
                    }
                    else if (null == ln)
                    {
                        ProgramLog.Log("No console input available");
                        break;
                    }
                }
                catch (ExitException)
                {
                }
                catch (Exception e)
                {
                    ProgramLog.Log("Exception from command");
                    ProgramLog.Log(e);
                }
            }
        }
Example #20
0
        static bool AssignSlot(ClientConnection conn, int id)
        {
            if (!conn.AssignSlot(id))
            {
                return(false);
            }

            conn.State = SlotState.ASSIGNING_SLOT;
            conn.ResetTimeout();

            var slot = Terraria.Netplay.Clients[id] as ServerSlot;

            slot.remoteAddress = conn.RemoteAddress;
            slot.conn          = conn;

            conn.Player.whoAmi = id;
            Main.player[id]    = conn.Player;

            var age = conn.Age;

            if (age > TimeSpan.FromMilliseconds(500))
            {
                ProgramLog.Log("Slot {1} assigned to {0} after {2}.", slot.remoteAddress, id, age);
            }
            else
            {
                ProgramLog.Log("Slot {1} assigned to {0}.", slot.remoteAddress, id);
            }

            return(true);
        }
 public static void Initialise(Entry plugin)
 {
     if (!Initialise())
     {
         ProgramLog.Log("Failed to initialise definitions.");
     }
 }
        public static void LoadForAuthenticated(IDbConnection ctx, IDbTransaction txn, Player player, bool createIfNone = true)
#endif
        {
            var ssc = LoadPlayerData(ctx, txn, player, createIfNone);

            if (ssc != null)
            {
                //Check to make sure the player is the same player (ie skin, clothes)

                var hctx = new HookContext()
                {
                    Player = player,
                    Sender = player
                };

                var args = new TDSM.Core.Events.HookArgs.PreApplyServerSideCharacter()
                {
                    Character = ssc
                };

                TDSM.Core.Events.HookPoints.PreApplyServerSideCharacter.Invoke(ref hctx, ref args);

                args.Character.ApplyToPlayer(player);

                var args1 = new TDSM.Core.Events.HookArgs.PostApplyServerSideCharacter();
                TDSM.Core.Events.HookPoints.PostApplyServerSideCharacter.Invoke(ref hctx, ref args1);
            }
            else
            {
                ProgramLog.Log("No SSC data");
            }
        }
        public static void startDedInputCallBack(object threadContext)
        {
            System.Threading.Thread.CurrentThread.Name = "APC";

            ProgramLog.Console.Print("Ready for commands.");
#if Full_API
            while (!Terraria.Netplay.disconnect)
            {
                try
                {
                    Console.Write(": ");
                    var input = Console.ReadLine();
                    _cmdParser.ParseConsoleCommand(input);
                }
                catch (ExitException e)
                {
                    ProgramLog.Log(e.Message);
                    break;
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, "Exception from command");
                }
            }
#endif
        }
        void OnSignTextSet(ref HookContext ctx, ref HookArgs.SignTextSet args)
        {
            var player = ctx.Player;

            if (player == null || player.Name == null)
            {
                ProgramLog.Log("<Restrict> Invalid player in OnSignTextSet.");
                ctx.SetResult(HookResult.IGNORE);
                return;
            }

            if (!restrictGuests)
            {
                return;
            }

            if (player.AuthenticatedAs == null)
            {
                ctx.SetResult(HookResult.IGNORE);
                player.sendMessage("<Restrict> You are not allowed to edit signs as a guest.");
                player.sendMessage("<Restrict> Type \"/reg password\" to request registration.");
            }
            else if (IsRestrictedForUser(ctx.Player, SignEdit))
            {
                ctx.SetResult(HookResult.IGNORE);
                player.sendMessage("<Restrict> You are not allowed to edit signs without permissions.");
            }
        }
Example #25
0
        public void Kick(string reason, bool announce = true)
        {
            if (kicking)
            {
                return;
            }

            state = SlotState.KICK;

            if (announce)
            {
                if (assignedSlot >= 0)
                {
                    ProgramLog.Log("{0} @ {1}: disconnecting for: {2}", RemoteAddress, assignedSlot, reason);
                    var player = Main.player[assignedSlot];
                    if (player != null)
                    {
                        player.DisconnectReason = reason;
                    }
                }
                else
                {
                    ProgramLog.Log("{0}: disconnecting for: {1}", RemoteAddress, reason);
                }
            }

            if (!kicking)
            {
                var msg = NewNetMessage.PrepareThreadInstance();
                msg.Disconnect(reason);
                KickAfter(msg.Output);
            }
        }
        private void PreviousCommandHandle(ISender sender, ArgumentList args)
        {
            var player = sender as Player;

            if (player != null)
            {
                if (Core.CommandDictionary.ContainsKey(player.name))
                {
                    CommandManager.Parser.ParseAndProcess(player, Core.CommandDictionary[player.name]);
                    ProgramLog.Log("Executed {0}'s previous command: {1}", player.name, Core.CommandDictionary[player.name]);
                }
                else
                {
                    sender.SendMessage("No Previous Command", 255, 255, 20, 20);
                }
                //ProgramLog.Log("{0}", ctx.Player.name); //, args.Prefix + " " + args.ArgumentString);
            }
            if (sender is ConsoleSender)
            {
                if (Core.CommandDictionary.ContainsKey("CONSOLE"))
                {
                    CommandManager.Parser.ParseAndProcess(ConsoleSender.Default, Core.CommandDictionary["CONSOLE"]);
                }
                else
                {
                    sender.SendMessage("No Previous Command", 255, 255, 20, 20);
                }
            }
        }
Example #27
0
		public LogViewer() {
			InitializeComponent();

			showMetrics = metrics.Checked = GuiConfiguration.LogViewerShowMetrics;
			showDebug = debug.Checked = GuiConfiguration.LogViewerShowDebug;
			showWarnings = warning.Checked = GuiConfiguration.LogViewerShowWarnings;
			showErrors = error.Checked = GuiConfiguration.LogViewerShowErrors;

			metrics.CheckedChanged += delegate {
				showMetrics = GuiConfiguration.LogViewerShowMetrics = metrics.Checked;
				UpdateView();
			};

			debug.CheckedChanged += delegate {
				showDebug = GuiConfiguration.LogViewerShowDebug = debug.Checked;
				UpdateView();
			};

			warning.CheckedChanged += delegate {
				showWarnings = GuiConfiguration.LogViewerShowWarnings = warning.Checked;
				UpdateView();
			};

			error.CheckedChanged += delegate {
				showErrors = GuiConfiguration.LogViewerShowErrors = error.Checked;
				UpdateView();
			};

			log = ProgramLog.Default;

			UpdateView();
		}
Example #28
0
        public static List <SalesRequestDetail> GetPastOrders(User user)
        {
            List <SalesRequestDetail> pastRequests = new List <SalesRequestDetail>();

            try
            {
                var connection = ConnectionsMgr.GetAdminConnection();
                {
                    var request = connection.Select(new[] { _Column.RequestDate, _Column.OutputName, _Column.ToEmail, _Column.Processed }, _Table.SalesRequest, string.Format("WHERE {0}='{1}' AND {2}='{3}' ORDER BY reqdate DESC LIMIT 10", _Column.Customer, user.Customer.SQLEscape(), _Column.ConnectID, user.OCConnID.SQLEscape()));

                    while (request.Read())
                    {
                        pastRequests.Add(new SalesRequestDetail(
                                             ((DateTime)request.Field2(0)).ToString("MMM dd, yyyy"),
                                             request.Field(1, ""),
                                             request.Field(2, ""),
                                             request.Field(3, "").ToUpper() == "Y" ? "Processed" : "Unprocessed"
                                             ));
                    }
                }
                connection.Close();
                return(pastRequests);
            }
            catch (Exception e)
            {
                ProgramLog.LogError(user, "SalesRequestManager", "GetPastOrders", e.Message);
                return(new List <SalesRequestDetail>());
            }
        }
        public void Load()
        {
            base.Load(ITEM_FILE);

            /*
             * We need to load additional items into the name lookup and only the name
             * lookup dictionary. This is at least until the item list can be fixed so
             * each item has a unique type or other identifier.
             */
            StreamReader  reader     = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(DEFINITIONS + ITEMS_BY_NAME));
            XmlSerializer serializer = new XmlSerializer(typeof(Item[]));

            try
            {
                Item[] deserialized = (Item[])serializer.Deserialize(reader);
                foreach (Item item in deserialized)
                {
                    nameLookup.Add(item.Name, item);
                }
            }
            catch (Exception e)
            {
                ProgramLog.Log(e);
            }
        }
Example #30
0
        public static List <PoItem> GetCurrentPoList(User user, FilterInfo filter)
        {
            List <PoItem> ret = new List <PoItem>();

            try
            {
                var connection = ConnectionsMgr.GetOCConnection(user, ECGB);
                {
                    var recCount = _GetRecordCount(user, connection, filter);
                    if (recCount > 0)
                    {
                        filter.ResultCount = recCount;
                        filter.MaxPage     = (int)(Math.Ceiling(recCount / (double)resultPageSize));
                    }

                    using (var queryCurrent = connection.Select($"{_Column.UniqueKey},{_Column.PONumber},{_Column.PODate},{_Column.ShipmentDate},{_Column.CancelDate},potype,round(totcmpinv) totcmpinv,round(totcmpasn) totcmpasn,round({_Column.TotalItems}) {_Column.TotalItems}", SrcH850, $"WHERE POStatus IN (0, 1) AND {filter.ToFetchQueryString(user, searchCols, resultPageSize)}"))
                    {
                        while (queryCurrent.Read())
                        {
                            PoItem po = new PoItem(queryCurrent);
                            ret.Add(po);
                        }
                    }
                }
                connection.Close();
            }
            catch (Exception e)
            {
                ProgramLog.LogError(user, nameof(PdsManager), nameof(GetCurrentPoList), e.Message);
            }
            return(ret);
        }
 public bool RunComponent(ComponentEvent componentEvent)
 {
     if (_componentEvents.ContainsKey(componentEvent))
     {
         foreach (var callback in _componentEvents[componentEvent])
         {
             try
             {
                 callback(this);
             }
             catch (StackOverflowException so)
             {
                 if (so == null)
                 {
                     ProgramLog.Log("Stack overflow detected while running component " + componentEvent);
                 }
                 else
                 {
                     ProgramLog.Log(so, "Stack overflow detected while running component " + componentEvent);
                 }
                 return(false);
             }
             catch (Exception e)
             {
                 ProgramLog.Log(e, "Exception running component " + componentEvent);
                 return(false);
             }
         }
     }
     return(true);
 }