Exemplo n.º 1
0
        public static void towizfile(string line)
        {
            var outline = string.Empty;

            if (!string.IsNullOrEmpty(line))
            {
                var filler = 78 - line.Length;
                if (filler < 1)
                {
                    filler = 1;
                }
                filler /= 2;
                for (var x = 0; x < filler; x++)
                {
                    outline += " ";
                }
                outline += line;
            }

            outline += "\r\n";
            using (
                var proxy =
                    new TextWriterProxy(new StreamWriter(SystemConstants.GetSystemFile(SystemFileTypes.Wizards), true)))
            {
                proxy.Write(outline);
            }
        }
Exemplo n.º 2
0
        public static void reset_colors(PlayerInstance ch)
        {
            var path = SystemConstants.GetSystemDirectory(SystemDirectoryTypes.Color) + "default";

            using (var proxy = new TextReaderProxy(new StreamReader(path)))
            {
                IEnumerable <string> lines = proxy.ReadIntoList();
                foreach (var line in lines.Where(l => !l.EqualsIgnoreCase("#colortheme") &&
                                                 !l.StartsWithIgnoreCase("name") &&
                                                 !l.EqualsIgnoreCase("maxcolors")))
                {
                    var tuple = line.FirstArgument();
                    switch (tuple.Item1.ToLower())
                    {
                    case "colors":
                        var colors = tuple.Item2.Split(' ');
                        for (var i = 0; i < colors.Length; i++)
                        {
                            ch.Colors[EnumerationExtensions.GetEnum <ATTypes>(i)] = (char)colors[i].ToInt32();
                        }
                        break;

                    case "end":
                        return;
                    }
                }
            }
        }
