コード例 #1
0
ファイル: WebAPI.cs プロジェクト: zerodowned/Core
        public static string GetContent(this HttpWebResponse response)
        {
            return(VitaNexCore.TryCatchGet(
                       () =>
            {
                var content = new StringBuilder();

                var s = response.GetResponseStream();

                if (s != null)
                {
                    var enc = Encoding.UTF8;

                    if (!String.IsNullOrWhiteSpace(response.ContentEncoding))
                    {
                        enc = Encoding.GetEncoding(response.ContentEncoding);
                    }

                    var r = new StreamReader(s, enc);
                    var b = new char[256];

                    int len;

                    while ((len = r.Read(b, 0, b.Length)) > 0)
                    {
                        content.Append(b, 0, len);
                    }

                    r.Close();
                    s.Close();
                }

                return content.ToString();
            },
                       CSOptions.ToConsole));
        }
コード例 #2
0
ファイル: CSharpCompiler.cs プロジェクト: uotools/JustUO
        public void Compile(bool async = false)
        {
            if (Status == CompileStatus.Compiling)
            {
                return;
            }

            var pct = new Thread(Init)
            {
                Name = "VNCSharpCompiler"
            };

            pct.Start();

            if (async)
            {
                return;
            }

            VitaNexCore.WaitWhile(
                () => Status == CompileStatus.Initializing || Status == CompileStatus.Compiling, TimeSpan.FromMinutes(5.0));

            pct.Join();
        }
コード例 #3
0
ファイル: IOExt.cs プロジェクト: AllanNisbet/runuo
        /// <summary>
        ///     Empties the contents of the specified directory with the option to include sub directories
        /// </summary>
        /// <param name="dir">Directory to empty</param>
        /// <param name="incDirs">True: includes sub directories</param>
        public static void EmptyDirectory(this DirectoryInfo dir, bool incDirs)
        {
            dir.Refresh();

            if (!dir.Exists)
            {
                return;
            }

            foreach (var f in dir.EnumerateFiles())
            {
                VitaNexCore.TryCatch(f.Delete);
            }

            if (incDirs)
            {
                foreach (var d in dir.EnumerateDirectories())
                {
                    VitaNexCore.TryCatch(d.Delete, true);
                }
            }

            dir.Refresh();
        }
コード例 #4
0
ファイル: Client.cs プロジェクト: LordEnigma/UO
        public void Close()
        {
            VitaNexCore.TryCatch(
                () =>
            {
                if (!Connected)
                {
                    return;
                }

                WebStats.Disconnected(this);

                Client.Close();
            },
                e =>
            {
                lock (WebStats.Clients)
                {
                    WebStats.Clients.Remove(this);
                }

                WebStats.CMOptions.ToConsole(e);
            });
        }
コード例 #5
0
 public static void Save()
 {
     VitaNexCore.TryCatch(SaveProfiles, CSOptions.ToConsole);
 }
コード例 #6
0
        public bool Trash(Mobile from, Item trashed, ref int tokens, bool message = true)
        {
            tokens = Math.Max(0, tokens);

            if (!Enabled || from == null || trashed == null || trashed.Deleted)
            {
                return(false);
            }

            if (!CanTrash(from, trashed))
            {
                OnTrashRejected(from, trashed, message);
                return(false);
            }

            bool multiple = false;

            if (trashed is Container)
            {
                bool      trashThis = true;
                Container c         = (Container)trashed;
                var       items     = c.FindItemsByType <Item>(false);

                if (items.Count > 0)
                {
                    multiple = true;
                }

                items.ForEach(
                    ci =>
                {
                    if (ci is Container)
                    {
                        from.SendMessage(0x55, "You cannot trash containers within containers.  Please trash them individually.");
                        trashThis = false;
                    }
                    if (!Trash(from, ci, false))
                    {
                        trashThis = false;
                    }
                });

                if (!trashThis)
                {
                    OnTrashRejected(from, trashed, message);
                    return(false);
                }
            }

            GetTrashTokens(from, trashed, ref tokens);
            OnTrashed(from, trashed, ref tokens, message);

            ItemTrashedEventArgs e = new ItemTrashedEventArgs(this, from, trashed, tokens, message);

            VitaNexCore.TryCatch(e.Invoke, TrashCollection.CMOptions.ToConsole);

            if (tokens != e.Tokens)
            {
                tokens = Math.Max(0, e.Tokens);
            }

            message = e.Message;

            if (!e.HandledTokens)
            {
                TrashCollection.EnsureProfile(from).TransferTokens(from, trashed, tokens, message);
            }

            if (from.Backpack != null && TrashCollection.CMOptions.UseTrashedProps)
            {
                from.Backpack.FindItemsByType(true, (Item i) => (i is ITrashTokenProperties)).ForEach(i => i.InvalidateProperties());
            }

            if (multiple && message)
            {
                from.SendMessage(0x55, "You trashed multiple items, check your profile history for more information.");
            }

            trashed.Delete();
            return(true);
        }
コード例 #7
0
 private static void CMSave()
 {
     VitaNexCore.TryCatch(() => ReportsFile.Serialize(SerializeReports), CMOptions.ToConsole);
 }
