public void GetTenantDetailsTest() { DataAccessHelper target = new DataAccessHelper(); // TODO: Initialize to an appropriate value string strTenantID = string.Empty; // TODO: Initialize to an appropriate value Tenant expected = null; // TODO: Initialize to an appropriate value Tenant actual; strTenantID = "C428C08B-A863-4814-A250-58F7421F5FF0"; actual = target.GetTenantDetails(strTenantID); Assert.AreEqual(expected, actual); // Assert.Inconclusive("Verify the correctness of this test method."); }
public RecipeItemDTO Insert(RecipeItemDTO recipeItem) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { RecipeItem entity = new RecipeItem(); Mapper.Mappers.RecipeItemMapper.ToRecipeItem(recipeItem, entity); context.RecipeItem.Add(entity); context.SaveChanges(); if (Mapper.Mappers.RecipeItemMapper.ToRecipeItemDTO(entity, recipeItem)) { return(recipeItem); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public NpcMonsterDTO Insert(NpcMonsterDTO npc) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { NpcMonster entity = new NpcMonster(); Mapper.Mappers.NpcMonsterMapper.ToNpcMonster(npc, entity); context.NpcMonster.Add(entity); context.SaveChanges(); if (Mapper.Mappers.NpcMonsterMapper.ToNpcMonsterDTO(entity, npc)) { return(npc); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public SaveResult InsertOrUpdate(ref MinigameLogDTO minigameLog) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { long minigameLogId = minigameLog.MinigameLogId; MinigameLog entity = context.MinigameLog.FirstOrDefault(c => c.MinigameLogId.Equals(minigameLogId)); if (entity == null) { minigameLog = Insert(minigameLog, context); return(SaveResult.Inserted); } minigameLog = Update(entity, minigameLog, context); return(SaveResult.Updated); } } catch (Exception e) { Logger.Error(e); return(SaveResult.Error); } }
public ShopItemDTO Insert(ShopItemDTO item) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { ShopItem entity = new ShopItem(); Mapper.Mappers.ShopItemMapper.ToShopItem(item, entity); context.ShopItem.Add(entity); context.SaveChanges(); if (Mapper.Mappers.ShopItemMapper.ToShopItemDTO(entity, item)) { return(item); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public async Task <List <Roles> > GetAdminRoles() { try { _DataHelper = new DataAccessHelper("Admin_GetAllAdminRoles", _configuration); DataTable dt = new DataTable(); await _DataHelper.RunAsync(dt); List <Roles> adminRoles = new List <Roles>(); if (dt.Rows.Count > 0) { adminRoles = (from model in dt.AsEnumerable() select new Roles() { RoleID = model.Field <int>("RoleID"), Role = model.Field <string>("Role") }).ToList(); } return(adminRoles); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw (ex); } finally { _DataHelper.Dispose(); } }
public SaveResult InsertOrUpdate(ref CharacterDTO character) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { long characterId = character.CharacterId; Character entity = context.Character.FirstOrDefault(c => c.CharacterId.Equals(characterId)); if (entity == null) { character = Insert(character, context); return(SaveResult.Inserted); } character = Update(entity, character, context); return(SaveResult.Updated); } } catch (Exception e) { Logger.Log.Error(string.Format(Language.Instance.GetMessageFromKey("INSERT_ERROR"), character, e.Message), e); return(SaveResult.Error); } }
public DeleteResult DeleteByPrimaryKey(long accountId, byte characterSlot) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { // actually a Character wont be deleted, it just will be disabled for future traces Character character = context.Character.SingleOrDefault(c => c.AccountId.Equals(accountId) && c.Slot.Equals(characterSlot) && c.State.Equals((byte)CharacterState.Active)); if (character != null) { character.State = (byte)CharacterState.Inactive; context.SaveChanges(); } return(DeleteResult.Deleted); } } catch (Exception e) { Logger.Error(string.Format(Language.Instance.GetMessageFromKey("DELETE_CHARACTER_ERROR"), characterSlot, e.Message), e); return(DeleteResult.Error); } }
public async Task <DatabaseResponse> GetVisitersCount() { try { _DataHelper = new DataAccessHelper("sps_Visiters", _configuration); DataSet ds = new DataSet(); int result = await _DataHelper.RunAsync(ds); Visiters visiters = new Visiters(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0) { visiters = (from model in ds.Tables[0].AsEnumerable() select new Visiters() { TotalVisits = model.Field <int?>("TotalVisit") }).FirstOrDefault(); } return(new DatabaseResponse { ResponseCode = result, Results = visiters }); } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw; } finally { _DataHelper.Dispose(); } }
public MaintenanceLogDTO Insert(MaintenanceLogDTO maintenanceLog) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { MaintenanceLog entity = new MaintenanceLog(); Mapper.Mapper.Instance.MaintenanceLogMapper.ToMaintenanceLog(maintenanceLog, entity); context.MaintenanceLog.Add(entity); context.SaveChanges(); if (Mapper.Mapper.Instance.MaintenanceLogMapper.ToMaintenanceLogDTO(entity, maintenanceLog)) { return(maintenanceLog); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public MapNpcDTO Insert(MapNpcDTO npc) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { MapNpc entity = new MapNpc(); Mapper.Mappers.MapNpcMapper.ToMapNpc(npc, entity); context.MapNpc.Add(entity); context.SaveChanges(); if (Mapper.Mappers.MapNpcMapper.ToMapNpcdto(entity, npc)) { return(npc); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public CardDTO Insert(ref CardDTO card) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { Card entity = new Card(); Mapper.Mappers.CardMapper.ToCard(card, entity); context.Card.Add(entity); context.SaveChanges(); if (Mapper.Mappers.CardMapper.ToCardDTO(entity, card)) { return(card); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public FamilyDTO LoadByCharacterId(long characterId) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { FamilyCharacter familyCharacter = context.FamilyCharacter.FirstOrDefault(fc => fc.Character.CharacterId.Equals(characterId)); if (familyCharacter != null) { Family family = context.Family.FirstOrDefault(a => a.FamilyId.Equals(familyCharacter.FamilyId)); if (family != null) { return(_mapper.Map <FamilyDTO>(family)); } } } } catch (Exception e) { Logger.Error(e); } return(null); }
public ShopSkillDTO Insert(ShopSkillDTO shopSkill) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { ShopSkill entity = new ShopSkill(); Mapper.Mappers.ShopSkillMapper.ToShopSkill(shopSkill, entity); context.ShopSkill.Add(entity); context.SaveChanges(); if (Mapper.Mappers.ShopSkillMapper.ToShopSkillDTO(entity, shopSkill)) { return(shopSkill); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public ScriptedInstanceDTO Insert(ScriptedInstanceDTO scriptedInstance) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { ScriptedInstance entity = new ScriptedInstance(); Mapper.Mappers.ScriptedInstanceMapper.ToScriptedInstance(scriptedInstance, entity); context.ScriptedInstance.Add(entity); context.SaveChanges(); if (Mapper.Mappers.ScriptedInstanceMapper.ToScriptedInstanceDTO(entity, scriptedInstance)) { return(scriptedInstance); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public DeleteResult DeleteById(long mailId) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { Mail mail = context.Mail.First(i => i.MailId.Equals(mailId)); if (mail == null) { return(DeleteResult.Deleted); } context.Mail.Remove(mail); context.SaveChanges(); return(DeleteResult.Deleted); } } catch (Exception e) { Logger.Error(e); return(DeleteResult.Error); } }
public WarpPointDTO Insert(WarpPointDTO warppoint) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { WarpPoint entity = new WarpPoint(); Mapper.Mappers.WarpPointMapper.ToWarpPoint(warppoint, entity); context.WarpPoint.Add(entity); context.SaveChanges(); if (Mapper.Mappers.WarpPointMapper.ToWarpPointDTO(entity, warppoint)) { return(warppoint); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public BCardDTO Insert(ref BCardDTO cardObject) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { BCard entity = new BCard(); Mapper.Mapper.Instance.BCardMapper.ToBCard(cardObject, entity); context.BCard.Add(entity); context.SaveChanges(); if (Mapper.Mapper.Instance.BCardMapper.ToBCardDTO(entity, cardObject)) { return(cardObject); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public ComboDTO Insert(ComboDTO combo) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { Combo entity = new Combo(); Mapper.Mappers.ComboMapper.ToCombo(combo, entity); context.Combo.Add(entity); context.SaveChanges(); if (Mapper.Mappers.ComboMapper.ToComboDTO(entity, combo)) { return(combo); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public SaveResult InsertOrUpdate(ref AccountDTO account) { try { using (var context = DataAccessHelper.CreateContext()) { long accountId = account.AccountId; Account entity = context.Account.FirstOrDefault(c => c.AccountId.Equals(accountId)); if (entity == null) { account = Insert(account, context); return(SaveResult.Inserted); } account = Update(entity, account, context); return(SaveResult.Updated); } } catch (Exception e) { Logger.Log.Error(string.Format(Language.Instance.GetMessageFromKey("UPDATE_ACCOUNT_ERROR"), account.AccountId, e.Message), e); return(SaveResult.Error); } }
public TeleporterDTO Insert(TeleporterDTO teleporter) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { Teleporter entity = new Teleporter(); Mapper.Mappers.TeleporterMapper.ToTeleporter(teleporter, entity); context.Teleporter.Add(entity); context.SaveChanges(); if (Mapper.Mappers.TeleporterMapper.ToTeleporterDTO(entity, teleporter)) { return(teleporter); } return(null); } } catch (Exception e) { Logger.Error(e); return(null); } }
public async Task <DatabaseResponse> UpdateAdminProfile(int AdminUserID, AdminProfile adminuser) { try { SqlParameter[] parameters = { new SqlParameter("@AdminID", SqlDbType.Int), new SqlParameter("@Name", SqlDbType.NVarChar), new SqlParameter("@NewPassword", SqlDbType.NVarChar) }; parameters[0].Value = AdminUserID; parameters[1].Value = adminuser.Name; parameters[2].Value = new Sha2().Hash(adminuser.NewPassword); _DataHelper = new DataAccessHelper("Admin_UpdateProfile", parameters, _configuration); DataTable dt = new DataTable(); int result = await _DataHelper.RunAsync(dt); return(new DatabaseResponse { ResponseCode = result, Results = adminuser }); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw (ex); } finally { _DataHelper.Dispose(); } }
public RecipeDTO Insert(RecipeDTO recipe) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { Recipe entity = new Recipe(); Mapper.Mappers.RecipeMapper.ToRecipe(recipe, entity); context.Recipe.Add(entity); context.SaveChanges(); if (Mapper.Mappers.RecipeMapper.ToRecipeDTO(entity, recipe)) { return recipe; } return null; } } catch (Exception e) { Logger.Error(e); return null; } }
public GeneralLogDTO Insert(GeneralLogDTO generalLog) { try { using (OpenNosContext context = DataAccessHelper.CreateContext()) { GeneralLog entity = new GeneralLog(); Mapper.Mappers.GeneralLogMapper.ToGeneralLog(generalLog, entity); context.GeneralLog.Add(entity); context.SaveChanges(); if (Mapper.Mappers.GeneralLogMapper.ToGeneralLogDTO(entity, generalLog)) { return generalLog; } return null; } } catch (Exception e) { Logger.Error(e); return null; } }
public static async Task Main(string[] args) { try { Console.Title = Title; } catch (PlatformNotSupportedException) { } Logger.PrintHeader(ConsoleText); InitializeConfiguration(); TypeAdapterConfig.GlobalSettings.Default.IgnoreAttribute(typeof(I18NFromAttribute)); TypeAdapterConfig.GlobalSettings.Default .IgnoreMember((member, side) => side == MemberSide.Destination && member.Type.GetInterfaces().Contains(typeof(IEntity)) || (member.Type.GetGenericArguments().Any() && member.Type.GetGenericArguments()[0].GetInterfaces().Contains(typeof(IEntity)))); try { var optionsBuilder = new DbContextOptionsBuilder <NosCoreContext>(); optionsBuilder.UseNpgsql(ParserConfiguration.Database !.ConnectionString); var dataAccess = new DataAccessHelper(); dataAccess.Initialize(optionsBuilder.Options); try { _logger.Warning(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.ENTER_PATH)); var folder = string.Empty; var key = default(ConsoleKeyInfo); if (args.Length == 0) { folder = Console.ReadLine(); _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_ALL)} [Y/n]"); key = Console.ReadKey(true); } else { folder = args.Aggregate(folder, (current, str) => current + str + " "); } var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterLogger(); containerBuilder.Register <IDbContextBuilder>(c => dataAccess).AsImplementedInterfaces().SingleInstance(); containerBuilder.RegisterAssemblyTypes(typeof(CardParser).Assembly) .Where(t => t.Name.EndsWith("Parser") && !t.IsGenericType) .AsSelf() .PropertiesAutowired(); containerBuilder.RegisterType <ImportFactory>().PropertiesAutowired(); var registerDatabaseObject = typeof(Parser).GetMethod(nameof(RegisterDatabaseObject)); var assemblyDto = typeof(IStaticDto).Assembly.GetTypes(); var assemblyDb = typeof(Account).Assembly.GetTypes(); assemblyDto.Where(p => typeof(IDto).IsAssignableFrom(p) && !p.Name.Contains("InstanceDto") && p.IsClass) .ToList() .ForEach(t => { var type = assemblyDb.First(tgo => string.Compare(t.Name, $"{tgo.Name}Dto", StringComparison.OrdinalIgnoreCase) == 0); var typepk = type.GetProperties() .Where(s => dataAccess.CreateContext().Model.FindEntityType(type) .FindPrimaryKey().Properties.Select(x => x.Name) .Contains(s.Name) ).ToArray()[0]; registerDatabaseObject?.MakeGenericMethod(t, type, typepk !.PropertyType).Invoke(null, new[] { containerBuilder, (object)typeof(IStaticDto).IsAssignableFrom(t) }); }); containerBuilder.RegisterType <Dao <ItemInstance, IItemInstanceDto?, Guid> >().As <IDao <IItemInstanceDto?, Guid> >() .SingleInstance(); var container = containerBuilder.Build(); var factory = container.Resolve <ImportFactory>(); factory.SetFolder(folder); await factory.ImportPacketsAsync().ConfigureAwait(false); if (key.KeyChar != 'n') { await factory.ImportAccountsAsync().ConfigureAwait(false); await factory.ImportMapsAsync().ConfigureAwait(false); await factory.ImportRespawnMapTypeAsync().ConfigureAwait(false); await factory.ImportMapTypeAsync().ConfigureAwait(false); await factory.ImportMapTypeMapAsync().ConfigureAwait(false); await factory.ImportPortalsAsync().ConfigureAwait(false); await factory.ImportI18NAsync().ConfigureAwait(false); //factory.ImportScriptedInstances(); await factory.ImportItemsAsync().ConfigureAwait(false); await factory.ImportSkillsAsync().ConfigureAwait(false); await factory.ImportCardsAsync().ConfigureAwait(false); await factory.ImportNpcMonstersAsync().ConfigureAwait(false); await factory.ImportDropsAsync().ConfigureAwait(false); //factory.ImportNpcMonsterData(); await factory.ImportMapNpcsAsync().ConfigureAwait(false); await factory.ImportMapMonstersAsync().ConfigureAwait(false); await factory.ImportShopsAsync().ConfigureAwait(false); //factory.ImportTeleporters(); await factory.ImportShopItemsAsync().ConfigureAwait(false); //factory.ImportShopSkills(); //factory.ImportRecipe(); await factory.ImportScriptsAsync().ConfigureAwait(false); await factory.ImportQuestsAsync().ConfigureAwait(false); } else { _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_MAPS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportMapsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_MAPTYPES)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportRespawnMapTypeAsync().ConfigureAwait(false); await factory.ImportMapTypeAsync().ConfigureAwait(false); await factory.ImportMapTypeMapAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_ACCOUNTS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportAccountsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_PORTALS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportPortalsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_I18N)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportI18NAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_TIMESPACES)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { //factory.ImportScriptedInstances(); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_ITEMS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportItemsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_NPCMONSTERS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportNpcMonstersAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_DROPS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportDropsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_NPCMONSTERDATA)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { //factory.ImportNpcMonsterData(); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_CARDS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportCardsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_SKILLS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportSkillsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_MAPNPCS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportMapNpcsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_MONSTERS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportMapMonstersAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_SHOPS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportShopsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_TELEPORTERS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { //factory.ImportTeleporters(); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_SHOPITEMS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportShopItemsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_SHOPSKILLS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { //factory.ImportShopSkills(); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_RECIPES)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { //factory.ImportRecipe(); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_SCRIPTS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportScriptsAsync().ConfigureAwait(false); } _logger.Information( $"{LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.PARSE_QUESTS)} [Y/n]"); key = Console.ReadKey(true); if (key.KeyChar != 'n') { await factory.ImportQuestsAsync().ConfigureAwait(false); } } _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.DONE)); Thread.Sleep(5000); } catch (FileNotFoundException) { _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.AT_LEAST_ONE_FILE_MISSING)); Thread.Sleep(5000); } } catch (Exception ex) { _logger.Error(ex.Message, ex); Console.ReadKey(); } }
public async Task <DatabaseResponse> PutAsync(EducationLevelUpdate educationLevelUpdate) { try { SqlParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int), new SqlParameter("@Level", SqlDbType.NVarChar), new SqlParameter("@Level_Ar", SqlDbType.NVarChar), new SqlParameter("@Updatedby", SqlDbType.Int), new SqlParameter("@Active", SqlDbType.Bit), new SqlParameter("@Weight", SqlDbType.Int) }; parameters[0].Value = educationLevelUpdate.Id; parameters[1].Value = educationLevelUpdate.Level; parameters[2].Value = educationLevelUpdate.Level_Ar; parameters[3].Value = educationLevelUpdate.UpdatedBy; parameters[4].Value = educationLevelUpdate.Active; parameters[5].Value = educationLevelUpdate.Weight; _DataHelper = new DataAccessHelper("spu_lu_Level", parameters, _configuration); DataTable dt = new DataTable(); int result = await _DataHelper.RunAsync(dt); List <EducationLevel> eduLevel = new List <EducationLevel>(); if (dt != null && dt.Rows.Count > 0) { eduLevel = (from model in dt.AsEnumerable() select new EducationLevel() { Id = model.Field <int>("Id"), Level = model.Field <string>("Level"), Level_Ar = model.Field <string>("Level_Ar"), CreatedBy = model.Field <string>("CreatedBy"), CreatedOn = model.Field <DateTime>("CreatedOn"), UpdatedOn = model.Field <DateTime>("UpdatedOn"), UpdatedBy = model.Field <string>("UpdatedBy"), Active = model.Field <bool?>("Active"), Weight = model.Field <int>("Weight") }).ToList(); } return(new DatabaseResponse { ResponseCode = result, Results = eduLevel }); } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw; } finally { _DataHelper.Dispose(); } }
public static void Main(string[] args) { #if DEBUG _isDebug = true; Thread.Sleep(1000); #endif CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US"); Console.Title = $"ACT4 Server{(_isDebug ? " Development Environment" : "")}"; bool ignoreStartupMessages = false; _port = Convert.ToInt32(ConfigurationManager.AppSettings["WorldPort"]); int portArgIndex = Array.FindIndex(args, s => s == "--port"); if (portArgIndex != -1 && args.Length >= portArgIndex + 1 && int.TryParse(args[portArgIndex + 1], out _port)) { Console.WriteLine("Port override: " + _port); } foreach (string arg in args) { switch (arg) { case "--nomsg": ignoreStartupMessages = true; break; case "--notelemetry": _ignoreTelemetry = true; break; } } // initialize Logger Logger.InitializeLogger(LogManager.GetLogger(typeof(Program))); if (!ignoreStartupMessages) { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); string text = $"ACT4 SERVER v{fileVersionInfo.ProductVersion}dev - PORT : {_port} by OpenNos Team "; int offset = (Console.WindowWidth / 2) + (text.Length / 2); string separator = new string('=', Console.WindowWidth); Console.WriteLine(separator + string.Format("{0," + offset + "}\n", text) + separator); } // initialize api string authKey = ConfigurationManager.AppSettings["MasterAuthKey"]; if (CommunicationServiceClient.Instance.Authenticate(authKey)) { Logger.Info(Language.Instance.GetMessageFromKey("API_INITIALIZED")); } // initialize DB if (DataAccessHelper.Initialize()) { // initialilize maps ServerManager.Instance.Initialize(); } else { Console.ReadKey(); return; } // TODO: initialize ClientLinkManager initialize PacketSerialization PacketFactory.Initialize <WalkPacket>(); if (bool.TryParse(ConfigurationManager.AppSettings["AutoReboot"], out bool autoreboot)) { autoreboot = false; } try { _exitHandler += ExitHandler; if (autoreboot) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; } NativeMethods.SetConsoleCtrlHandler(_exitHandler, true); } catch (Exception ex) { Logger.Error("General Error", ex); } NetworkManager <WorldCryptography> networkManager = null; string ipAddress = ConfigurationManager.AppSettings["IPAddress"]; string publicIp = ConfigurationManager.AppSettings["PublicIP"]; portloop: try { networkManager = new NetworkManager <WorldCryptography>(ipAddress, _port, typeof(CommandPacketHandler), typeof(LoginCryptography), true); } catch (SocketException ex) { if (ex.ErrorCode == 10048) { _port++; Logger.Info("Port already in use! Incrementing..."); goto portloop; } Logger.Error("General Error", ex); Environment.Exit(ex.ErrorCode); } ServerManager.Instance.ServerGroup = ConfigurationManager.AppSettings["ServerGroup"]; const int sessionLimit = 100; // Needs workaround int? newChannelId = CommunicationServiceClient.Instance.RegisterWorldServer(new SerializableWorldServer(ServerManager.Instance.WorldId, publicIp, _port, sessionLimit, ServerManager.Instance.ServerGroup)); if (newChannelId.HasValue) { ServerManager.Instance.ChannelId = newChannelId.Value; MailServiceClient.Instance.Authenticate(authKey, ServerManager.Instance.WorldId); ConfigurationServiceClient.Instance.Authenticate(authKey, ServerManager.Instance.WorldId); ServerManager.Instance.Configuration = ConfigurationServiceClient.Instance.GetConfigurationObject(); ServerManager.Instance.MallApi = new GameObject.Helpers.MallAPIHelper(ServerManager.Instance.Configuration.MallBaseURL); ServerManager.Instance.SynchronizeSheduling(); } else { Logger.Error("Could not retrieve ChannelId from Web API."); Console.ReadKey(); } }
private VideoLocal ProcessFile_LocalInfo() { // hash and read media info for file int nshareID = -1; string filePath = ""; ImportFolderRepository repNS = new ImportFolderRepository(); List <ImportFolder> shares = repNS.GetAll(); DataAccessHelper.GetShareAndPath(FileName, shares, ref nshareID, ref filePath); if (!File.Exists(FileName)) { logger.Error("File does not exist: {0}", FileName); return(null); } int numAttempts = 0; // Wait 3 minutes seconds before giving up on trying to access the file while ((!CanAccessFile(FileName)) && (numAttempts < 180)) { numAttempts++; Thread.Sleep(1000); Console.WriteLine("Attempt # " + numAttempts.ToString()); } // if we failed to access the file, get ouuta here if (numAttempts == 180) { logger.Error("Could not access file: " + FileName); return(null); } // check if we have already processed this file VideoLocal vlocal = null; VideoLocalRepository repVidLocal = new VideoLocalRepository(); FileNameHashRepository repFNHash = new FileNameHashRepository(); List <VideoLocal> vidLocals = repVidLocal.GetByFilePathAndShareID(filePath, nshareID); FileInfo fi = new FileInfo(FileName); if (vidLocals.Count > 0) { vlocal = vidLocals[0]; logger.Trace("VideoLocal record found in database: {0}", vlocal.VideoLocalID); if (ForceHash) { vlocal.FileSize = fi.Length; vlocal.DateTimeUpdated = DateTime.Now; } } else { logger.Trace("VideoLocal, creating new record"); vlocal = new VideoLocal(); vlocal.DateTimeUpdated = DateTime.Now; vlocal.DateTimeCreated = vlocal.DateTimeUpdated; vlocal.FilePath = filePath; vlocal.FileSize = fi.Length; vlocal.ImportFolderID = nshareID; vlocal.Hash = ""; vlocal.CRC32 = ""; vlocal.MD5 = ""; vlocal.SHA1 = ""; vlocal.IsIgnored = 0; vlocal.IsVariation = 0; } // check if we need to get a hash this file Hashes hashes = null; if (string.IsNullOrEmpty(vlocal.Hash) || ForceHash) { // try getting the hash from the CrossRef if (!ForceHash) { CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository(); List <CrossRef_File_Episode> crossRefs = repCrossRefs.GetByFileNameAndSize(Path.GetFileName(vlocal.FilePath), vlocal.FileSize); if (crossRefs.Count == 1) { vlocal.Hash = crossRefs[0].Hash; vlocal.HashSource = (int)HashSource.DirectHash; } } // try getting the hash from the LOCAL cache if (!ForceHash && string.IsNullOrEmpty(vlocal.Hash)) { List <FileNameHash> fnhashes = repFNHash.GetByFileNameAndSize(Path.GetFileName(vlocal.FilePath), vlocal.FileSize); if (fnhashes != null && fnhashes.Count > 1) { // if we have more than one record it probably means there is some sort of corruption // lets delete the local records foreach (FileNameHash fnh in fnhashes) { repFNHash.Delete(fnh.FileNameHashID); } } if (fnhashes != null && fnhashes.Count == 1) { logger.Trace("Got hash from LOCAL cache: {0} ({1})", FileName, fnhashes[0].Hash); vlocal.Hash = fnhashes[0].Hash; vlocal.HashSource = (int)HashSource.WebCacheFileName; } } // hash the file if (string.IsNullOrEmpty(vlocal.Hash) || ForceHash) { DateTime start = DateTime.Now; logger.Trace("Calculating hashes for: {0}", FileName); // update the VideoLocal record with the Hash hashes = FileHashHelper.GetHashInfo(FileName, true, MainWindow.OnHashProgress, ServerSettings.Hash_CRC32, ServerSettings.Hash_MD5, ServerSettings.Hash_SHA1); TimeSpan ts = DateTime.Now - start; logger.Trace("Hashed file in {0} seconds --- {1} ({2})", ts.TotalSeconds.ToString("#0.0"), FileName, Utils.FormatByteSize(vlocal.FileSize)); vlocal.Hash = hashes.ed2k; vlocal.CRC32 = hashes.crc32; vlocal.MD5 = hashes.md5; vlocal.SHA1 = hashes.sha1; vlocal.HashSource = (int)HashSource.DirectHash; } // We should have a hash by now // before we save it, lets make sure there is not any other record with this hash (possible duplicate file) VideoLocal vidTemp = repVidLocal.GetByHash(vlocal.Hash); if (vidTemp != null) { // don't delete it, if it is actually the same record if (vidTemp.VideoLocalID != vlocal.VideoLocalID) { // delete the VideoLocal record logger.Warn("Deleting duplicate video file record"); logger.Warn("---------------------------------------------"); logger.Warn("Keeping record for: {0}", vlocal.FullServerPath); logger.Warn("Deleting record for: {0}", vidTemp.FullServerPath); logger.Warn("---------------------------------------------"); // check if we have a record of this in the database, if not create one DuplicateFileRepository repDups = new DuplicateFileRepository(); List <DuplicateFile> dupFiles = repDups.GetByFilePathsAndImportFolder(vlocal.FilePath, vidTemp.FilePath, vlocal.ImportFolderID, vidTemp.ImportFolderID); if (dupFiles.Count == 0) { dupFiles = repDups.GetByFilePathsAndImportFolder(vidTemp.FilePath, vlocal.FilePath, vidTemp.ImportFolderID, vlocal.ImportFolderID); } if (dupFiles.Count == 0) { DuplicateFile dup = new DuplicateFile(); dup.DateTimeUpdated = DateTime.Now; dup.FilePathFile1 = vlocal.FilePath; dup.FilePathFile2 = vidTemp.FilePath; dup.ImportFolderIDFile1 = vlocal.ImportFolderID; dup.ImportFolderIDFile2 = vidTemp.ImportFolderID; dup.Hash = vlocal.Hash; repDups.Save(dup); } repVidLocal.Delete(vidTemp.VideoLocalID); } } repVidLocal.Save(vlocal); // also save the filename to hash record // replace the existing records just in case it was corrupt FileNameHash fnhash = null; List <FileNameHash> fnhashes2 = repFNHash.GetByFileNameAndSize(Path.GetFileName(vlocal.FilePath), vlocal.FileSize); if (fnhashes2 != null && fnhashes2.Count > 1) { // if we have more than one record it probably means there is some sort of corruption // lets delete the local records foreach (FileNameHash fnh in fnhashes2) { repFNHash.Delete(fnh.FileNameHashID); } } if (fnhashes2 != null && fnhashes2.Count == 1) { fnhash = fnhashes2[0]; } else { fnhash = new FileNameHash(); } fnhash.FileName = Path.GetFileName(vlocal.FilePath); fnhash.FileSize = vlocal.FileSize; fnhash.Hash = vlocal.Hash; fnhash.DateTimeUpdated = DateTime.Now; repFNHash.Save(fnhash); } // now check if we have stored a VideoInfo record bool refreshMediaInfo = false; VideoInfoRepository repVidInfo = new VideoInfoRepository(); VideoInfo vinfo = repVidInfo.GetByHash(vlocal.Hash); if (vinfo == null) { refreshMediaInfo = true; vinfo = new VideoInfo(); vinfo.Hash = vlocal.Hash; vinfo.Duration = 0; vinfo.FileSize = fi.Length; vinfo.DateTimeUpdated = DateTime.Now; vinfo.FileName = filePath; vinfo.AudioBitrate = ""; vinfo.AudioCodec = ""; vinfo.VideoBitrate = ""; vinfo.VideoBitDepth = ""; vinfo.VideoCodec = ""; vinfo.VideoFrameRate = ""; vinfo.VideoResolution = ""; repVidInfo.Save(vinfo); } else { // check if we need to update the media info if (vinfo.VideoCodec.Trim().Length == 0) { refreshMediaInfo = true; } else { refreshMediaInfo = false; } } if (refreshMediaInfo) { logger.Trace("Getting media info for: {0}", FileName); MediaInfoResult mInfo = FileHashHelper.GetMediaInfo(FileName, true); vinfo.AudioBitrate = string.IsNullOrEmpty(mInfo.AudioBitrate) ? "" : mInfo.AudioBitrate; vinfo.AudioCodec = string.IsNullOrEmpty(mInfo.AudioCodec) ? "" : mInfo.AudioCodec; vinfo.DateTimeUpdated = vlocal.DateTimeUpdated; vinfo.Duration = mInfo.Duration; vinfo.FileName = filePath; vinfo.FileSize = fi.Length; vinfo.VideoBitrate = string.IsNullOrEmpty(mInfo.VideoBitrate) ? "" : mInfo.VideoBitrate; vinfo.VideoBitDepth = string.IsNullOrEmpty(mInfo.VideoBitDepth) ? "" : mInfo.VideoBitDepth; vinfo.VideoCodec = string.IsNullOrEmpty(mInfo.VideoCodec) ? "" : mInfo.VideoCodec; vinfo.VideoFrameRate = string.IsNullOrEmpty(mInfo.VideoFrameRate) ? "" : mInfo.VideoFrameRate; vinfo.VideoResolution = string.IsNullOrEmpty(mInfo.VideoResolution) ? "" : mInfo.VideoResolution; vinfo.FullInfo = string.IsNullOrEmpty(mInfo.FullInfo) ? "" : mInfo.FullInfo; repVidInfo.Save(vinfo); } // now add a command to process the file CommandRequest_ProcessFile cr_procfile = new CommandRequest_ProcessFile(vlocal.VideoLocalID, false); cr_procfile.Save(); return(vlocal); }
protected override bool IsKnownException(Exception exception) { return(base.IsKnownException(exception) || DataAccessHelper.IsDataAccessKnownException(exception)); }
public async Task <DatabaseResponse> GetContactUsQueries(int pageNumber, int pageSize, string paramIsSearch, string sortType, int sortField) { try { SqlParameter[] parameters = { new SqlParameter("@PageNo", SqlDbType.Int), new SqlParameter("@PageSize", SqlDbType.Int), new SqlParameter("@Keyword", SqlDbType.NVarChar), new SqlParameter("@SortType", SqlDbType.NVarChar), new SqlParameter("@SortField", SqlDbType.Int) }; parameters[0].Value = pageNumber; parameters[1].Value = pageSize; parameters[2].Value = paramIsSearch; parameters[3].Value = sortType; parameters[4].Value = sortField; _DataHelper = new DataAccessHelper("sps_ContactUs", parameters, _configuration); DataTable dt = new DataTable(); int result = await _DataHelper.RunAsync(dt); List <ContactUs> contactUs = new List <ContactUs>(); if (dt != null && dt.Rows.Count > 0) { contactUs = (from model in dt.AsEnumerable() select new ContactUs() { Id = model.Field <int>("Id"), FirstName = model.Field <string>("FirstName"), LastName = model.Field <string>("LastName"), Email = model.Field <string>("Email"), Telephone = model.Field <string>("Telephone"), Subject = model.Field <string>("Subject"), Message = model.Field <string>("Message"), TotalRows = model.Field <Int64>("Totalrows"), IsReplied = model.Field <int>("IsReplied"), RepliedText = model.Field <string>("RepliedText"), RepliedBy = model.Field <string>("RepliedBy"), RepliedById = model.Field <int?>("RepliedById"), RepliedOn = model.Field <DateTime?>("RepliedOn") }).ToList(); } return(new DatabaseResponse { ResponseCode = result, Results = contactUs }); } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw; } finally { _DataHelper.Dispose(); } }
public async Task <DatabaseResponse> GetUserNotifications(int UserId, int PageNo, int PageSize) { try { SqlParameter[] parameters = { new SqlParameter("@UserID", SqlDbType.Int), new SqlParameter("@PageNo", SqlDbType.Int), new SqlParameter("@PageSize", SqlDbType.Int) }; parameters[0].Value = UserId; parameters[1].Value = PageNo; parameters[2].Value = PageSize; _DataHelper = new DataAccessHelper("sps_Notifications", parameters, _configuration); DataSet ds = new DataSet(); int result = await _DataHelper.RunAsync(ds); List <Notification> userNotification = new List <Notification>(); if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow drItem in ds.Tables[0].Rows) { Notification notification = new Notification(); notification.Id = Convert.ToInt32(drItem["Id"]); notification.IsApproved = Convert.ToBoolean(drItem["IsApproved"]); notification.ReferenceId = Convert.ToInt32(drItem["ReferenceId"]); notification.ReferenceTypeId = Convert.ToInt32(drItem["ReferenceTypeId"]); notification.Status = drItem["Status"].ToString() != "" ? Convert.ToInt32(drItem["Status"]) : 1; if ((notification.ReferenceTypeId == 2 || notification.ReferenceTypeId == 1) && (!notification.IsApproved)) { string FilterCond1 = "ReferenceId=" + notification.ReferenceId; List <ReviewerComments> ReviewerComments = new List <ReviewerComments>(); foreach (DataRow dritem2 in ds.Tables[0].Select(FilterCond1)) { ReviewerComments objComments = new ReviewerComments(); objComments.Reviewer = Convert.ToString(dritem2["Reviewer"]); objComments.Reasons = Convert.ToString(dritem2["Comment"]); ReviewerComments.Add(objComments); } notification.reviewerComments = ReviewerComments; } notification.Total = Convert.ToInt32(drItem["Total"]); notification.Subject = Convert.ToString(drItem["Subject"]); notification.Content = Convert.ToString(drItem["Content"]); notification.MessageType = Convert.ToString(drItem["MessageType"]); notification.CreatedDate = Convert.ToDateTime(drItem["CreatedDate"]); notification.IsRead = Convert.ToBoolean(drItem["IsRead"]); notification.Totalrows = Convert.ToInt32(drItem["Totalrows"]); notification.Rownumber = Convert.ToInt32(drItem["Rownumber"]); notification.Reviewer = Convert.ToString(drItem["Reviewer"]); notification.Comment = Convert.ToString(drItem["Comment"]); notification.EmailUrl = Convert.ToString(drItem["EmailUrl"]); notification.TotalUnRead = Convert.ToInt32(drItem["TotalUnRead"]); userNotification.Add(notification); } } var un = userNotification.Where(c => c.Status == 1); return(new DatabaseResponse { ResponseCode = result, Results = un }); } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw; } finally { _DataHelper.Dispose(); } }