Exemplo n.º 3
0
        public async Task NewBill(InputBillDto inputBillDto, string destiny)
        {
            try
            {
                var paymentMethod = SystemConstants.ListPaymentMethods().FirstOrDefault(wh => wh.SysId == inputBillDto.PaymentMethodSysId);
                var billDestiny   = destiny.ToUpper() == SystemConstants.BillDestinyReceive
                    ? SystemConstants.BillDestinyReceive
                    : SystemConstants.BillDestinyPay;

                var bill = new Bill(
                    paymentMethod,
                    inputBillDto.Value,
                    billDestiny,
                    SystemConstants.BillStatus_EmAberto,
                    inputBillDto.DueDate,
                    inputBillDto.Description
                    );

                await _ravenDatabaseProvider.CreateEntity <Bill>(bill);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 4
0
        public async Task UpdatePaymentMethod(string id, string paymentMethodSysId)
        {
            try
            {
                var bill = await _ravenDatabaseProvider.GetEntity <Bill>(id);

                if (bill == null)
                {
                    throw new Exception("Não foi encontrado nenhum lançamento financeiro com o id " + id);
                }

                var paymentMethod = SystemConstants.ListPaymentMethods().FirstOrDefault(x => x.SysId == paymentMethodSysId);
                if (paymentMethod == null)
                {
                    throw new ArgumentException("Não foi incontrado um meio de pagamento válido!");
                }


                bill.UpdatePaymentMethod(paymentMethod);

                if (!string.IsNullOrEmpty(bill.ServiceOrderId))
                {
                    var serviceOrder = await _ravenDatabaseProvider.GetEntity <ServiceOrder>(bill.ServiceOrderId);

                    serviceOrder.Bill.UpdatePaymentMethod(paymentMethod);
                    await _ravenDatabaseProvider.UpdateEntity <ServiceOrder>(serviceOrder.Id, serviceOrder);
                }

                await _ravenDatabaseProvider.UpdateEntity <Bill>(id, bill);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 5
0
        public static void show_colorthemes(CharacterInstance ch)
        {
            ch.SendToPager("&Ythe following themes are available:\r\n");

            var proxy = new DirectoryProxy();
            var path  = SystemConstants.GetSystemDirectory(SystemDirectoryTypes.Color);

            var count = 0;
            var col   = 0;

            foreach (var file in proxy.GetFiles(path).ToList()
                     .Where(x => !x.EqualsIgnoreCase("cvs") && !x.StartsWith(".")))
            {
                ++count;
                ch.PagerPrintf("%s%-15.15s", color_str(ATTypes.AT_PLAIN, ch), file);
                if (++col % 6 == 0)
                {
                    ch.SendToPager("\r\n");
                }
            }

            if (count == 0)
            {
                ch.SendToPager("No themes defined yet.\r\n");
            }

            if (col % 6 != 0)
            {
                ch.SendToPager("\r\n");
            }
        }
Exemplo n.º 6
0
 protected void SelectedConstantChanging(CodesModel newValue)
 {
     IsInProgress = true;
     if (newValue != null)
     {
         DataGridSource.ReFill(SystemConstants.Where(x => x.CMasterId == newValue.CId));
     }
     IsInProgress = false;
 }
Exemplo n.º 7
0
        public void PassengerProcessor()
        {
            var np  = new PassengerProcessor();
            var res = np.ProcessPNL(SystemConstants.GetTestPNL());

            Assert.AreEqual(res.Count, 3);
            Assert.AreEqual(res["LVGVUP"].Count, 2);
            Assert.AreEqual(res["LVK6HA"].Count, 1);
        }
Exemplo n.º 8
0
        public static void shutdown_mud(string reason)
        {
            var path = SystemConstants.GetSystemFile(SystemFileTypes.Shutdown);

            using (var proxy = new TextWriterProxy(new StreamWriter(path, true)))
            {
                proxy.Write("{0}\n", reason);
            }
        }
Exemplo n.º 9
0
        private static void SendFileToBuffer(CharacterInstance ch, SystemFileTypes fileType)
        {
            string path = SystemConstants.GetSystemFile(fileType);

            using (TextReaderProxy proxy = new TextReaderProxy(new StreamReader(path)))
            {
                string buffer = proxy.ReadToEnd();
                comm.write_to_buffer(ch.Descriptor, buffer, buffer.Length);
            }
        }
Exemplo n.º 10
0
        private static void SendFileToBuffer(this PlayerInstance ch, SystemFileTypes fileType)
        {
            var path = SystemConstants.GetSystemFile(fileType);

            using (var proxy = new TextReaderProxy(new StreamReader(path)))
            {
                var buffer = proxy.ReadToEnd();
                ch.Descriptor.WriteToBuffer(buffer, buffer.Length);
            }
        }
Exemplo n.º 11
0
        public static void do_idea(CharacterInstance ch, string argument)
        {
            ch.SetColor(ATTypes.AT_PLAIN);
            if (CheckFunctions.CheckIfEmptyString(ch, argument, "Usage:  'idea <message>'\r\n"))
            {
                return;
            }

            db.append_file(ch, SystemConstants.GetSystemFile(SystemFileTypes.Idea), argument);
            ch.SendTo("Thanks, your idea has been recorded.");
        }
Exemplo n.º 12
0
        private static void InitializeManagersAndGameSettings()
        {
            LogManager = Kernel.Get <ILogManager>();
            LogManager.Boot("-----------------------[ Boot Log ]----------------------");

            var loaded = SystemConstants.LoadSystemDirectoriesFromConfig(GameConstants.DataPath);

            LogManager.Boot("{0} SystemDirectories loaded.", loaded);

            loaded = SystemConstants.LoadSystemFilesFromConfig();
            LogManager.Boot("{0} SystemFiles loaded.", loaded);

            LookupManager = Kernel.Get <ILookupManager>();

            LuaManager = Kernel.Get <ILuaManager>();

            NetworkManager = Kernel.Get <ITcpServer>();
            NetworkManager.Startup(Convert.ToInt32(ConfigurationManager.AppSettings["port"]),
                                   IPAddress.Parse(ConfigurationManager.AppSettings["host"]));
            NetworkManager.OnTcpUserStatusChanged += NetworkManager_OnOnTcpUserStatusChanged;

            RepositoryManager = Kernel.Get <IRepositoryManager>();

            var luaInitializer = Kernel.Get <IInitializer>("LuaInitializer");

            if (luaInitializer == null)
            {
                throw new ApplicationException("LuaInitializer failed to start");
            }

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Lookups));
            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.StatModLookups));

            BanManager      = Kernel.Get <IBanManager>();
            BoardManager    = Kernel.Get <IBoardManager>();
            CalendarManager = Kernel.Get <ICalendarManager>();

            GameManager = Kernel.Get <IGameManager>();
            GameManager.SetGameTime(CalendarManager.GameTime);
            GameManager.GameTime.SetTimeOfDay(GameConstants.GetSystemValue <int>("HourOfSunrise"),
                                              GameConstants.GetSystemValue <int>("HourOfDayBegin"), GameConstants.GetSystemValue <int>("HourOfSunset"),
                                              GameConstants.GetSystemValue <int>("HourOfNightBegin"));

            WeatherManager = Kernel.Get <IWeatherManager>();

            NewsManager = Kernel.Get <INewsManager>();

            AuctionManager = Kernel.Get <IAuctionManager>();

            ClanManager = Kernel.Get <IClanManager>();

            InitializeStaticGameData();
        }
        public ActionResult Edit(SystemConstants data)
        {
            if (ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                data.UserID = ((User)Session["LoginUser"]).UserID;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(data);
        }
Exemplo n.º 14
0
        public static void do_bug(CharacterInstance ch, string argument)
        {
            var tm = DateTime.Now;

            ch.SetColor(ATTypes.AT_PLAIN);
            if (CheckFunctions.CheckIfEmptyString(ch, argument,
                                                  "Usage:  'bug <message>'  (your location is automatically recorded)"))
            {
                return;
            }

            db.append_file(ch, SystemConstants.GetSystemFile(SystemFileTypes.PBug),
                           $"({tm.ToLongDateString()}):  {argument}");
            ch.SendTo("Thanks, your bug notice has been recorded.");
        }
Exemplo n.º 15
0
        public void Save()
        {
            string path = SystemConstants.GetSystemDirectory(SystemDirectoryTypes.System) + "time.dat";

            using (TextWriterProxy proxy = new TextWriterProxy(new StreamWriter(path)))
            {
                proxy.Write("#TIME\n");
                proxy.Write("Mhour  {0}\n", Hour);
                proxy.Write("Mday   {0}\n", Day);
                proxy.Write("Mmonth {0}\n", Month);
                proxy.Write("Myear  {0}\n", Year);
                proxy.Write("End\n\n");
                proxy.Write("#END\n");
            }
        }
Exemplo n.º 16
0
        public void LoadMap(SystemFileTypes fileType, IEnumerable <string> map)
        {
            var path = SystemConstants.GetSystemFile(fileType);

            using (var proxy = new TextReaderProxy(new StreamReader(path)))
            {
                IEnumerable <string> lines = proxy.ReadIntoList();
                if (!lines.Any())
                {
                    throw new InvalidDataException($"Missing data for {fileType}");
                }

                map.ToList().AddRange(lines);
            }
        }
Exemplo n.º 17
0
        /// <summary>Cập nhật thông tin nhân viên</summary>
        /// <param name="request">The request.</param>
        /// <returns>
        ///   <br />
        /// </returns>
        /// <exception cref="ThainhLabExeption">Không tìm thấy nhân viên có Id: {request.Id}</exception>
        /// <Modified>
        /// Name     Date         Comments
        /// thainh2  5/10/2021   created
        /// </Modified>
        public async Task <ApiResult <string> > Update(StaffUpdateRequest request)
        {
            try
            {
                var staff = await _context.Staffs.FindAsync(request.Id);

                if (staff == null)
                {
                    throw new ThainhLabExeption($"Không tìm thấy nhân viên có Id: {request.Id}");
                }
                // Check trùng email
                var staffObj = await _context.Staffs.FirstOrDefaultAsync(t => t.Email == request.Email.Trim() && t.Status == true && t.Id != request.Id);

                if (staffObj != null)
                {
                    return(new ApiErrorResult <string>("Email đã tồn tại"));
                }
                // Check trùng số điện thoại
                var objStaff_PhoneNumber = await _context.Staffs.FirstOrDefaultAsync(t => t.Tel == request.Tel.Trim() && t.Status == true && t.Id != request.Id);

                if (objStaff_PhoneNumber != null)
                {
                    return(new ApiErrorResult <string>("Số điện thoại đã tồn tại"));
                }

                staff.Name         = SystemConstants.StripHTML(request.Name);
                staff.NameUnsigned = SystemConstants.ConvertToUnSign(SystemConstants.StripHTML(request.Name));
                staff.Email        = request.Email;
                staff.Tel          = request.Tel;
                staff.UpdateBy     = request.UpdateBy;
                staff.UpdateDate   = DateTime.Now;
                var result = await _context.SaveChangesAsync();

                return(new ApiSuccessResult <string>(result.ToString()));
            }
            catch (Exception e)
            {
                var logRequest = new LogWritelogRequest()
                {
                    MethodName  = "StaffService_Update",
                    CreateDate  = DateTime.Now,
                    Description = e.Message
                };
                await WriteLog(logRequest);

                throw new ThainhLabExeption(e.Message);
            }
        }
Exemplo n.º 18
0
        /// <summary>Tạo mới nhân viên</summary>
        /// <param name="request">The request.</param>
        /// <returns>
        ///   <br />
        /// </returns>
        /// <Modified>
        /// Name     Date         Comments
        /// thainh2  5/10/2021   created
        /// </Modified>
        public async Task <ApiResult <string> > Create(StaffCreateRequest request)
        {
            try
            {
                // Check trùng email
                var staffObj = await _context.Staffs.FirstOrDefaultAsync(t => t.Email == request.Email.Trim() && t.Status == true);

                if (staffObj != null)
                {
                    return(new ApiErrorResult <string>("Email đã tồn tại"));
                }

                //Check trùng số điện thoại
                var objStaff_PhoneNumber = await _context.Staffs.FirstOrDefaultAsync(t => t.Tel == request.Tel.Trim() && t.Status == true);

                if (objStaff_PhoneNumber != null)
                {
                    return(new ApiErrorResult <string>("Số điện thoại đã tồn tại"));
                }

                var staff = new Staff()
                {
                    Name         = SystemConstants.StripHTML(request.Name),
                    NameUnsigned = SystemConstants.ConvertToUnSign(SystemConstants.StripHTML(request.Name)),
                    Email        = request.Email,
                    Tel          = request.Tel,
                    Status       = true,
                    CreateBy     = request.CreateBy,
                    CreateDate   = DateTime.Now
                };
                _context.Staffs.Add(staff);
                await _context.SaveChangesAsync();

                return(new ApiSuccessResult <string>(staff.Id.ToString()));
            }
            catch (Exception e)
            {
                var logRequest = new LogWritelogRequest()
                {
                    MethodName  = "StaffService_Create",
                    CreateDate  = DateTime.Now,
                    Description = e.Message
                };
                await WriteLog(logRequest);

                throw new ThainhLabExeption(e.Message);
            }
        }
        public ActionResult Create(SystemConstants data)
        {
            if (ModelState.IsValid)
            {
                if (Session["LoginUser"] != null)
                {
                    data.UserID = ((User)Session["LoginUser"]).UserID;
                }

                db.SystemConstants.Add(data);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(data);
        }
Exemplo n.º 20
0
        public async Task NewServiceOrder(InputServiceOrderDto serviceOrderDto)
        {
            try
            {
                var session = await _ravenDatabaseProvider.GetSession();

                var paymentMethod = SystemConstants.ListPaymentMethods().FirstOrDefault(wh => wh.SysId == serviceOrderDto.PaymentMethodSysId);

                if (paymentMethod == null)
                {
                    throw new InvalidEnumArgumentException("Não foi encontrado um meio de pagamento válido");
                }

                var customer = await _ravenDatabaseProvider.GetEntity <Customer>(serviceOrderDto.CustomerId);

                if (customer == null)
                {
                    throw new InvalidEnumArgumentException("Não foi encontrado um cliente com o ID informado");
                }

                var bill = new Bill(
                    paymentMethod,
                    serviceOrderDto.Value,
                    SystemConstants.BillDestinyReceive,
                    SystemConstants.BillStatus_EmAberto,
                    serviceOrderDto.DueDate,
                    serviceOrderDto.Description
                    );

                await session.StoreAsync(bill);

                ServiceOrder serviceOrder = new ServiceOrder(DateTime.Now, serviceOrderDto.Description, customer, bill);

                await session.StoreAsync(serviceOrder);

                //await _ravenDatabaseProvider.CommitAsync(session);
                await session.SaveChangesAsync();

                session.Dispose();
                bill.SetServiceOrderId(serviceOrder.Id);
                await _ravenDatabaseProvider.UpdateEntity <Bill>(bill.Id, bill);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 21
0
        public virtual void Load()
        {
            var path = SystemConstants.GetSystemDirectory(SystemDirectory);

            var appSetting = GameConstants.GetAppSetting(AppSettingName);

            if (string.IsNullOrEmpty(appSetting))
            {
                throw new EntryNotFoundException($"{AppSettingName} not found in app.config");
            }

            IEnumerable <string> fileList = appSetting.Split(',');

            foreach (var fileName in fileList)
            {
                _luaManager.DoLuaScript($"{path}\\{fileName}.lua");
            }
        }
Exemplo n.º 22
0
        private static void LoadSystemDataFromLuaScripts()
        {
            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Commands));
            LogManager.Boot("{0} Commands loaded.", RepositoryManager.COMMANDS.Count);
            LookupManager.CommandLookup.UpdateFunctionReferences(RepositoryManager.COMMANDS.Values);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.SpecFuns));
            LogManager.Boot("{0} SpecFuns loaded.", RepositoryManager.SPEC_FUNS.Count);
            //SpecFunLookupTable.UpdateCommandFunctionReferences(RepositoryManager.Instance.SPEC_FUNS.Values);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Socials));
            LogManager.Boot("{0} Socials loaded.", RepositoryManager.SOCIALS.Count);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Skills));
            LogManager.Boot("{0} Skills loaded.", RepositoryManager.SKILLS.Count);
            LookupManager.SkillLookup.UpdateFunctionReferences(RepositoryManager.SKILLS.Values);
            LookupManager.SpellLookup.UpdateFunctionReferences(RepositoryManager.SKILLS.Values);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Liquids));
            LogManager.Boot("{0} Liquids loaded.", RepositoryManager.LIQUIDS.Count);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Mixtures));
            LogManager.Boot("{0} Mixtures loaded.",
                            RepositoryManager.GetRepository <MixtureData>(RepositoryTypes.Mixtures).Count);
            // TODO: Update function references

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Herbs));
            LogManager.Boot("{0} Herbs loaded.", RepositoryManager.HERBS.Count);
            LookupManager.SkillLookup.UpdateFunctionReferences(RepositoryManager.HERBS.Values);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Tongues));
            LogManager.Boot("{0} Tongues loaded.", RepositoryManager.LANGUAGES.Count);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Planes));
            LogManager.Boot("{0} Planes loaded.", RepositoryManager.PLANES.Count);

            LuaManager.DoLuaScript(SystemConstants.GetSystemFile(SystemFileTypes.Morphs));
            LogManager.Boot("{0} Morphs loaded.", RepositoryManager.MORPHS.Count);
        }