コード例 #8
0
        public static GiveFlags GiveTo(this Item item, Mobile m, GiveFlags flags = GiveFlags.All, bool message = true)
        {
            if (item == null || item.Deleted || m == null || m.Deleted || flags == GiveFlags.None)
            {
                return(GiveFlags.None);
            }

            var pack   = flags.HasFlag(GiveFlags.Pack);
            var bank   = flags.HasFlag(GiveFlags.Bank);
            var feet   = flags.HasFlag(GiveFlags.Feet);
            var corpse = flags.HasFlag(GiveFlags.Corpse);
            var delete = flags.HasFlag(GiveFlags.Delete);

            if (pack && (m.Backpack == null || m.Backpack.Deleted || !m.Backpack.CheckHold(m, item, false)))
            {
                pack   = false;
                flags &= ~GiveFlags.Pack;
            }

            if (bank && (!m.Player || !m.BankBox.CheckHold(m, item, false)))
            {
                bank   = false;
                flags &= ~GiveFlags.Bank;
            }

            if (corpse && (m.Alive || m.Corpse == null || m.Corpse.Deleted))
            {
                corpse = false;
                flags &= ~GiveFlags.Corpse;
            }

            if (feet && (m.Map == null || m.Map == Map.Internal) && (m.LogoutMap == null || m.LogoutMap == Map.Internal))
            {
                feet   = false;
                flags &= ~GiveFlags.Feet;
            }

            var result = VitaNexCore.TryCatchGet(
                f =>
            {
                if (pack && m.Backpack.DropItemStack(m, item))
                {
                    return(GiveFlags.Pack);
                }

                if (bank && m.BankBox.DropItemStack(m, item))
                {
                    return(GiveFlags.Bank);
                }

                if (corpse && m.Corpse.DropItemStack(m, item))
                {
                    return(GiveFlags.Corpse);
                }

                if (feet)
                {
                    if (m.Map != null && m.Map != Map.Internal)
                    {
                        item.MoveToWorld(m.Location, m.Map);

                        if (m.Player)
                        {
                            item.SendInfoTo(m.NetState);
                        }

                        return(GiveFlags.Feet);
                    }

                    if (m.LogoutMap != null && m.LogoutMap != Map.Internal)
                    {
                        item.MoveToWorld(m.LogoutLocation, m.LogoutMap);

                        return(GiveFlags.Feet);
                    }
                }

                if (delete)
                {
                    item.Delete();

                    return(GiveFlags.Delete);
                }

                return(GiveFlags.None);
            },
                flags);

            if (!message || result == GiveFlags.None || result == GiveFlags.Delete)
            {
                return(result);
            }

            var amount = String.Empty;
            var name   = ResolveName(item, m);

            var p = item.Stackable && item.Amount > 1;

            if (p)
            {
                amount = item.Amount.ToString("#,0") + " ";

                if (!Insensitive.EndsWith(name, "s") && !Insensitive.EndsWith(name, "z"))
                {
                    name += "s";
                }
            }

            switch (result)
            {
            case GiveFlags.Pack:
                m.SendMessage("{0}{1} {2} been placed in your pack.", amount, name, p ? "have" : "has");
                break;

            case GiveFlags.Bank:
                m.SendMessage("{0}{1} {2} been placed in your bank.", amount, name, p ? "have" : "has");
                break;

            case GiveFlags.Corpse:
                m.SendMessage("{0}{1} {2} been placed in your corpse.", amount, name, p ? "have" : "has");
                break;

            case GiveFlags.Feet:
                m.SendMessage("{0}{1} {2} been placed at your feet.", amount, name, p ? "have" : "has");
                break;
            }

            return(result);
        }
コード例 #9
0
 public static void Load()
 {
     VitaNexCore.TryCatch(LoadSeasons, CMOptions.ToConsole);
     VitaNexCore.TryCatch(LoadBattles, CMOptions.ToConsole);
     VitaNexCore.TryCatch(LoadProfiles, CMOptions.ToConsole);
 }
コード例 #10
0
 protected virtual void OnBeforeSend()
 {
     VitaNexCore.TryCatch(() => EnumerateInstances(User, GetType()).Where(g => g != this).ForEach(InternalClose));
 }
コード例 #11
0
        private static ConquestRewardInfo CreateInstance(Type t)
        {
            if (t == null)
            {
                return(null);
            }

            return(VitaNexCore.TryCatchGet(
                       () =>
            {
                ConquestRewardInfo info;

                if (t.IsEqualOrChildOf <TitleScroll>())
                {
                    var scroll = t.CreateInstanceSafe <TitleScroll>();

                    if (scroll != null)
                    {
                        string name = scroll.ResolveName();

                        if (scroll.Title != null)
                        {
                            name += " - " +
                                    (scroll.Title.MaleTitle == scroll.Title.FemaleTitle
                                            ? scroll.Title.MaleTitle
                                            : (scroll.Title.MaleTitle + ":" + scroll.Title.FemaleTitle));
                        }

                        info = new ConquestRewardInfo(
                            t, scroll.LabelNumber, name, scroll.Amount, scroll.Stackable, scroll.Hue, scroll.ItemID);

                        scroll.Delete();
                        return info;
                    }
                }
                else if (t.IsEqualOrChildOf <HueScroll>())
                {
                    var scroll = t.CreateInstanceSafe <HueScroll>();

                    if (scroll != null)
                    {
                        string name = scroll.ResolveName();

                        if (scroll.TitleHue != null)
                        {
                            name += ": #" + scroll.TitleHue;
                        }

                        info = new ConquestRewardInfo(
                            t, scroll.LabelNumber, name, scroll.Amount, scroll.Stackable, scroll.Hue, scroll.ItemID);

                        scroll.Delete();
                        return info;
                    }
                }
                else if (t.IsEqualOrChildOf <Item>())
                {
                    var item = t.CreateInstanceSafe <Item>();

                    if (item != null)
                    {
                        info = new ConquestRewardInfo(
                            t, item.LabelNumber, item.ResolveName().ToUpperWords(), item.Amount, item.Stackable,
                            item.Hue, item.ItemID);

                        item.Delete();
                        return info;
                    }
                }
                else if (t.IsEqualOrChildOf <Mobile>())
                {
                    var mob = t.CreateInstanceSafe <Mobile>();

                    if (mob != null)
                    {
                        info = new ConquestRewardInfo(t, 0, mob.RawName.ToUpperWords(), 1, false, mob.Hue,
                                                      ShrinkTable.Lookup(mob));

                        mob.Delete();

                        return info;
                    }
                }
                else if (t.IsEqualOrChildOf <IEntity>())
                {
                    var ent = t.CreateInstanceSafe <IEntity>();

                    if (ent != null)
                    {
                        info = new ConquestRewardInfo(t, 0, t.Name.SpaceWords());

                        ent.Delete();
                        return info;
                    }
                }
                else if (t.IsEqualOrChildOf <XmlAttachment>())
                {
                    var xml = t.CreateInstanceSafe <XmlAttachment>();

                    if (xml != null)
                    {
                        info = new ConquestRewardInfo(t, 0, xml.Name.ToUpperWords());

                        xml.Delete();
                        return info;
                    }
                }

                info = new ConquestRewardInfo(t, 0, t.Name.SpaceWords());

                return info;
            },
                       Conquests.CMOptions.ToConsole));
        }
コード例 #12
0
 public static TObj ReadTypeCreate <TObj>(this GenericReader reader, params object[] args)
     where TObj : class
 {
     return(VitaNexCore.TryCatchGet(t => t.CreateInstanceSafe <TObj>(args), ReadType(reader), VitaNexCore.ToConsole));
 }
コード例 #13
0
ファイル: SuperGump_Assets.cs プロジェクト: uotools/JustUO
        public static SuperGumpAsset CreateInstance(FileInfo file, bool cache, bool reload)
        {
            if (file == null || !file.Exists)
            {
                return(Empty);
            }

            return(VitaNexCore.TryCatchGet(
                       () =>
            {
                var hash = CryptoGenerator.GenString(CryptoHashType.MD5, file.FullName);

                SuperGumpAsset a;

                lock (_CacheLock)
                {
                    a = AssetCache.FirstOrDefault(ca => ca.Hash == hash);
                }

                if (a == null || reload)
                {
                    using (var img = new Bitmap(file.FullName, true))
                    {
                        a = new SuperGumpAsset(file, img);

                        if (cache)
                        {
                            lock (_CacheLock)
                            {
                                AssetCache.AddOrReplace(a);
                            }
                        }
                    }
                }

                if (IsNullOrEmpty(a))
                {
                    return Empty;
                }

                if (!cache || a.Capacity > 0x1000)
                {
                    lock (_CacheLock)
                    {
                        AssetCache.Remove(a);
                        AssetCache.Free(false);
                    }
                }

                lock (_CacheLock)
                {
                    if (AssetCache.Count > 100)
                    {
                        AssetCache.RemoveAt(0);
                    }

                    AssetCache.Free(false);
                }

                return a;
            },
                       VitaNexCore.ToConsole));
        }
コード例 #14
0
ファイル: PokerExport.cs プロジェクト: zerodowned/UO-Forever
        private static void FlushCallback(bool transactional)
        {
            int total = ExportQueue.Values.Sum(d => d.Count);

            if (!_Updating || ExportQueue.Count == 0 || total == 0)
            {
                if (transactional)
                {
                    Connection.EndTransaction();
                    _Sync.Set();
                }

                OnAbort();
                return;
            }

            CMOptions.ToConsole("{0:#,0} objects in {1:#,0} tables pending update...", total, ExportQueue.Count);

            int updated = 0;

            ConcurrentStack <QueuedData> stack;

            QueuedData[] pop;
            QueuedData   peek;

            MySQLData[][] batch;
            int           count;

            var watch = new Stopwatch();

            watch.Start();

            foreach (string table in ExportQueue.Keys.TakeWhile(table => _Updating && updated < CMOptions.ExportCapacity))
            {
                stack = ExportQueue[table];

                if (stack == null || stack.IsEmpty)
                {
                    ExportQueue.TryRemove(table, out stack);
                    continue;
                }

                count = Math.Max(0, Math.Min(CMOptions.ExportCapacity - updated, stack.Count));

                if (count == 0)
                {
                    continue;
                }

                pop = new QueuedData[count];

                if (stack.TryPopRange(pop) > 0)
                {
                    peek = pop.FirstOrDefault(p => p != null && p.RawData != null && p.RawData.Count > 0);

                    if (peek == null || !Connection.CreateTable(table, peek.RawData))
                    {
                        ExportQueue.TryRemove(table, out stack);
                        continue;
                    }

                    batch = pop.AsParallel().Select(qd => qd.SqlData).ToMultiArray();

                    if (batch.Length > 0)
                    {
                        if (CMOptions.ModuleDebug)
                        {
                            CMOptions.ToConsole("Update {0:#,0} objects in '{1}'...", batch.Length, table);
                        }

                        Connection.InsertMany(table, batch);

                        updated += batch.Length;
                    }
                }

                if (stack.IsEmpty)
                {
                    ExportQueue.TryRemove(table, out stack);
                }
            }

            if (transactional)
            {
                VitaNexCore.TryCatch(Connection.EndTransaction, CMOptions.ToConsole);
            }

            watch.Stop();

            CMOptions.ToConsole("Updated {0:#,0} objects in {1:F2} seconds.", updated, watch.Elapsed.TotalSeconds);

            _UpdateCount += updated;

            //GC.Collect();

            _Sync.Set();

            if (!ExportQueue.IsEmpty)
            {
                Flush();
            }
        }
コード例 #15
0
 private static void CSLoad()
 {
     VitaNexCore.TryCatchGet(PlayerProfiles.Import, x => x.ToConsole());
     VitaNexCore.TryCatchGet(ZombieEvents.Import, x => x.ToConsole());
 }