Exemplo n.º 23
0
        public static void mudprog_file_read(Template index, string filename)
        {
            var path = SystemConstants.GetSystemDirectory(SystemDirectoryTypes.Prog) + filename;

            using (var proxy = new TextReaderProxy(new StreamReader(path)))
            {
                do
                {
                    var line = proxy.ReadLine();
                    if (line.StartsWith("|"))
                    {
                        break;
                    }
                    if (line.StartsWith(">"))
                    {
                        continue;
                    }

                    var type = (MudProgTypes)EnumerationFunctions.GetEnumByName <MudProgTypes>(proxy.ReadNextWord());
                    if (type == MudProgTypes.Error ||
                        type == MudProgTypes.InFile)
                    {
                        LogManager.Instance.Bug("Invalid mud prog type {0} in file {1}", type, path);
                        continue;
                    }

                    var prog = new MudProgData
                    {
                        Type       = type,
                        ArgList    = proxy.ReadString(),
                        Script     = proxy.ReadString(),
                        IsFileProg = true
                    };

                    index.AddMudProg(prog);
                    break;
                } while (!proxy.EndOfStream);
            }
        }
        public async Task <long> Create(DocumentsCreateRequest request)
        {
            var user = new User()
            {
            };
            var document = new Document()
            {
                UserID = request.UserID,
                FacultyOfDocumentID = request.FalcultyOfDocumentID,
                MagazineID          = request.MagazineID,
                Caption             = "Document file",
                CreateOn            = DateTime.Now.Date,
            };

            if (request.DocumentFile != null)
            {
                user.Documents = new List <Document>()
                {
                    new Document()
                    {
                        Caption      = "Document file",
                        CreateOn     = DateTime.Now.Date,
                        FileSize     = request.DocumentFile.Length,
                        DocumentPath = await this.SaveFile(request.DocumentFile),
                    }
                };
            }
            if (request.FalcultyOfDocumentID == 1)
            {
                SystemConstants.SendMail("*****@*****.**");
            }
            _context.Documents.Add(document);
            await _context.SaveChangesAsync();

            return(document.ID);
        }
Exemplo n.º 25
0
        public static void do_typo(CharacterInstance ch, string argument)
        {
            ch.SetColor(ATTypes.AT_PLAIN);

            if (CheckFunctions.CheckIfEmptyString(ch, argument,
                                                  "Usage:  'typo <message>'  (your location is automatically recorded)"))
            {
                if (ch.Trust >= LevelConstants.GetLevel(ImmortalTypes.Ascendant))
                {
                    ch.SendTo("Usage:  'typo list' or 'typo clear now'");
                }
                return;
            }

            if (!argument.EqualsIgnoreCase("clear now") || ch.Trust < LevelConstants.GetLevel(ImmortalTypes.Ascendant))
            {
                return;
            }
            var path = SystemConstants.GetSystemFile(SystemFileTypes.Typo);

            using (var proxy = new TextWriterProxy(new StreamWriter(path, false)))
                proxy.Write(string.Empty);
            ch.SendTo("Typo file cleared.");
        }
 protected void btnLogOut_Click(object sender, EventArgs e)
 {
     SystemConstants.LogOut("LogIn");
 }