コード例 #16
0
        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            IsDisposed = true;

            //Console.WriteLine("SuperGump Disposing: {0} (0x{1:X})", GetType(), Serial);

            //GC.SuppressFinalize(this);

            VitaNexCore.TryCatch(OnDispose);

            VitaNexCore.TryCatch(UnregisterInstance);

            NextButtonID    = 1;
            NextSwitchID    = 0;
            NextTextInputID = 0;

            if (InstancePoller != null)
            {
                VitaNexCore.TryCatch(InstancePoller.Dispose);
            }

            VitaNexCore.TryCatch(
                () =>
            {
                Buttons.Clear();
                TileButtons.Clear();
                Switches.Clear();
                Radios.Clear();
                TextInputs.Clear();
                LimitedTextInputs.Clear();

                Entries.Free(true);

                Layout.Clear();
            });

            VitaNexCore.TryCatch(
                () =>
            {
                Linked.AsEnumerable().ForEach(Unlink);
                Linked.Free(true);
            });

            VitaNexCore.TryCatch(
                () =>
            {
                Children.AsEnumerable().ForEach(RemoveChild);
                Children.Free(true);
            });

            IsOpen = false;
            Hidden = false;

            VitaNexCore.TryCatch(OnDisposed);

            InstancePoller = null;

            Parent = null;
            User   = null;

            Buttons           = null;
            TileButtons       = null;
            Switches          = null;
            Radios            = null;
            TextInputs        = null;
            LimitedTextInputs = null;

            Layout = null;

            Linked   = null;
            Children = null;
        }
コード例 #17
0
        public virtual SuperGump Send()
        {
            if (IsDisposed || _Sending)
            {
                return(this);
            }

            _Sending = true;

            return(VitaNexCore.TryCatchGet(
                       () =>
            {
                if (IsOpen)
                {
                    InternalClose(this);
                }

                Compile();
                Clear();

                AddPage();

                CompileLayout(Layout);
                Layout.ApplyTo(this);

                InvalidateOffsets();
                InvalidateSize();

                Compiled = true;

                if (Modal && ModalSafety && Buttons.Count == 0 && TileButtons.Count == 0)
                {
                    CanDispose = true;
                    CanClose = true;
                }

                OnBeforeSend();

                Initialized = true;
                IsOpen = User.SendGump(this, false);
                Hidden = false;

                if (IsOpen)
                {
                    OnSend();
                }
                else
                {
                    OnSendFail();
                }

                _Sending = false;

                return this;
            },
                       e =>
            {
                Console.WriteLine("SuperGump '{0}' could not be sent, an exception was caught:", GetType().FullName);
                VitaNexCore.ToConsole(e);
                IsOpen = false;
                Hidden = false;
                OnSendFail();

                _Sending = false;
            }) ?? this);
        }
コード例 #18
0
ファイル: AutoDonate.cs プロジェクト: uotools/JustUO
        private static void ImportMySQL(DonationTransactionState state)
        {
            Connection.UseDatabase(CMOptions.MySQL.Database);

            int count = 0;

            var rows = Connection.Select(
                CMOptions.TableName,
                null,
                new[] { new MySQLCondition("state", state.ToString().ToUpper()) },
                "time",
                MySQLSortOrder.ASC);

            if (Connection.HasError)
            {
                if (!CMOptions.ModuleQuietMode)
                {
                    foreach (OdbcError e in Connection.Errors)
                    {
                        OnExceptionThrown(new Exception(e.Message), "OdbcError");
                    }
                }
            }
            else if (rows.Length > 0)
            {
                var gTrans = new List <DonationTransaction>(rows.Length);

                foreach (MySQLRow row in rows)
                {
                    VitaNexCore.TryCatch(
                        () =>
                    {
                        var total  = row["total"].GetValue <decimal>();
                        var credit = row["credit"].GetValue <long>();
                        int time   = row["time"].GetValue <int>(), version = row["version"].GetValue <int>();
                        string id  = row["id"].GetValue <string>(),
                        email      = row["email"].GetValue <string>(),
                        notes      = row["notes"].GetValue <string>(),
                        extra      = row["extra"].GetValue <string>(),
                        status     = row["state"].GetValue <string>(),
                        account    = row["account"].GetValue <string>();

                        IAccount a = Accounts.GetAccount(account ?? String.Empty) ??
                                     Accounts.GetAccounts().FirstOrDefault(ac => ac.AccessLevel == AccessLevel.Owner);

                        DonationTransactionState s;

                        if (a == null || !Enum.TryParse(status, true, out s))
                        {
                            s = DonationTransactionState.Void;
                        }

                        gTrans.Add(new DonationTransaction(id, s, a, email, total, credit, time, version, notes, extra));

                        ++count;
                    },
                        e => OnExceptionThrown(e, "Could not load MySQL data for transaction in row {0:#,0}", row.ID));
                }

                gTrans.TrimExcess();

                foreach (DonationTransaction trans in gTrans)
                {
                    VitaNexCore.TryCatch(
                        () =>
                    {
                        DonationProfile dp;

                        if (!Profiles.TryGetValue(trans.Account, out dp))
                        {
                            Profiles.Add(trans.Account, dp = new DonationProfile(trans.Account));
                        }
                        else if (dp == null)
                        {
                            Profiles[trans.Account] = dp = new DonationProfile(trans.Account);
                        }

                        if (!dp.Contains(trans))
                        {
                            dp.Add(trans);
                        }

                        switch (trans.State)
                        {
                        case DonationTransactionState.Pending:
                            {
                                if (dp.Process(trans))
                                {
                                }
                            }
                            break;

                        case DonationTransactionState.Processed:
                            break;

                        case DonationTransactionState.Claimed:
                            break;

                        case DonationTransactionState.Void:
                            {
                                if (dp.Void(trans))
                                {
                                }
                            }
                            break;
                        }
                    },
                        e => OnExceptionThrown(e, "Could not load MySQL data for transaction ID {0}", trans.ID));
                }
            }

            CMOptions.ToConsole("Imported {0} {1} transactions.", count, state);
        }
コード例 #19
0
 public static void Save()
 {
     VitaNexCore.TryCatch(SaveSeasons, CMOptions.ToConsole);
     VitaNexCore.TryCatch(SaveBattles, CMOptions.ToConsole);
     VitaNexCore.TryCatch(SaveProfiles, CMOptions.ToConsole);
 }
コード例 #20
0
        public override void Ignite()
        {
            var points = new List <Point3D>();

            Location.ScanRange(
                Map,
                5,
                r =>
            {
                if (!Map.CanSpawnMobile(r.Current))
                {
                    r.Exclude();
                }

                if (!r.Excluded)
                {
                    points.Add(r.Current);
                }

                return(false);
            });

            if (points.Count == 0)
            {
                return;
            }

            var t = this.GetRandomSpawn();

            if (t == null)
            {
                return;
            }

            var m = VitaNexCore.TryCatchGet(() => t.CreateInstance <Mobile>(), DeceitBraziers.CMOptions.ToConsole);

            if (m == null)
            {
                return;
            }

            VitaNexCore.TryCatch(
                () =>
            {
                Duration  = CoolDown;
                Protected = true;
                base.Ignite();

                var fx = new FireExplodeEffect(this, Map, 5, 2)
                {
                    Reversed      = true,
                    EffectHandler = e =>
                                    e.Source.GetMobilesInRange(e.Map, 0)
                                    .Where(v => v != null && v.CanBeDamaged())
                                    .ForEach(v => AOS.Damage(v, Utility.RandomMinMax(10, 20), 10, 80, 0, 0, 10))
                };

                fx.Callback = () =>
                {
                    if (fx.CurrentProcess < fx.Repeat)
                    {
                        return;
                    }

                    new SmokeExplodeEffect(Location, Map, 1).Send();
                    m.MoveToWorld(points.GetRandom(), Map);
                };

                fx.Send();
            },
                ex => m.Delete());
        }
コード例 #21
0
 public static void Sync()
 {
     VitaNexCore.TryCatch(SyncSeasons, CMOptions.ToConsole);
     VitaNexCore.TryCatch(SyncBattles, CMOptions.ToConsole);
     VitaNexCore.TryCatch(SyncProfiles, CMOptions.ToConsole);
 }
コード例 #22
0
ファイル: WebSockets.cs プロジェクト: somedude373/NeverFade
        private static void HandleConnection(WebSocketsClient client)
        {
            VitaNexCore.TryCatch(
                () =>
            {
                if (client.Seeded)
                {
                    return;
                }

                var headers = new Dictionary <string, string>();

                Receive(
                    client,
                    false,
                    true,
                    (c, d, b) =>
                {
                    if (d.Length == 0)
                    {
                        return;
                    }

                    var lines = d.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    lines = lines.Take(lines.Length - 1).ToArray();

                    if (CMOptions.ModuleDebug)
                    {
                        CMOptions.ToConsole(lines.Not(String.IsNullOrWhiteSpace).ToArray());
                    }

                    lines.ForEach(
                        line =>
                    {
                        line = line.Trim();

                        var header = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        if (header.Length == 0)
                        {
                            return;
                        }

                        var hk = header[0].Replace(":", String.Empty);

                        if (String.IsNullOrWhiteSpace(hk))
                        {
                            return;
                        }

                        var hv = header.Length > 1 ? String.Join(" ", header.Skip(1)) : String.Empty;

                        if (!headers.ContainsKey(hk))
                        {
                            headers.Add(hk, hv);
                        }
                        else
                        {
                            headers[hk] = hv;
                        }
                    });
                });

                if (headers.Count > 0)
                {
                    HandleHttpRequest(client, headers);
                }
                else
                {
                    throw new Exception("No headers defined for WebSockets client handshake.", new SocketException());
                }
            },
                CMOptions.ToConsole);
        }