Exemplo n.º 27
0
        public static void do_say(CharacterInstance ch, string argument)
        {
#if !SCRAMBLE
            var speaking = -1;

            /*foreach (int key in GameConstants.LanguageTable.Keys
             *  .Where(key => (key & ch.Speaking) > 0))
             * {
             *  speaking = key;
             *  break;
             * }*/
#endif

            if (CheckFunctions.CheckIfEmptyString(ch, argument, "Say what?"))
            {
                return;
            }
            if (CheckFunctions.CheckIf(ch,
                                       args => ((CharacterInstance)args[0]).CurrentRoom.Flags.IsSet((int)RoomFlags.Silence),
                                       "You can't do that here.", new List <object> {
                ch
            }))
            {
                return;
            }

            var actflags = ch.Act;
            if (ch.IsNpc())
            {
                ch.Act.RemoveBit((int)ActFlags.Secretive);
            }

            foreach (var vch in ch.CurrentRoom.Persons.Where(vch => vch != ch))
            {
                var sbuf = argument;
                if (vch.IsIgnoring(ch))
                {
                    if (!ch.IsImmortal() || vch.Trust > ch.Trust)
                    {
                        continue;
                    }

                    vch.SetColor(ATTypes.AT_IGNORE);
                    vch.Printf("You attempt to ignore %s, but are unable to do so.\r\n", ch.Name);
                }

#if !SCRAMBLE
                /*if (speaking != -1 && (!ch.IsNpc() || ch.Speaking != 0))
                 * {
                 *  int speakswell = vch.KnowsLanguage(ch.Speaking, ch).GetLowestOfTwoNumbers(ch.KnowsLanguage(ch.Speaking, vch));
                 *  if (speakswell < 75)
                 *      sbuf = act_comm.TranslateLanguage(speakswell, argument, GameConstants.LanguageTable[speaking]);
                 * }*/
#else
                if (KnowsLanguage(vch, ch.Speaking, ch) == 0 &&
                    (!ch.IsNpc() || ch.Speaking != 0))
                {
                    sbuf = ScrambleText(argument, ch.Speaking);
                }
#endif
                sbuf = sbuf.Drunkify(ch);

                // TODO Toggle global mobtrigger flag
                comm.act(ATTypes.AT_SAY, "$n says '$t'", ch, sbuf, vch, ToTypes.Victim);
            }

            ch.Act = actflags;
            // TODO Toggle global mobtrigger flag
            comm.act(ATTypes.AT_SAY, "You say '%T'", ch, null, argument.Drunkify(ch), ToTypes.Character);

            if (ch.CurrentRoom.Flags.IsSet((int)RoomFlags.LogSpeech))
            {
                db.append_to_file(SystemConstants.GetSystemFile(SystemFileTypes.Log),
                                  $"{(ch.IsNpc() ? ch.ShortDescription : ch.Name)}: {argument}");
            }

            MudProgHandler.ExecuteMobileProg(MudProgTypes.Speech, argument, ch);
            if (ch.CharDied())
            {
                return;
            }
            MudProgHandler.ExecuteObjectProg(MudProgTypes.Speech, argument, ch);
            if (ch.CharDied())
            {
                return;
            }
            MudProgHandler.ExecuteRoomProg(MudProgTypes.Speech, argument, ch);
        }
Exemplo n.º 28
0
        public static void make_wizlist()
        {
            var wizList   = new List <WizardData>();
            var directory = SystemConstants.GetSystemDirectory(SystemDirectoryTypes.God);
            var files     = new DirectoryProxy().GetFiles(directory);

            foreach (var file in files.Where(x => !x.StartsWithIgnoreCase(".")))
            {
                using (var proxy = new TextReaderProxy(new StreamReader(file)))
                {
                    var wizard = new WizardData {
                        Name = file
                    };
                    wizard.Level = wizard.Load(proxy.ReadIntoList());
                    wizList.Add(wizard);
                }
            }

            var buffer = $" Masters of the {GameManager.Instance.SystemData.MudTitle}!";

            var iLevel = 65535;

            foreach (var wiz in wizList)
            {
                if (wiz.Level < iLevel)
                {
                    if (!string.IsNullOrEmpty(buffer))
                    {
                        towizfile(buffer);
                        buffer = string.Empty;
                    }
                    towizfile(string.Empty);
                    iLevel = wiz.Level;
                    if (iLevel == LevelConstants.MaxLevel)
                    {
                        towizfile(" Supreme Entity");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 1)
                    {
                        towizfile(" Infinite");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 2)
                    {
                        towizfile(" Eternal");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 3)
                    {
                        towizfile(" Ancient");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 4)
                    {
                        towizfile(" Exalted Gods");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 5)
                    {
                        towizfile(" Ascendant Gods");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 6)
                    {
                        towizfile(" Greater Gods");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 7)
                    {
                        towizfile(" Gods");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 8)
                    {
                        towizfile(" Lesser Gods");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 9)
                    {
                        towizfile(" Immortals");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 10)
                    {
                        towizfile(" Demi Gods");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 11)
                    {
                        towizfile(" Saviors");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 12)
                    {
                        towizfile(" Creators");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 13)
                    {
                        towizfile(" Acolytes");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 14)
                    {
                        towizfile(" Neophytes");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 15)
                    {
                        towizfile(" Retired");
                    }
                    else if (iLevel == LevelConstants.MaxLevel - 16)
                    {
                        towizfile(" Guests");
                    }
                    else
                    {
                        towizfile(" Servants");
                    }
                }

                if (buffer.Length + wiz.Name.Length > 76)
                {
                    towizfile(buffer);
                    buffer = string.Empty;
                }
                buffer += " " + wiz.Name;
                if (buffer.Length > 70)
                {
                    towizfile(buffer);
                    buffer = string.Empty;
                }
            }

            if (!string.IsNullOrEmpty(buffer))
            {
                towizfile(buffer);
            }
        }
Exemplo n.º 29
0
        public static void do_reply(CharacterInstance ch, string argument)
        {
#if !SCRAMBLE
            var speaking = -1;

            /*foreach (int key in GameConstants.LanguageTable.Keys
             *                           .Where(key => (key & ch.Speaking) > 0))
             * {
             *  speaking = key;
             *  break;
             * }*/
#endif

            ch.Deaf.RemoveBit(ChannelTypes.Tells);
            if (ch.CurrentRoom.Flags.IsSet(RoomFlags.Silence))
            {
                ch.SendTo("You can't do that here.\r\n");
                return;
            }

            if (!ch.IsNpc() && ch.Act.IsSet((int)PlayerFlags.Silence))
            {
                ch.SendTo("Your message didn't get through.\r\n");
                return;
            }

            var victim = ((PlayerInstance)ch).ReplyTo;
            if (victim == null)
            {
                ch.SendTo("They aren't here.\r\n");
                return;
            }

            if (!victim.IsNpc() &&
                victim.Switched != null &&
                ch.CanSee(victim) &&
                ch.Trust > LevelConstants.AvatarLevel)
            {
                ch.SendTo("That player is switched.\r\n");
                return;
            }

            if (!victim.IsNpc() && ((PlayerInstance)victim).Descriptor == null)
            {
                ch.SendTo("That player is link-dead.\r\n");
                return;
            }

            if (!victim.IsNpc() && victim.Act.IsSet((int)PlayerFlags.AwayFromKeyboard))
            {
                ch.SendTo("That player is afk.\r\n");
                return;
            }

            if (victim.Deaf.IsSet(ChannelTypes.Tells) &&
                (!ch.IsImmortal() || ch.Trust < victim.Trust))
            {
                comm.act(ATTypes.AT_PLAIN, "$E has $S tells turned off.", ch, null, victim, ToTypes.Character);
                return;
            }

            if ((!ch.IsImmortal() && !victim.IsAwake()) ||
                (!victim.IsNpc() && victim.CurrentRoom.Flags.IsSet(RoomFlags.Silence)))
            {
                comm.act(ATTypes.AT_PLAIN, "$E can't hear you.", ch, null, victim, ToTypes.Character);
                return;
            }

            if (((PlayerInstance)victim).Descriptor != null &&
                ((PlayerInstance)victim).Descriptor.ConnectionStatus == ConnectionTypes.Editing &&
                ch.Trust < LevelConstants.GetLevel(ImmortalTypes.God))
            {
                comm.act(ATTypes.AT_PLAIN, "$E is currently in a writing buffer. Please try again later.", ch, null, victim, ToTypes.Character);
                return;
            }

            if (victim.IsIgnoring(ch))
            {
                if (!ch.IsImmortal() || victim.Trust > ch.Trust)
                {
                    ch.SetColor(ATTypes.AT_IGNORE);
                    ch.Printf("%s is ignoring you.\r\n", victim.Name);
                    return;
                }

                victim.SetColor(ATTypes.AT_IGNORE);
                victim.Printf("You attempt to ignore %s, but are unable to do so.\r\n", ch.Name);
            }

            comm.act(ATTypes.AT_TELL, "You tell $N '$t'", ch, argument, victim, ToTypes.Character);
            var position = victim.CurrentPosition;
            victim.CurrentPosition = PositionTypes.Standing;

#if !SCRAMBLE
            /*if (speaking != -1 && (!ch.IsNpc() || ch.Speaking > 0))
             * {
             *  int speakswell = victim.KnowsLanguage(ch.Speaking, ch).GetLowestOfTwoNumbers(ch.KnowsLanguage(ch.Speaking, victim));
             *  if (speakswell < 85)
             *      comm.act(ATTypes.AT_TELL, "$n tells you '$t'",
             *               ch, act_comm.TranslateLanguage(speakswell, argument,
             *                             GameConstants.LanguageTable[speaking]), victim, ToTypes.Victim);
             *  else
             *      comm.act(ATTypes.AT_TELL, "$n tells you '$t'",
             *               ch, argument, victim, ToTypes.Victim);
             * }
             * else
             *  comm.act(ATTypes.AT_TELL, "$n tells you '$t'", ch, argument, victim, ToTypes.Victim);*/
#else
            if (act_comm.KnowsLanguage(victim, ch.Speaking, ch) == 0 &&
                (ch.IsNpc() || ch.Speaking != 0))
            {
                comm.act(ATTypes.AT_TELL, "$n tells you '$t'", ch,
                         TranslateLanguage(speakswell, argument, GameConstants.LanguageTable[speaking]),
                         victim, ToTypes.Victim);
            }
            else
            {
                comm.act(ATTypes.AT_TELL, "$n tells you '$t'",
                         ch, scramble(argument, ch.Speaking), victim, ToTypes.Victim);
            }
#endif

            victim.CurrentPosition           = position;
            ((PlayerInstance)victim).ReplyTo = ch;
            ((PlayerInstance)ch).RetellTo    = victim;

            if (ch.CurrentRoom.Flags.IsSet((int)RoomFlags.LogSpeech))
            {
                var buffer =
                    $"{(ch.IsNpc() ? ch.ShortDescription : ch.Name)}: {argument} (tell to) {(victim.IsNpc() ? victim.ShortDescription : victim.Name)}";
                db.append_to_file(SystemConstants.GetSystemFile(SystemFileTypes.Log), buffer);
            }

            MudProgHandler.ExecuteMobileProg(MudProgTypes.Tell, argument, ch);
        }