コード例 #23
0
        public override bool OnBuyItems(Mobile buyer, List <BuyItemResponse> list)
        {
            if (!Trading || !IsActiveSeller || CashType == null || !CashType.IsNotNull)
            {
                return(false);
            }

            if (!buyer.CheckAlive())
            {
                return(false);
            }

            if (!CheckVendorAccess(buyer))
            {
                Say("I can't serve you! Company policy.");
                //Say(501522); // I shall not treat with scum like thee!
                return(false);
            }

            UpdateBuyInfo();

            var info         = GetSellInfo();
            var totalCost    = 0;
            var validBuy     = new List <BuyItemResponse>(list.Count);
            var fromBank     = false;
            var fullPurchase = true;
            var controlSlots = buyer.FollowersMax - buyer.Followers;

            foreach (var buy in list)
            {
                var ser    = buy.Serial;
                var amount = buy.Amount;

                if (ser.IsItem)
                {
                    var item = World.FindItem(ser);

                    if (item == null)
                    {
                        continue;
                    }

                    var gbi = LookupDisplayObject(item);

                    if (gbi != null)
                    {
                        ProcessSinglePurchase(buy, gbi, validBuy, ref controlSlots, ref fullPurchase, ref totalCost);
                    }
                    else if (item != BuyPack && item.IsChildOf(BuyPack))
                    {
                        if (amount > item.Amount)
                        {
                            amount = item.Amount;
                        }

                        if (amount <= 0)
                        {
                            continue;
                        }

                        foreach (var ssi in info.Where(ssi => ssi.IsSellable(item) && ssi.IsResellable(item)))
                        {
                            totalCost += ssi.GetBuyPriceFor(item) * amount;
                            validBuy.Add(buy);
                            break;
                        }
                    }
                }
                else if (ser.IsMobile)
                {
                    var mob = World.FindMobile(ser);

                    if (mob == null)
                    {
                        continue;
                    }

                    var gbi = LookupDisplayObject(mob);

                    if (gbi != null)
                    {
                        ProcessSinglePurchase(buy, gbi, validBuy, ref controlSlots, ref fullPurchase, ref totalCost);
                    }
                }
            }

            if (fullPurchase && validBuy.Count == 0)
            {
                // Thou hast bought nothing!
                SayTo(buyer, 500190);
            }
            else if (validBuy.Count == 0)
            {
                // Your order cannot be fulfilled, please try again.
                SayTo(buyer, 500187);
            }

            if (validBuy.Count == 0)
            {
                return(false);
            }

            var bought = buyer.AccessLevel >= AccessLevel.GameMaster;

            if (!bought && CashType.TypeEquals <ObjectProperty>())
            {
                var cashSource = GetCashObject(buyer) ?? buyer;

                bought = CashProperty.Consume(cashSource, totalCost);

                if (!bought)
                {
                    // Begging thy pardon, but thou cant afford that.
                    SayTo(buyer, 500192);
                    return(false);
                }

                SayTo(buyer, "{0:#,0} {1} has been deducted from your total.", totalCost, CashName.GetString(buyer));
            }

            var isGold = CashType.TypeEquals <Gold>();

            var cont = buyer.Backpack;

            if (!bought && cont != null && isGold)
            {
                VitaNexCore.TryCatch(
                    () =>
                {
                    var lt = ScriptCompiler.FindTypeByName("GoldLedger") ?? Type.GetType("GoldLedger");

                    if (lt == null)
                    {
                        return;
                    }

                    var ledger = cont.FindItemByType(lt);

                    if (ledger == null || ledger.Deleted)
                    {
                        return;
                    }

                    var lp = lt.GetProperty("Gold");

                    if (lp == null)
                    {
                        return;
                    }

                    if (lp.PropertyType.IsEqual <Int64>())
                    {
                        var lg = (long)lp.GetValue(ledger, null);

                        if (lg < totalCost)
                        {
                            return;
                        }

                        lp.SetValue(ledger, lg - totalCost, null);
                        bought = true;
                    }
                    else if (lp.PropertyType.IsEqual <Int32>())
                    {
                        var lg = (int)lp.GetValue(ledger, null);

                        if (lg < totalCost)
                        {
                            return;
                        }

                        lp.SetValue(ledger, lg - totalCost, null);
                        bought = true;
                    }

                    if (bought)
                    {
                        buyer.SendMessage(2125, "{0:#,0} gold has been withdrawn from your ledger.", totalCost);
                    }
                });
            }

            if (!bought)
            {
                ConsumeCurrency(buyer, ref totalCost, ref bought);
            }

            if (!bought && cont != null)
            {
                if (cont.ConsumeTotal(CashType, totalCost))
                {
                    bought = true;
                }
            }

            if (!bought && isGold && Banker.Withdraw(buyer, totalCost))
            {
                bought   = true;
                fromBank = true;
            }

            if (!bought && !isGold)
            {
                cont = buyer.FindBankNoCreate();

                if (cont != null && cont.ConsumeTotal(CashType, totalCost))
                {
                    bought   = true;
                    fromBank = true;
                }
            }

            if (!bought)
            {
                // Begging thy pardon, but thou cant afford that.
                SayTo(buyer, 500192);
                return(false);
            }

            buyer.PlaySound(0x32);

            cont = buyer.Backpack ?? buyer.BankBox;

            foreach (var buy in validBuy)
            {
                var ser    = buy.Serial;
                var amount = buy.Amount;

                if (amount < 1)
                {
                    continue;
                }

                if (ser.IsItem)
                {
                    var item = World.FindItem(ser);

                    if (item == null)
                    {
                        continue;
                    }

                    var gbi = LookupDisplayObject(item);

                    if (gbi != null)
                    {
                        ProcessValidPurchase(amount, gbi, buyer, cont);
                    }
                    else
                    {
                        if (amount > item.Amount)
                        {
                            amount = item.Amount;
                        }

                        if (info.Where(ssi => ssi.IsSellable(item)).Any(ssi => ssi.IsResellable(item)))
                        {
                            Item buyItem;

                            if (amount >= item.Amount)
                            {
                                buyItem = item;
                            }
                            else
                            {
                                buyItem = LiftItemDupe(item, item.Amount - amount) ?? item;
                            }

                            if (cont == null || !cont.TryDropItem(buyer, buyItem, false))
                            {
                                buyItem.MoveToWorld(buyer.Location, buyer.Map);
                            }
                        }
                    }
                }
                else if (ser.IsMobile)
                {
                    var mob = World.FindMobile(ser);

                    if (mob == null)
                    {
                        continue;
                    }

                    var gbi = LookupDisplayObject(mob);

                    if (gbi != null)
                    {
                        ProcessValidPurchase(amount, gbi, buyer, cont);
                    }
                }
            }

            if (fullPurchase)
            {
                if (buyer.AccessLevel >= AccessLevel.GameMaster)
                {
                    SayTo(buyer, true, "I would not presume to charge thee anything.  Here are the goods you requested.");
                }
                else if (fromBank)
                {
                    SayTo(
                        buyer,
                        true,
                        "The total of thy purchase is {0:#,0} {1}, which has been withdrawn from your bank account.  My thanks for the patronage.",
                        totalCost,
                        CashName.GetString(buyer));
                }
                else
                {
                    SayTo(
                        buyer,
                        true,
                        "The total of thy purchase is {0:#,0} {1}.  My thanks for the patronage.",
                        totalCost,
                        CashName.GetString(buyer));
                }
            }
            else
            {
                if (buyer.AccessLevel >= AccessLevel.GameMaster)
                {
                    SayTo(
                        buyer,
                        true,
                        "I would not presume to charge thee anything.  Unfortunately, I could not sell you all the goods you requested.");
                }
                else if (fromBank)
                {
                    SayTo(
                        buyer,
                        true,
                        "The total of thy purchase is {0:#,0} {1}, which has been withdrawn from your bank account.  My thanks for the patronage.  Unfortunately, I could not sell you all the goods you requested.",
                        totalCost,
                        CashName.GetString(buyer));
                }
                else
                {
                    SayTo(
                        buyer,
                        true,
                        "The total of thy purchase is {0:#,0} {1}.  My thanks for the patronage.  Unfortunately, I could not sell you all the goods you requested.",
                        totalCost,
                        CashName.GetString(buyer));
                }
            }

            return(true);
        }
コード例 #24
0
ファイル: WebStats.cs プロジェクト: LordEnigma/UO
        public static void HandleConnection(WebStatsClient client)
        {
            VitaNexCore.TryCatch(
                () =>
            {
                var headers = new Dictionary <string, string>();

                client.Receive(
                    false,
                    true,
                    (c, d, b) =>
                {
                    EndReceive(c, d, b);

                    if (d.Length == 0)
                    {
                        return;
                    }

                    var lines = d.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    lines = lines.Take(lines.Length - 1).ToArray();

                    if (CMOptions.ModuleDebug)
                    {
                        CMOptions.ToConsole(lines.Not(String.IsNullOrWhiteSpace).ToArray());
                    }

                    lines.ForEach(
                        line =>
                    {
                        line = line.Trim();

                        var header = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        if (header.Length == 0)
                        {
                            return;
                        }

                        string hk = header[0].Replace(":", String.Empty);

                        if (String.IsNullOrWhiteSpace(hk))
                        {
                            return;
                        }

                        string hv = header.Length > 1 ? String.Join(" ", header.Skip(1)) : String.Empty;

                        if (!headers.ContainsKey(hk))
                        {
                            headers.Add(hk, hv);
                        }
                        else
                        {
                            headers[hk] = hv;
                        }
                    });
                });

                if (headers.Count > 0)
                {
                    HandleHttpRequest(client, headers);
                    return;
                }

                client.Send(GetJSON(false), true, false, EndSend);
            },
                CMOptions.ToConsole);

            if (client != null)
            {
                client.Close();
            }
        }
コード例 #25
0
 private static void CMLoad()
 {
     VitaNexCore.TryCatch(() => ReportsFile.Deserialize(DeserializeReports), CMOptions.ToConsole);
 }
コード例 #26
0
        private void Init()
        {
            VitaNexCore.TryCatch(
                () =>
            {
                Status = CompileStatus.Initializing;

                if (!InputDirectory.Exists)
                {
                    Status        = CompileStatus.Aborted;
                    StatusMessage = "Input directory '" + InputDirectory + "' does not exist.";
                    return;
                }

                var infos = new List <FileInfo>();

                foreach (var file in FileMasks.SelectMany(
                             t => InputDirectory.GetFiles(t, SearchOption.AllDirectories).Where(file => !infos.Contains(file))))
                {
                    infos.Add(file);
                }

                var files = infos.ToArray();
                infos.Clear();

                if (files.Length == 0)
                {
                    Status        = CompileStatus.Aborted;
                    StatusMessage = "No files to compile.";
                    return;
                }

                var refs      = new List <string>();
                var fileNames = new List <string>();

                foreach (var fName in files.Select(t => t.FullName)
                         .Where(fName => !String.IsNullOrEmpty(fName))
                         .Where(fName => !fileNames.Contains(fName)))
                {
                    fileNames.Add(fName);
                }

                foreach (var t in DefaultReferences.Where(t => !String.IsNullOrEmpty(t)).Where(t => !refs.Contains(t)))
                {
                    refs.Add(t);
                }

                foreach (var t in References.Where(t => !String.IsNullOrEmpty(t)).Where(t => !refs.Contains(t)))
                {
                    refs.Add(t);
                }

                var configs = GetConfigFiles();

                if (configs != null)
                {
                    foreach (var t in configs.Select(GetConfigAssemblies)
                             .SelectMany(
                                 asm => asm.Where(t => !String.IsNullOrEmpty(t))
                                 .Where(t => File.Exists(IOUtility.GetSafeFilePath(IOUtility.GetBaseDirectory() + "/" + t, true)))
                                 .Where(t => !refs.Contains(t))))
                    {
                        refs.Add(t);
                    }
                }

                Status     = CompileStatus.Compiling;
                Parameters = new CompilerParameters(
                    refs.ToArray(),
                    IOUtility.GetUnusedFilePath(OutputDirectory.FullName, OutputFileName),
                    Debug)
                {
                    GenerateExecutable = false,
                    WarningLevel       = 4,
                    CompilerOptions    = String.Empty
                };

                foreach (var arg in Arguments)
                {
                    Parameters.CompilerOptions += arg + " ";
                }

                Results = Provider.CompileAssemblyFromFile(Parameters, fileNames.ToArray());

                if (Results.Errors.Count > 0)
                {
                    int errorCount = 0, warningCount = 0;

                    foreach (CompilerError e in Results.Errors)
                    {
                        if (e.IsWarning)
                        {
                            ++warningCount;
                        }
                        else
                        {
                            ++errorCount;
                        }
                    }

                    Errors = new string[Results.Errors.Count];

                    for (var e = 0; e < Results.Errors.Count; e++)
                    {
                        Errors[e] = String.Format(
                            "[{0}][{1}][{2}]: Line {3}, Column {4}\n{5}",
                            Results.Errors[e].IsWarning ? "Warning" : "Error",
                            Results.Errors[e].FileName,
                            Results.Errors[e].ErrorNumber,
                            Results.Errors[e].Line,
                            Results.Errors[e].Column,
                            Results.Errors[e].ErrorText);
                    }

                    StatusMessage = String.Format(
                        "Finished compiling with {0} error{1} and {2} warning{3}",
                        errorCount,
                        errorCount > 1 ? "s" : "",
                        warningCount,
                        warningCount > 1 ? "s" : "");

                    Status = CompileStatus.Completed;
                }
                else
                {
                    StatusMessage = "Finished compiling with no errors or warnings.";
                    Status        = CompileStatus.Completed;
                }
            },
                ex =>
            {
                Status        = CompileStatus.Aborted;
                StatusMessage = ex.Message;
            });

            if (CompiledCallback != null)
            {
                CompiledCallback(Results);
            }
        }