Exemplo n.º 30
0
        protected void imgBtnUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload1.HasFile)     // CHECK IF ANY FILE HAS BEEN SELECTED.
            {
                if (fileUpload1.PostedFile.ContentLength >= SystemConstants.ImageLimitInByte())
                {
                    lblUploadStatus.Text      = "Maximum file size is 4MB.";
                    lblUploadStatus.ForeColor = Color.Red;
                }
                else
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(fileUpload1.PostedFile.ContentType, "image/\\S+"))
                    {
                        string ext = fileUpload1.PostedFile.ContentType;
                        if (ext == "bmp" || ext == ".bmp")
                        {
                            lblUploadStatus.Text      = ".bmp extension is not supported";
                            lblUploadStatus.ForeColor = Color.Red;
                        }
                        else
                        {
                            int iFailedCnt = 0;

                            string sFileName = Path.GetFileName(fileUpload1.FileName);

                            if (SizeUploaded <= SystemConstants.MaxActivityImageStorage)
                            {
                                Stream input  = fileUpload1.PostedFile.InputStream;
                                byte[] buffer = new byte[input.Length];
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    int read;
                                    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        ms.Write(buffer, 0, read);
                                    }
                                    if (isSupported)
                                    {
                                        UploadedTitle.Text            = "Preview";
                                        ProviderImagePreview.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(ms.ToArray());
                                    }
                                    else
                                    {
                                        ProviderImagePreview.Visible = false;
                                        lblimageTitle.Visible        = true;
                                        lblimageTitle.Text           = sFileName + " - " + SizeUploaded + "kb";
                                        UploadedTitle.Text           = "Uploaded Image";
                                    }
                                    hdnImageStream.Value = Convert.ToBase64String(ms.ToArray());
                                }

                                fileName = fileUpload1.FileName;

                                SizeUploaded   = fileUpload1.PostedFile.ContentLength / 1024;
                                ImageUploaded += 1;
                            }
                            else
                            {
                                iFailedCnt               += 1;
                                lblUploadStatus.Text     += "</br><b>" + iFailedCnt + "</b> file could not be uploaded. Maximum Size per activity is" + SystemConstants.MaxActivityImageStorage + " Kb";
                                lblUploadStatus.ForeColor = Color.Red;
                            }

                            lblUploadStatus.Text      = "Image uploaded.";
                            lblUploadStatus.ForeColor = ColorTranslator.FromHtml("#1B274F");
                        }
                    }
                    else
                    {
                        lblUploadStatus.Text = "Only image files are accepted."; lblUploadStatus.ForeColor = Color.Red;
                    }
                }
            }
            else
            {
                lblUploadStatus.Text = "No files selected."; lblUploadStatus.ForeColor = Color.Red;
            }
            lblUploadStatus.Visible = true;
            if (ImageUploaded > 0)
            {
                divUploadSuccessfull.Visible = true;
            }
        }
Exemplo n.º 31
0
        public override IEnumerable <MemberResult> GetDefinedMembers(int index, AstMemberType memberType, bool isMemberAccess = false)
        {
            HashSet <MemberResult> members = new HashSet <MemberResult>();

            HashSet <GeneroPackage> includedPackages = new HashSet <GeneroPackage>();

            if (memberType.HasFlag(AstMemberType.SystemTypes) && !isMemberAccess)
            {
                // Built-in types
                members.AddRange(BuiltinTypes.Select(x => new MemberResult(Tokens.TokenKinds[x], GeneroMemberType.Keyword, this)));

                foreach (var package in Packages.Values.Where(x => _importedPackages[x.Name] && x.ContainsInstanceMembers &&
                                                              (this.LanguageVersion >= x.MinimumLanguageVersion && this.LanguageVersion <= x.MaximumLanguageVersion)))
                {
                    members.Add(new MemberResult(package.Name, GeneroMemberType.Module, this));
                    includedPackages.Add(package);
                }
            }
            if (memberType.HasFlag(AstMemberType.Constants) && !isMemberAccess)
            {
                members.AddRange(SystemConstants.Where(x => this.LanguageVersion >= x.Value.MinimumLanguageVersion && this.LanguageVersion <= x.Value.MaximumLanguageVersion)
                                 .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Keyword, this)));
                members.AddRange(SystemMacros.Where(x => this.LanguageVersion >= x.Value.MinimumLanguageVersion && this.LanguageVersion <= x.Value.MaximumLanguageVersion)
                                 .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Constant, this)));
            }
            if (memberType.HasFlag(AstMemberType.Variables) && !isMemberAccess)
            {
                members.AddRange(SystemVariables.Where(x => this.LanguageVersion >= x.Value.MinimumLanguageVersion && this.LanguageVersion <= x.Value.MaximumLanguageVersion)
                                 .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Keyword, this)));
            }
            if (memberType.HasFlag(AstMemberType.Functions) && !isMemberAccess)
            {
                members.AddRange(SystemFunctions.Where(x => this.LanguageVersion >= x.Value.MinimumLanguageVersion && this.LanguageVersion <= x.Value.MaximumLanguageVersion)
                                 .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Function, this)));
                foreach (var package in Packages.Values.Where(x => _importedPackages[x.Name] && x.ContainsStaticClasses &&
                                                              (this.LanguageVersion >= x.MinimumLanguageVersion && this.LanguageVersion <= x.MaximumLanguageVersion)))
                {
                    if (!includedPackages.Contains(package))
                    {
                        members.Add(new MemberResult(package.Name, GeneroMemberType.Module, this));
                    }
                }
            }

            // TODO: need to handle multiple results of the same name
            AstNode containingNode = GetContainingNode(_body, index);

            if (containingNode != null)
            {
                if (containingNode is IFunctionResult)
                {
                    if (memberType.HasFlag(AstMemberType.Variables))
                    {
                        members.AddRange((containingNode as IFunctionResult).Variables.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)));
                        foreach (var varList in (containingNode as IFunctionResult).LimitedScopeVariables)
                        {
                            foreach (var item in varList.Value)
                            {
                                if (item.Item2.IsInSpan(index))
                                {
                                    members.Add(new MemberResult(item.Item1.Name, item.Item1, GeneroMemberType.Instance, this));
                                    break;
                                }
                            }
                        }
                    }
                    if (memberType.HasFlag(AstMemberType.SystemTypes))
                    {
                        members.AddRange((containingNode as IFunctionResult).Types.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Class, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.Constants))
                    {
                        members.AddRange((containingNode as IFunctionResult).Constants.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Constant, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.Functions))
                    {
                        foreach (var res in (containingNode as IFunctionResult).Variables /*.Where(x => x.Value.HasChildFunctions(this))
                                                                                           */.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)))
                        {
                            if (!members.Contains(res))
                            {
                                members.Add(res);
                            }
                        }

                        foreach (var varList in (containingNode as IFunctionResult).LimitedScopeVariables)
                        {
                            foreach (var item in varList.Value)
                            {
                                if (item.Item2.IsInSpan(index))
                                {
                                    members.Add(new MemberResult(item.Item1.Name, item.Item1, GeneroMemberType.Instance, this));
                                    break;
                                }
                            }
                        }
                    }
                }

                if (_body is IModuleResult)
                {
                    // check for module vars, types, and constants (and globals defined in this module)
                    if (memberType.HasFlag(AstMemberType.Variables))
                    {
                        members.AddRange((_body as IModuleResult).Variables.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)));
                        members.AddRange((_body as IModuleResult).GlobalVariables.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.UserDefinedTypes))
                    {
                        members.AddRange((_body as IModuleResult).Types.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Class, this)));
                        members.AddRange((_body as IModuleResult).GlobalTypes.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Class, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.Constants))
                    {
                        members.AddRange((_body as IModuleResult).Constants.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Constant, this)));
                        members.AddRange((_body as IModuleResult).GlobalConstants.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Constant, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.Dialogs))
                    {
                        members.AddRange((_body as IModuleResult).Functions.Where(x => x.Value is DeclarativeDialogBlock)
                                         .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Dialog, this)));
                        members.AddRange((_body as IModuleResult).FglImports.Select(x => new MemberResult(x, GeneroMemberType.Module, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.Reports))
                    {
                        members.AddRange((_body as IModuleResult).Functions.Where(x => x.Value is ReportBlockNode)
                                         .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Report, this)));
                    }
                    if (memberType.HasFlag(AstMemberType.Functions))
                    {
                        members.AddRange((_body as IModuleResult).Functions
                                         .Where(x => !(x.Value is ReportBlockNode) && !(x.Value is DeclarativeDialogBlock))
                                         .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Method, this)));
                        foreach (var res in (_body as IModuleResult).Variables /*.Where(x => x.Value.HasChildFunctions(this))
                                                                                */.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)))
                        {
                            if (!members.Contains(res))
                            {
                                members.Add(res);
                            }
                        }
                        foreach (var res in (_body as IModuleResult).GlobalVariables /*.Where(x => x.Value.HasChildFunctions(this))
                                                                                      */.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)))
                        {
                            if (!members.Contains(res))
                            {
                                members.Add(res);
                            }
                        }
                    }

                    // Tables and cursors are module specific, and cannot be accessed via fgl import
                    if (memberType.HasFlag(AstMemberType.DeclaredCursors) ||
                        memberType.HasFlag(AstMemberType.PreparedCursors) ||
                        memberType.HasFlag(AstMemberType.Tables))
                    {
                        if (memberType.HasFlag(AstMemberType.DeclaredCursors))
                        {
                            members.AddRange((_body as IModuleResult).Cursors.Where(x => x.Value is DeclareStatement).Select(x => new MemberResult(x.Value.Name, x.Value, GeneroMemberType.Cursor, this)));
                        }
                        if (memberType.HasFlag(AstMemberType.PreparedCursors))
                        {
                            members.AddRange((_body as IModuleResult).Cursors.Where(x => x.Value is PrepareStatement).Select(x => new MemberResult(x.Value.Name, x.Value, GeneroMemberType.Cursor, this)));
                        }
                        if (memberType.HasFlag(AstMemberType.Tables))
                        {
                            members.AddRange((_body as IModuleResult).Tables.Select(x => new MemberResult(x.Value.Name, x.Value, GeneroMemberType.DbTable, this)));
                        }
                    }
                    else
                    {
                        members.AddRange((_body as IModuleResult).FglImports.Select(x => new MemberResult(x, GeneroMemberType.Module, this)));
                    }
                }
            }

            // TODO: this could probably be done more efficiently by having each GeneroAst load globals and functions into
            // dictionaries stored on the IGeneroProject, instead of in each project entry.
            // However, this does required more upkeep when changes occur. Will look into it...
            if (_projEntry != null && _projEntry is IGeneroProjectEntry)
            {
                IGeneroProjectEntry genProj = _projEntry as IGeneroProjectEntry;
                if (genProj.ParentProject != null &&
                    !genProj.FilePath.ToLower().EndsWith(".inc"))
                {
                    foreach (var projEntry in genProj.ParentProject.ProjectEntries.Where(x => x.Value != genProj))
                    {
                        if (projEntry.Value.Analysis != null &&
                            projEntry.Value.Analysis.Body != null)
                        {
                            projEntry.Value.Analysis.Body.SetNamespace(null);
                            IModuleResult modRes = projEntry.Value.Analysis.Body as IModuleResult;
                            if (modRes != null)
                            {
                                // check global types
                                // TODO: need to add an option to enable/disable legacy linking (to not reference other modules' non-public members
                                if (memberType.HasFlag(AstMemberType.Variables))
                                {
                                    members.AddRange(modRes.GlobalVariables.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)));
                                    members.AddRange(modRes.Variables.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)));
                                }
                                if (memberType.HasFlag(AstMemberType.UserDefinedTypes))
                                {
                                    members.AddRange(modRes.GlobalTypes.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Class, this)));
                                    members.AddRange(modRes.Types.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Class, this)));
                                }
                                if (memberType.HasFlag(AstMemberType.Constants))
                                {
                                    members.AddRange(modRes.GlobalConstants.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Constant, this)));
                                    members.AddRange(modRes.Constants.Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Constant, this)));
                                }
                                if (memberType.HasFlag(AstMemberType.Dialogs))
                                {
                                    members.AddRange(modRes.Functions.Where(x => x.Value is DeclarativeDialogBlock)
                                                     .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Dialog, this)));
                                }
                                if (memberType.HasFlag(AstMemberType.Reports))
                                {
                                    members.AddRange(modRes.Functions.Where(x => x.Value is ReportBlockNode)
                                                     .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Report, this)));
                                }
                                if (memberType.HasFlag(AstMemberType.Functions))
                                {
                                    members.AddRange(modRes.Functions.Where(x => !(x.Value is ReportBlockNode) && !(x.Value is DeclarativeDialogBlock))
                                                     .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Method, this)));
                                    foreach (var res in modRes.GlobalVariables/*.Where(x =>
                                                                               * {
                                                                               * return x.Value.HasChildFunctions(this);
                                                                               * })*/
                                             .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)))
                                    {
                                        if (!members.Contains(res))
                                        {
                                            members.Add(res);
                                        }
                                    }
                                    foreach (var res in modRes.Variables/*.Where(x =>
                                                                         * {
                                                                         * return x.Value.HasChildFunctions(this);
                                                                         * })*/
                                             .Select(x => new MemberResult(x.Key, x.Value, GeneroMemberType.Variable, this)))
                                    {
                                        if (!members.Contains(res))
                                        {
                                            members.Add(res);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (memberType.HasFlag(AstMemberType.Functions))
            {
                _includePublicFunctions = true; // allow for deferred adding of public functions
            }

            if (memberType.HasFlag(AstMemberType.Tables))
            {
                _includeDatabaseTables = true;  // allow for deferred adding of external database tables
            }

            members.AddRange(this.ProjectEntry.GetIncludedFiles().Where(x => x.Analysis != null).SelectMany(x => x.Analysis.GetDefinedMembers(1, memberType)));

            return(members);
        }
Exemplo n.º 32
0
        public static IAnalysisResult GetValueByIndex(string exprText, int index, Genero4glAst ast, out IGeneroProject definingProject, out IProjectEntry projectEntry, out bool isDeferredFunction,
                                                      FunctionProviderSearchMode searchInFunctionProvider = FunctionProviderSearchMode.NoSearch, bool isFunctionCallOrDefinition = false,
                                                      bool getTypes = true, bool getVariables = true, bool getConstants = true)
        {
            isDeferredFunction = false;
            definingProject    = null;
            projectEntry       = null;
            //_functionProvider = functionProvider;
            //_databaseProvider = databaseProvider;
            //_programFileProvider = programFileProvider;

            AstNode containingNode = null;

            if (ast != null)
            {
                containingNode = GetContainingNode(ast.Body, index);
                ast.Body.SetNamespace(null);
            }

            IAnalysisResult res = null;
            int             tmpIndex = 0;
            int             bracketDepth = 0;
            bool            doSearch = false;
            bool            resetStartIndex = false;
            int             startIndex = 0, endIndex = 0;
            bool            noEndIndexSet = false;

            if (exprText == null)
            {
                return(null);
            }

            while (tmpIndex < exprText.Length)
            {
                if (resetStartIndex)
                {
                    startIndex      = tmpIndex;
                    resetStartIndex = false;
                    if (startIndex + 1 > exprText.Length)
                    {
                        break;
                    }
                }

                doSearch = false;
                switch (exprText[tmpIndex])
                {
                case '.':
                {
                    if (bracketDepth == 0)
                    {
                        endIndex = tmpIndex - 1;
                        if (endIndex >= startIndex)
                        {
                            // we have our 'piece'
                            doSearch = true;
                        }
                        if (exprText[startIndex] == '.')
                        {
                            startIndex++;
                        }
                    }
                    tmpIndex++;
                }
                break;

                case '[':
                    if (noEndIndexSet)
                    {
                        noEndIndexSet = false;
                    }
                    else
                    {
                        if (bracketDepth == 0)
                        {
                            endIndex = tmpIndex - 1;
                        }
                    }
                    bracketDepth++;
                    tmpIndex++;
                    break;

                case ']':
                {
                    bracketDepth--;
                    if (bracketDepth == 0)
                    {
                        if (exprText.Length <= tmpIndex + 1 ||
                            exprText[tmpIndex + 1] != '[')
                        {
                            // we have our first 'piece'
                            doSearch = true;
                        }
                        else
                        {
                            noEndIndexSet = true;
                        }
                    }
                    tmpIndex++;
                }
                break;

                default:
                {
                    if (bracketDepth == 0 && (tmpIndex + 1 == exprText.Length))
                    {
                        endIndex = tmpIndex;
                        doSearch = true;
                    }
                    tmpIndex++;
                }
                break;
                }

                if (!doSearch)
                {
                    continue;
                }

                // we can do our search
                var dotPiece = exprText.Substring(startIndex, (endIndex - startIndex) + 1);
                if (dotPiece.Contains('('))
                {
                    // remove the params piece
                    int remIndex = dotPiece.IndexOf('(');
                    dotPiece = dotPiece.Substring(0, remIndex);
                }

                bool lookForFunctions = isFunctionCallOrDefinition && (endIndex + 1 == exprText.Length);

                resetStartIndex = true;

                if (res != null)
                {
                    if (ast != null)
                    {
                        var gmi = new GetMemberInput
                        {
                            Name       = dotPiece,
                            AST        = ast,
                            IsFunction = lookForFunctions
                        };
                        IAnalysisResult tempRes = res.GetMember(gmi);
                        if (gmi.DefiningProject != null && definingProject != gmi.DefiningProject)
                        {
                            definingProject = gmi.DefiningProject;
                        }
                        if (gmi.ProjectEntry != null && projectEntry != gmi.ProjectEntry)
                        {
                            projectEntry = gmi.ProjectEntry;
                        }
                        res = tempRes;
                        if (tempRes == null)
                        {
                            res = null;
                            break;
                        }
                    }
                    else
                    {
                        res = null;
                        break;
                    }
                }
                else
                {
                    IFunctionResult funcRes;
                    if (!lookForFunctions)
                    {
                        if (SystemVariables.TryGetValue(dotPiece, out res) ||
                            SystemConstants.TryGetValue(dotPiece, out res) ||
                            SystemMacros.TryGetValue(dotPiece, out res))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (SystemFunctions.TryGetValue(dotPiece, out funcRes))
                        {
                            res = funcRes;
                            continue;
                        }

                        if (ast != null && ast._functionProvider != null && ast._functionProvider.Name.Equals(dotPiece, StringComparison.OrdinalIgnoreCase))
                        {
                            res = ast._functionProvider;
                            continue;
                        }
                    }

                    if (containingNode != null && containingNode is IFunctionResult)
                    {
                        IFunctionResult func = containingNode as IFunctionResult;
                        if ((getVariables && func.Variables.TryGetValue(dotPiece, out res)))
                        {
                            continue;
                        }
                        if (!lookForFunctions)
                        {
                            // Check for local vars, types, and constants
                            if ((getTypes && func.Types.TryGetValue(dotPiece, out res)) ||
                                (getConstants && func.Constants.TryGetValue(dotPiece, out res)))
                            {
                                continue;
                            }

                            List <Tuple <IAnalysisResult, IndexSpan> > limitedScopeVars;
                            if ((getVariables && func.LimitedScopeVariables.TryGetValue(dotPiece, out limitedScopeVars)))
                            {
                                foreach (var item in limitedScopeVars)
                                {
                                    if (item.Item2.IsInSpan(index))
                                    {
                                        res = item.Item1;

                                        break;
                                    }
                                }
                                if (res != null)
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    if (ast != null && ast.Body is IModuleResult)
                    {
                        IModuleResult mod = ast.Body as IModuleResult;
                        if (!lookForFunctions)
                        {
                            // check for module vars, types, and constants (and globals defined in this module)
                            if ((getVariables && (mod.Variables.TryGetValue(dotPiece, out res) || mod.GlobalVariables.TryGetValue(dotPiece, out res))) ||
                                (getTypes && (mod.Types.TryGetValue(dotPiece, out res) || mod.GlobalTypes.TryGetValue(dotPiece, out res))) ||
                                (getConstants && (mod.Constants.TryGetValue(dotPiece, out res) || mod.GlobalConstants.TryGetValue(dotPiece, out res))))
                            {
                                continue;
                            }

                            // check for cursors in this module
                            if (mod.Cursors.TryGetValue(dotPiece, out res))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            // check for module functions
                            if (mod.Functions.TryGetValue(dotPiece, out funcRes))
                            {
                                // check for any function info collected at the project entry level, and update the function's documentation with that.
                                if (ast._projEntry != null && ast._projEntry is IGeneroProjectEntry)
                                {
                                    var commentInfo = (ast._projEntry as IGeneroProjectEntry).GetFunctionInfo(funcRes.Name);
                                    if (commentInfo != null)
                                    {
                                        funcRes.SetCommentDocumentation(commentInfo);
                                    }
                                }
                                res = funcRes;
                                continue;
                            }
                        }
                    }

                    // TODO: this could probably be done more efficiently by having each GeneroAst load globals and functions into
                    // dictionaries stored on the IGeneroProject, instead of in each project entry.
                    // However, this does required more upkeep when changes occur. Will look into it...
                    if (ast != null && ast.ProjectEntry != null && ast.ProjectEntry is IGeneroProjectEntry)
                    {
                        IGeneroProjectEntry genProj = ast.ProjectEntry as IGeneroProjectEntry;
                        if (genProj.ParentProject != null &&
                            !genProj.FilePath.ToLower().EndsWith(".inc"))
                        {
                            bool found = false;
                            foreach (var projEntry in genProj.ParentProject.ProjectEntries.Where(x => x.Value != genProj))
                            {
                                if (projEntry.Value.Analysis != null &&
                                    projEntry.Value.Analysis.Body != null)
                                {
                                    projEntry.Value.Analysis.Body.SetNamespace(null);
                                    IModuleResult modRes = projEntry.Value.Analysis.Body as IModuleResult;
                                    if (modRes != null)
                                    {
                                        if (!lookForFunctions)
                                        {
                                            // check global vars, types, and constants
                                            // TODO: need option to enable/disable legacy linking
                                            if ((getVariables && (modRes.Variables.TryGetValue(dotPiece, out res) || modRes.GlobalVariables.TryGetValue(dotPiece, out res))) ||
                                                (getTypes && (modRes.Types.TryGetValue(dotPiece, out res) || modRes.GlobalTypes.TryGetValue(dotPiece, out res))) ||
                                                (getConstants && (modRes.Constants.TryGetValue(dotPiece, out res) || modRes.GlobalConstants.TryGetValue(dotPiece, out res))))
                                            {
                                                found = true;
                                                break;
                                            }

                                            // check for cursors in this module
                                            if (modRes.Cursors.TryGetValue(dotPiece, out res))
                                            {
                                                found = true;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            // check project functions
                                            if (modRes.Functions.TryGetValue(dotPiece, out funcRes))
                                            {
                                                if (funcRes.AccessModifier == AccessModifier.Public)
                                                {
                                                    res   = funcRes;
                                                    found = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (found)
                            {
                                continue;
                            }
                        }
                    }

                    // check for classes
                    GeneroPackage package;
                    if (Packages.TryGetValue(dotPiece, out package))
                    {
                        res = package;
                        continue;
                    }

                    /* TODO:
                     * Need to check for:
                     * 1) Temp tables
                     */

                    // Nothing found yet...
                    // If our containing node is at the function or globals level, we need to go deeper
                    if (containingNode != null &&
                        (containingNode is GlobalsNode ||
                         containingNode is FunctionBlockNode ||
                         containingNode is ReportBlockNode))
                    {
                        containingNode = GetContainingNode(containingNode, index);
                    }
                    // check for record field
                    if (containingNode != null &&
                        (containingNode is DefineNode ||
                         containingNode is TypeDefNode))
                    {
                        containingNode = GetContainingNode(containingNode, index);

                        if (containingNode != null &&
                            (containingNode is VariableDefinitionNode ||
                             containingNode is TypeDefinitionNode) &&
                            containingNode.Children.Count == 1 &&
                            containingNode.Children[containingNode.Children.Keys[0]] is TypeReference)
                        {
                            var typeRef = containingNode.Children[containingNode.Children.Keys[0]] as TypeReference;
                            while (typeRef != null &&
                                   typeRef.Children.Count == 1)
                            {
                                if (typeRef.Children[typeRef.Children.Keys[0]] is RecordDefinitionNode)
                                {
                                    var         recNode = typeRef.Children[typeRef.Children.Keys[0]] as RecordDefinitionNode;
                                    VariableDef recField;
                                    if (recNode.MemberDictionary.TryGetValue(exprText, out recField))
                                    {
                                        res = recField;
                                        break;
                                    }
                                    else
                                    {
                                        recField = recNode.MemberDictionary.Where(x => x.Value.LocationIndex < index)
                                                   .OrderByDescending(x => x.Value.LocationIndex)
                                                   .Select(x => x.Value)
                                                   .FirstOrDefault();
                                        if (recField != null)
                                        {
                                            typeRef = recField.Type;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                else if (typeRef.Children[typeRef.Children.Keys[0]] is TypeReference)
                                {
                                    typeRef = typeRef.Children[typeRef.Children.Keys[0]] as TypeReference;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    // try an imported module
                    if (ast != null && ast.Body is IModuleResult &&
                        ast.ProjectEntry != null && ast.ProjectEntry != null)
                    {
                        if ((ast.Body as IModuleResult).FglImports.Contains(dotPiece))
                        {
                            // need to get the ast for the other project entry
                            var refProjKVP = (ast.ProjectEntry as IGeneroProjectEntry).ParentProject.ReferencedProjects.Values.FirstOrDefault(
                                x =>
                            {
                                var fn = Path.GetFileNameWithoutExtension(x.Directory);
                                return(fn?.Equals(dotPiece, StringComparison.OrdinalIgnoreCase) ?? false);
                            });
                            if (refProjKVP is IAnalysisResult)
                            {
                                definingProject = refProjKVP;
                                res             = refProjKVP as IAnalysisResult;
                                continue;
                            }

                            IAnalysisResult sysImportMod;
                            // check the system imports
                            if (SystemImportModules.TryGetValue(dotPiece, out sysImportMod))
                            {
                                res = sysImportMod;
                                continue;
                            }
                        }
                    }

                    if (!lookForFunctions)
                    {
                        // try include files
                        var foundInclude = false;
                        if (ast?.ProjectEntry != null)
                        {
                            foreach (var includeFile in ast.ProjectEntry.GetIncludedFiles())
                            {
                                if (includeFile.Analysis?.Body is IModuleResult)
                                {
                                    var mod = includeFile.Analysis.Body as IModuleResult;
                                    if ((getTypes && (mod.Types.TryGetValue(dotPiece, out res) || mod.GlobalTypes.TryGetValue(dotPiece, out res))) ||
                                        (getConstants && (mod.Constants.TryGetValue(dotPiece, out res) || mod.GlobalConstants.TryGetValue(dotPiece, out res))))
                                    {
                                        foundInclude = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (foundInclude)
                        {
                            continue;
                        }

                        if (ast?._databaseProvider != null)
                        {
                            res = ast._databaseProvider.GetTable(dotPiece);
                            if (res != null)
                            {
                                continue;
                            }
                        }
                    }

                    // Only do a public function search if the dotPiece is the whole text we're searching for
                    // I.e. no namespaces
                    if (lookForFunctions && dotPiece == exprText)
                    {
                        if (searchInFunctionProvider == FunctionProviderSearchMode.Search)
                        {
                            if (res == null && ast?._functionProvider != null)
                            {
                                // check for the function name in the function provider
                                var funcs = ast._functionProvider.GetFunction(dotPiece);
                                if (funcs != null)
                                {
                                    res = funcs.FirstOrDefault();
                                    if (res != null)
                                    {
                                        continue;
                                    }
                                }
                            }
                        }
                        else if (searchInFunctionProvider == FunctionProviderSearchMode.Deferred)
                        {
                            isDeferredFunction = true;
                        }
                    }

                    if (res == null)
                    {
                        break;
                    }
                }
            }

            return(res);
        }