コード例 #27
0
ファイル: ItemExt.cs プロジェクト: LordEnigma/UO
        public static GiveFlags GiveTo(
            this Item item, Mobile m, GiveFlags flags = GiveFlags.PackBankFeet, bool message = true)
        {
            if (item == null || item.Deleted || m == null || m.Deleted || flags == GiveFlags.None)
            {
                return(GiveFlags.None);
            }

            bool pack   = flags.HasFlag(GiveFlags.Pack);
            bool bank   = flags.HasFlag(GiveFlags.Bank);
            bool feet   = flags.HasFlag(GiveFlags.Feet);
            bool delete = flags.HasFlag(GiveFlags.Delete);

            GiveFlags result = VitaNexCore.TryCatchGet(
                () =>
            {
                if (pack && m.PlaceInBackpack(item))
                {
                    return(GiveFlags.Pack);
                }

                if (bank && m.BankBox.TryDropItem(m, item, false))
                {
                    return(GiveFlags.Bank);
                }

                if (feet)
                {
                    MapPoint mp = m.ToMapPoint();

                    if (!mp.Internal)
                    {
                        item.MoveToWorld(mp.Location, mp.Map);
                        return(GiveFlags.Feet);
                    }
                }

                if (delete)
                {
                    item.Delete();
                    return(GiveFlags.Delete);
                }

                return(GiveFlags.None);
            });

            if (message)
            {
                string amount = String.Empty;
                string name   = ResolveName(item, m);

                bool p = false;

                if (item.Stackable && item.Amount > 1)
                {
                    amount = item.Amount.ToString("#,0") + " ";
                    p      = true;

                    if (!Insensitive.EndsWith(name, "s") && !Insensitive.EndsWith(name, "z"))
                    {
                        name += "s";
                    }
                }

                switch (result)
                {
                case GiveFlags.Pack:
                    m.SendMessage("{0}{1} {2} been placed in your pack.", amount, name, p ? "have" : "has");
                    break;

                case GiveFlags.Bank:
                    m.SendMessage("{0}{1} {2} been placed in your bank.", amount, name, p ? "have" : "has");
                    break;

                case GiveFlags.Feet:
                    m.SendMessage("{0}{1} {2} been placed at your feet.", amount, name, p ? "have" : "has");
                    break;
                }
            }

            return(result);
        }
コード例 #28
0
ファイル: Client.cs プロジェクト: AllanNisbet/runuo
        public bool ReceiveHeaders(out KeyValueString[] headers)
        {
            headers = _EmptyHeaders;

            var buffer = _EmptyBuffer;
            var length = 0;

            if (Stream.CanRead)
            {
                VitaNexCore.WaitWhile(() => !Stream.DataAvailable, TimeSpan.FromMilliseconds(1000));

                if (Stream.DataAvailable)
                {
                    buffer = new byte[Client.ReceiveBufferSize];

                    using (var ms = new MemoryStream())
                    {
                        int idx = 0, seq = 0;

                        while (Stream.DataAvailable)
                        {
                            var r = Stream.ReadByte();

                            if (r > -1)
                            {
                                if (++length > WebAPI.CSOptions.MaxReceiveBufferSizeBytes)
                                {
                                    throw new InternalBufferOverflowException(
                                              String.Format("Received data exceeded {0:#,0} bytes", WebAPI.CSOptions.MaxReceiveBufferSizeBytes));
                                }

                                var b = (byte)r;

                                buffer[idx++] = b;

                                if (Sequence(b, ref seq) && seq >= 4)
                                {
                                    break;
                                }

                                if (idx >= buffer.Length)
                                {
                                    ms.Write(buffer, 0, idx);
                                    idx = 0;
                                }
                            }
                        }

                        if (idx > 0)
                        {
                            ms.Write(buffer, 0, idx);
                        }

                        buffer = ms.ToArray();
                        length = buffer.Length;
                    }
                }
            }

            WebAPI.CSOptions.ToConsole(
                "Received {0:#,0} bytes ({1:#,0} bytes/read)",
                length,
                Math.Min(length, Client.ReceiveBufferSize));

            if (length <= 0)
            {
                return(false);
            }

            var raw = Encoding.ASCII.GetString(buffer, 0, length);

            if (String.IsNullOrWhiteSpace(raw))
            {
                return(false);
            }

            var h = raw.Split(_Separators, StringSplitOptions.RemoveEmptyEntries);

            if (h.Length == 0)
            {
                return(false);
            }

            headers = ParseHeaders(h).ToArray();

            return(headers.Length > 0);
        }
コード例 #29
0
 public static void Load()
 {
     VitaNexCore.TryCatch(LoadProfiles, CSOptions.ToConsole);
 }
コード例 #30
0
ファイル: Tree.cs プロジェクト: somedude373/NeverFade
        protected override void OnDispose()
        {
            base.OnDispose();

            VitaNexCore.TryCatch(Nodes.Clear);
        }