public void InitializeTest() { EducationContext = new EducationDataContext(); Container = AssemblySetup.CreateWindsorContainer(EducationContext); RepositoryContainer repositoryContainer = new RepositoryContainer(Container, EducationContext); ProviderManager manager = new ProviderManager(repositoryContainer, new DataTableBinder()); Target = new ProviderController(manager); }
public FrmProvider() { InitializeComponent(); // manufacturerManager = new ProviderManager(); countryManager = new CountryManager(); }
public void InitializeTest() { EducationContext = new EducationDataContext(); Container = AssemblySetup.CreateWindsorContainer(EducationContext); RepositoryContainer repositoryContainer = new RepositoryContainer(Container, EducationContext); ProviderManager providerManager = new ProviderManager(repositoryContainer, new DataTableBinder()); ProgramManager programManager = new ProgramManager(repositoryContainer, new DataTableBinder()); ServiceTypeManager serviceTypeManager = new ServiceTypeManager(repositoryContainer, new DataTableBinder()); Target = new PartnersController(providerManager, programManager, serviceTypeManager); }
private static void SendSmsUsingConfigBasedProviders() { Console.WriteLine("##############Sending sms using config based provider##############\n"); var providerManager = new ProviderManager(); var smsProviders = providerManager.Providers.All<SmsProviderBase>(); var message = providerManager.Settings.Get<Message>("Message"); foreach (var smsProvider in smsProviders) { var result = smsProvider.SendSms(message); Console.WriteLine(result); Console.WriteLine(); } }
public FrmDanhMucSanPham() { InitializeComponent(); //Create Manager which will use in form productManager = new ProductManager(); productNameManager = new ProductNameManager(); productStatusManager = new ProductStatusManager(); unitManager = new UnitManager(); categoryManager = new CategoryManager(); manufacturerManager = new ManufacturerManager(); countryManager = new CountryManager(); providerManager = new ProviderManager(); // MODE = Constants.MODE.ADD; }
public void Should_get_provider_config_using_the_specified_provider_config_source() { var providerDesccriptors = new List<IProviderDescriptor> { MockRepository.GenerateMock<IProviderDescriptor>() }; var settings = MockRepository.GenerateMock<IProviderSettings>(); var providerConfig = MockRepository.GenerateMock<IProviderConfig>(); providerConfig.Stub(x => x.ProviderDescriptors).Return(providerDesccriptors); providerConfig.Stub(x => x.Settings).Return(settings); var xmlProviderConfigSource = MockRepository.GenerateMock<XmlProviderConfigSource>(); xmlProviderConfigSource.Stub(x => x.GetProviderConfiguration()).Return(providerConfig); var providerManager = new ProviderManager(xmlProviderConfigSource); Assert.That(providerManager.Providers, Is.Not.Null); Assert.That(providerManager.Settings, Is.Not.Null); }
public void fillData(DataGridViewRow row) { try { textBoxMaPhieu.Text = row.Cells[0].Value.ToString(); textBoxNgayTao.Text = row.Cells[1].Value.ToString(); textBoxNguoiLapPhieu.Text = row.Cells[4].Value.ToString(); textBoxNhanVienGH.Text = row.Cells[2].Value.ToString(); HoTro ht = new HoTro(); ht.TaiDuLieu(comboBoxNhaCungCap, "Provider", "ProviderId", "ProviderName"); string providerName = row.Cells[3].Value.ToString(); ProviderManager pl = new ProviderManager(); foreach (Provider p in pl.GetAll()) { if (p.ProviderName.Equals(providerName)) { comboBoxNhaCungCap.SelectedValue = p.ID; break; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
[Read(Check = false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!! public CapabilitiesData GetPortalCapabilities() { var result = new CapabilitiesData { LdapEnabled = false, Providers = null, SsoLabel = string.Empty, SsoUrl = string.Empty }; try { if (SetupInfo.IsVisibleSettings(ManagementType.LdapSettings.ToString()) && (!CoreBaseSettings.Standalone || TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).Ldap)) { //var settings = SettingsManager.Load<LdapSettings>(); //result.LdapEnabled = settings.EnableLdapAuthentication; result.LdapEnabled = false; } } catch (Exception ex) { Log.Error(ex.Message); } try { result.Providers = ProviderManager.AuthProviders.Where(loginProvider => { var provider = ProviderManager.GetLoginProvider(loginProvider); return(provider != null && provider.IsEnabled); }) .ToList(); } catch (Exception ex) { Log.Error(ex.Message); } try { if (SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString()) && TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).Sso) { //var settings = SettingsManager.Load<SsoSettingsV2>(); //if (settings.EnableSso) //{ var uri = HttpContextAccessor.HttpContext.Request.GetUrlRewriter(); var configUrl = Configuration["web:sso:saml:login:url"] ?? ""; result.SsoUrl = string.Format("{0}://{1}{2}{3}", uri.Scheme, uri.Host, (uri.Port == 80 || uri.Port == 443) ? "" : ":" + uri.Port, configUrl); result.SsoLabel = string.Empty; // result.SsoLabel = settings.SpLoginLabel; //} } } catch (Exception ex) { Log.Error(ex.Message); } return(result); }
/// <summary> /// Consulta o numero de sequencia dos lotes de RPS. /// /// Obs.: Nem todos provedores suportam este metodo. /// </summary> /// <param name="serie">The serie.</param> /// <returns>RetornoWebservice.</returns> /// <exception cref="NotImplementedException"></exception> public RetornoWebservice ConsultarSequencialRps(string serie) { var provider = ProviderManager.GetProvider(Configuracoes); return(provider.ConsultarSequencialRps(serie)); }
/// <summary> /// Cancela uma NFSe /// /// Obs.: Nem todos provedores suportam este metodo. /// </summary> /// <param name="codigoCancelamento">O codigo de cancelamento.</param> /// <param name="numeroNFSe">O numero da NFSe.</param> /// <param name="motivo">O motivo.</param> /// <returns>RetornoWebservice.</returns> public RetornoWebservice CancelaNFSe(string codigoCancelamento, string numeroNFSe, string motivo) { var provider = ProviderManager.GetProvider(Configuracoes); return(provider.CancelaNFSe(codigoCancelamento, numeroNFSe, motivo, NotasFiscais)); }
public async Task RefreshAllMetadata(MetadataRefreshOptions refreshOptions, IProgress <double> progress, CancellationToken cancellationToken) { // Refresh bottom up, children first, then the boxset // By then hopefully the movies within will have Tmdb collection values var items = GetRecursiveChildren(); var totalItems = items.Count; var numComplete = 0; // Refresh seasons foreach (var item in items) { if (!(item is Season)) { continue; } cancellationToken.ThrowIfCancellationRequested(); if (refreshOptions.RefreshItem(item)) { await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); } numComplete++; double percent = numComplete; percent /= totalItems; progress.Report(percent * 100); } // Refresh episodes and other children foreach (var item in items) { if ((item is Season)) { continue; } cancellationToken.ThrowIfCancellationRequested(); var skipItem = false; var episode = item as Episode; if (episode != null && refreshOptions.MetadataRefreshMode != MetadataRefreshMode.FullRefresh && !refreshOptions.ReplaceAllMetadata && episode.IsMissingEpisode && episode.LocationType == LocationType.Virtual && episode.PremiereDate.HasValue && (DateTime.UtcNow - episode.PremiereDate.Value).TotalDays > 30) { skipItem = true; } if (!skipItem) { if (refreshOptions.RefreshItem(item)) { await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); } } numComplete++; double percent = numComplete; percent /= totalItems; progress.Report(percent * 100); } refreshOptions = new MetadataRefreshOptions(refreshOptions); await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false); }
public void Connect(int timeout) { this.Connect(); ProviderManager.WaitConnected((IProvider)this, timeout); }
/// <summary> /// Constructor /// </summary> public MappingManager(ProviderManager ProviderManager) { Modules = new List <IModule>(); Mappings = new List <IMapping>(); this.ProviderManager = ProviderManager; }
/// <summary> /// 获取默认的CTP插件 /// </summary> /// <returns></returns> public static XProvider GetCtp(this ProviderManager manager) { return((XProvider)manager.GetExecutionProvider(QuantBoxConst.PIdCtp)); }
public GMQueryDataProvider() { _md = GMSDK.MdApi.Instance; ProviderManager.Add(this); }
private UserInfo GetUser(AuthModel memberModel, out bool viaEmail) { viaEmail = true; var action = MessageAction.LoginFailViaApi; UserInfo user; try { if ((string.IsNullOrEmpty(memberModel.Provider) && string.IsNullOrEmpty(memberModel.SerializedProfile)) || memberModel.Provider == "email") { memberModel.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName")); if (!string.IsNullOrEmpty(memberModel.Password)) { memberModel.Password.ThrowIfNull(new ArgumentException(@"password empty", "password")); } else { memberModel.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash")); } int counter; int.TryParse(Cache.Get <string>("loginsec/" + memberModel.UserName), out counter); if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(memberModel.UserName)) { throw new BruteForceCredentialException(); } Cache.Insert("loginsec/" + memberModel.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim(); if (string.IsNullOrEmpty(memberModel.PasswordHash)) { memberModel.Password = (memberModel.Password ?? "").Trim(); if (!string.IsNullOrEmpty(memberModel.Password)) { memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password); } } user = UserManager.GetUsersByPasswordHash( TenantManager.GetCurrentTenant().TenantId, memberModel.UserName, memberModel.PasswordHash); if (user == null || !UserManager.UserExists(user)) { throw new Exception("user not found"); } Cache.Insert("loginsec/" + memberModel.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); } else { viaEmail = false; action = MessageAction.LoginFailViaApiSocialAccount; LoginProfile thirdPartyProfile; if (!string.IsNullOrEmpty(memberModel.SerializedProfile)) { thirdPartyProfile = new LoginProfile(Signature, InstanceCrypto, memberModel.SerializedProfile); } else { thirdPartyProfile = ProviderManager.GetLoginProfile(memberModel.Provider, memberModel.AccessToken); } memberModel.UserName = thirdPartyProfile.EMail; user = GetUserByThirdParty(thirdPartyProfile); } } catch (BruteForceCredentialException) { MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce); throw new AuthenticationException("Login Fail. Too many attempts"); } catch { MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, action); throw new AuthenticationException("User authentication failed"); } return(user); }
public AuthenticationController( UserManager userManager, TenantManager tenantManager, SecurityContext securityContext, TenantCookieSettingsHelper tenantCookieSettingsHelper, CookiesManager cookiesManager, PasswordHasher passwordHasher, EmailValidationKeyModelHelper emailValidationKeyModelHelper, ICache cache, SetupInfo setupInfo, MessageService messageService, ProviderManager providerManager, IOptionsSnapshot <AccountLinker> accountLinker, CoreBaseSettings coreBaseSettings, PersonalSettingsHelper personalSettingsHelper, StudioNotifyService studioNotifyService, UserManagerWrapper userManagerWrapper, UserHelpTourHelper userHelpTourHelper, Signature signature, InstanceCrypto instanceCrypto, DisplayUserSettingsHelper displayUserSettingsHelper, MessageTarget messageTarget, StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper, SettingsManager settingsManager, SmsManager smsManager, TfaManager tfaManager, TimeZoneConverter timeZoneConverter, SmsKeyStorage smsKeyStorage, CommonLinkUtility commonLinkUtility, ApiContext apiContext, AuthContext authContext) { UserManager = userManager; TenantManager = tenantManager; SecurityContext = securityContext; TenantCookieSettingsHelper = tenantCookieSettingsHelper; CookiesManager = cookiesManager; PasswordHasher = passwordHasher; EmailValidationKeyModelHelper = emailValidationKeyModelHelper; Cache = cache; SetupInfo = setupInfo; MessageService = messageService; ProviderManager = providerManager; AccountLinker = accountLinker; CoreBaseSettings = coreBaseSettings; PersonalSettingsHelper = personalSettingsHelper; StudioNotifyService = studioNotifyService; UserHelpTourHelper = userHelpTourHelper; Signature = signature; InstanceCrypto = instanceCrypto; DisplayUserSettingsHelper = displayUserSettingsHelper; MessageTarget = messageTarget; StudioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper; SettingsManager = settingsManager; SmsManager = smsManager; TfaManager = tfaManager; TimeZoneConverter = timeZoneConverter; SmsKeyStorage = smsKeyStorage; CommonLinkUtility = commonLinkUtility; ApiContext = apiContext; AuthContext = authContext; UserManagerWrapper = userManagerWrapper; }
private BaseProvider(string name) { ProviderManager.Register(name, this); }
/// <summary> /// Gets the serialization provider for a given type. /// </summary> /// <param name="type">The type to serialize.</param> /// <returns>The serialization provider or the default JSON provider.</returns> internal static TraceSerializationProvider GetSerializationProvider(Type type) { return(ProviderManager.GetProvider <TraceSerializationProvider>(type, typeof(TraceSerializationProviderAttribute), () => new JsonObjectSerializer())); }
public void ApplyFilter(bool reset, bool notifications = true) { if (AllDownloads == null || !AllDownloads.Any()) { Fetch(); return; } _mutexFilter.WaitOne(); FavSeasonData currentFavSeason = null; SeasonData currentSeasonData = null; var seasonNr = -1; var newSeasons = new ObservableCollection <FavSeasonData>(); var newNonSeasons = new ObservableCollection <DownloadData>(); var setNewEpisodes = false; var setNewUpdates = false; if (_isNewShow) { notifications = false; } reset = reset || _isNewShow; if (!reset) { newSeasons = Seasons; newNonSeasons = NonSeasons; } UploadData currentUpload = null; var ignoreCurrentUpload = false; foreach (var download in AllDownloads) { //upload stuff -------------------------------------------------------------------- if (currentUpload == null || currentUpload != download.Upload) { currentUpload = download.Upload; ignoreCurrentUpload = true; do { var language = currentUpload.Language; if (!Settings.Instance.MarkSubbedAsGerman && currentUpload.Subbed) //dont mark german-subbed as german { language &= ~UploadLanguage.German; //remove german } if ((language & FilterLanguage) == 0) //Filter: Language { break; } if (!string.IsNullOrWhiteSpace(FilterRuntime) && //Filter: Runtime !(new Regex(FilterRuntime).Match(currentUpload.Runtime).Success)) { break; } if (!string.IsNullOrWhiteSpace(FilterSize) && //Filter: Size !(new Regex(FilterSize).Match(currentUpload.Size).Success)) { break; } if (!string.IsNullOrWhiteSpace(FilterUploader) && //Filter: Uploader !(new Regex(FilterUploader).Match(currentUpload.Uploader).Success)) { break; } if (!string.IsNullOrWhiteSpace(FilterFormat) && //Filter: Format !(new Regex(FilterFormat).Match(currentUpload.Format).Success)) { break; } ignoreCurrentUpload = false; } while (false); } if (ignoreCurrentUpload) //Filter: All upload stuff { continue; } //episode stuff --------------------- if (!string.IsNullOrWhiteSpace(FilterName) && //Filter: Name !(new Regex(FilterName).Match(download.Title).Success)) { continue; } if (!string.IsNullOrWhiteSpace(FilterHoster)) { var r = new Regex(FilterHoster); var dls = download.Links.Keys.Where(hoster => r.Match(hoster).Success).ToList(); //all keys that match the regex if (!dls.Any()) //Filter: Hoster { continue; } for (var i = download.Links.Keys.Count - 1; i >= 0; i--) { var key = download.Links.Keys.ElementAt(i); if (!dls.Contains(key)) { download.Links.Remove(key); } } } //------------------------------------------ //Season stuff ------------------------------------------------------------------------------------ if (currentSeasonData == null || currentSeasonData != download.Upload.Season) { currentSeasonData = download.Upload.Season; seasonNr = -1; var m2 = new Regex("(?:season|staffel)\\s*(\\d+)", RegexOptions.IgnoreCase).Match(currentSeasonData.Title); if (m2.Success) { int.TryParse(m2.Groups[1].Value, out seasonNr); } } if (seasonNr == -1) { if (newNonSeasons.All(d => d.Title != download.Title)) { newNonSeasons.Add(download); } continue; } if (currentFavSeason == null || currentFavSeason.Number != seasonNr) { currentFavSeason = newSeasons.FirstOrDefault(favSeasonData => favSeasonData.Number == seasonNr) ?? new FavSeasonData() { Number = seasonNr, Show = this }; if (!newSeasons.Contains(currentFavSeason)) //season not yet added? { newSeasons.Add(currentFavSeason); } } var episodeNr = -1; var mts = new Regex("S0{0,4}" + seasonNr + "\\.?E(\\d+)", RegexOptions.IgnoreCase).Matches(download.Title); var mts_ep = new Regex("[^A-Z]E(\\d+)", RegexOptions.IgnoreCase).Matches(download.Title); var mts_alt = new Regex("\\bE(\\d+)\\b", RegexOptions.IgnoreCase).Matches(download.Title); if (mts.Count == 1 && mts_ep.Count == 1) //if there is exactly one match for "S<xx>E<yy>" and there is no second "E<zz>" (e.g. S01E01-E12) { int.TryParse(mts[0].Groups[1].Value, out episodeNr); } else if (mts_alt.Count == 1) { //if there's exactly one match for the alternative regex int.TryParse(mts_alt[0].Groups[1].Value, out episodeNr); } if (episodeNr == -1) { if (currentFavSeason.NonEpisodes.All(d => d.Title != download.Title)) { currentFavSeason.NonEpisodes.Add(download); } continue; } var currentFavEpisode = currentFavSeason.Episodes.FirstOrDefault(episodeData => episodeData.Number == episodeNr); if (currentFavEpisode == null) { currentFavEpisode = new FavEpisodeData(); currentFavEpisode.Season = currentFavSeason; currentFavEpisode.Number = episodeNr; var existed = false; var oldSeason = Seasons.FirstOrDefault(s => s.Number == currentFavSeason.Number); if (oldSeason != null) { var oldEpisode = oldSeason.Episodes.FirstOrDefault(e => e.Number == currentFavEpisode.Number); if (oldEpisode != null) //we can copy old data to current episode { currentFavEpisode.Watched = oldEpisode.Watched; currentFavEpisode.Downloaded = oldEpisode.Downloaded; currentFavEpisode.EpisodeInformation = oldEpisode.EpisodeInformation; existed = true; } } if (notifications && !existed) { currentFavEpisode.NewEpisode = true; setNewEpisodes = true; } currentFavSeason.Episodes.Add(currentFavEpisode); currentFavEpisode.Downloads.Add(download); if (ProviderData != null && (currentFavEpisode.EpisodeInformation == null || reset)) { StaticInstance.ThreadPool.QueueWorkItem(() => { //currentFavEpisode.ReviewInfoReview = SjInfo.ParseSjDeSite(InfoUrl, currentFavEpisode.Season.Number, currentFavEpisode.Number); currentFavEpisode.EpisodeInformation = ProviderManager.GetProvider().GetEpisodeInformation(ProviderData, currentFavEpisode.Season.Number, currentFavEpisode.Number); }, true, WorkItemPriority.BelowNormal); } } else { FavEpisodeData oldEpisode = null; var oldSeason = Seasons.FirstOrDefault(s => s.Number == currentFavSeason.Number); if (oldSeason != null) { oldEpisode = oldSeason.Episodes.FirstOrDefault(e => e.Number == currentFavEpisode.Number); } if (currentFavEpisode.Downloads.All(d => d.Title != download.Title)) { if (notifications && (oldEpisode == null || (!oldEpisode.NewEpisode && oldEpisode.Downloads.All(d => d.Title != download.Title)))) { currentFavEpisode.NewUpdate = true; setNewUpdates = true; } currentFavEpisode.Downloads.Add(download); } } } if (reset) { Seasons.Clear(); foreach (var season in newSeasons) { Seasons.Add(season); } NonSeasons.Clear(); foreach (var nonSeason in newNonSeasons) { NonSeasons.Add(nonSeason); } } if (setNewEpisodes) { Notified = false; NewEpisodes = true; } if (setNewUpdates) { NewUpdates = true; } RecalcNumbers(); _mutexFilter.ReleaseMutex(); }
/// <summary> /// Registers resources that classes will depend on /// </summary> /// <returns>Task.</returns> protected override async Task RegisterResources() { ServerKernel = new Kernel(); await base.RegisterResources().ConfigureAwait(false); RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager)); RegisterSingleInstance <IServerApplicationHost>(this); RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths); RegisterSingleInstance(ServerKernel); RegisterSingleInstance(ServerConfigurationManager); RegisterSingleInstance <IWebSocketServer>(() => new AlchemyServer(Logger)); IsoManager = new IsoManager(); RegisterSingleInstance(IsoManager); RegisterSingleInstance <IBlurayExaminer>(() => new BdInfoExaminer()); ZipClient = new DotNetZipClient(); RegisterSingleInstance(ZipClient); UserDataRepository = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(UserDataRepository); UserRepository = await GetUserRepository().ConfigureAwait(false); RegisterSingleInstance(UserRepository); DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(DisplayPreferencesRepository); ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(ItemRepository); UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository); RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataRepository, () => DirectoryWatchers); RegisterSingleInstance(LibraryManager); DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager); RegisterSingleInstance(DirectoryWatchers); ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, LibraryManager); RegisterSingleInstance(ProviderManager); RegisterSingleInstance <ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager)); MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ZipClient, ApplicationPaths, JsonSerializer, HttpClient); RegisterSingleInstance(MediaEncoder); var clientConnectionManager = new SessionManager(UserDataRepository, ServerConfigurationManager, Logger, UserRepository); RegisterSingleInstance <ISessionManager>(clientConnectionManager); HttpServer = await _httpServerCreationTask.ConfigureAwait(false); RegisterSingleInstance(HttpServer, false); ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager); RegisterSingleInstance(ServerManager); LocalizationManager = new LocalizationManager(ServerConfigurationManager); RegisterSingleInstance(LocalizationManager); var displayPreferencesTask = Task.Run(async() => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false)); var itemsTask = Task.Run(async() => await ConfigureItemRepositories().ConfigureAwait(false)); var userdataTask = Task.Run(async() => await ConfigureUserDataRepositories().ConfigureAwait(false)); await ConfigureNotificationsRepository().ConfigureAwait(false); await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false); SetKernelProperties(); }
public void Connect(int timeout) { Connect(); ProviderManager.WaitConnected(this, timeout); }
// Prevent inheritance outside of Roslyn. internal CompletionService(HostWorkspaceServices services) { _services = services; _providerManager = new(this); }
private static OrderAgent GetAgent(ProviderManager manager, string name) { return((OrderAgent)manager.Providers[name]); }
public static void Main(string[] args) { ProviderA providerA = new ProviderA("http://stackoverflow.com", "active"); string url = ProviderManager.GetRedirectUrl("A"); }
/// <summary> /// Constructor /// </summary> /// <param name="ServiceType">Service type</param> /// <param name="AttributeType">Attribute type</param> /// <param name="ProviderManager">Provider manager</param> /// <param name="MappingManager">Mapping manager</param> public MappingKey(Type ServiceType, Type AttributeType, ProviderManager ProviderManager, MappingManager MappingManager) : base(ServiceType, AttributeType, ProviderManager, MappingManager) { }
/// <summary> /// Registers resources that classes will depend on /// </summary> /// <returns>Task.</returns> protected override async Task RegisterResources(IProgress <double> progress) { await base.RegisterResources(progress).ConfigureAwait(false); RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer)); RegisterSingleInstance <IServerApplicationHost>(this); RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths); RegisterSingleInstance(ServerConfigurationManager); LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer); RegisterSingleInstance(LocalizationManager); RegisterSingleInstance <IBlurayExaminer>(() => new BdInfoExaminer()); UserDataManager = new UserDataManager(LogManager); RegisterSingleInstance(UserDataManager); UserRepository = await GetUserRepository().ConfigureAwait(false); RegisterSingleInstance(UserRepository); DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(DisplayPreferencesRepository); ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(ItemRepository); ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager); RegisterSingleInstance(ProviderRepository); FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false); RegisterSingleInstance(FileOrganizationRepository); AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false); RegisterSingleInstance(AuthenticationRepository); //SyncRepository = await GetSyncRepository().ConfigureAwait(false); //RegisterSingleInstance(SyncRepository); UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService); RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager); RegisterSingleInstance(LibraryManager); var musicManager = new MusicManager(LibraryManager); RegisterSingleInstance <IMusicManager>(new MusicManager(LibraryManager)); LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager); RegisterSingleInstance(LibraryMonitor); ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager); RegisterSingleInstance(ProviderManager); SeriesOrderManager = new SeriesOrderManager(); RegisterSingleInstance(SeriesOrderManager); RegisterSingleInstance <ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager)); HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html", _supportsNativeWebSocket); RegisterSingleInstance(HttpServer, false); progress.Report(10); ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager); RegisterSingleInstance(ServerManager); var innerProgress = new ActionableProgress <double>(); innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15)); await RegisterMediaEncoder(innerProgress).ConfigureAwait(false); progress.Report(90); ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder); RegisterSingleInstance(ImageProcessor); SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager")); RegisterSingleInstance(SyncManager); DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager); RegisterSingleInstance(DtoService); var encryptionManager = new EncryptionManager(); RegisterSingleInstance <IEncryptionManager>(encryptionManager); ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager); RegisterSingleInstance(ConnectManager); SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository); RegisterSingleInstance(SessionManager); var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer); RegisterSingleInstance <INewsService>(newsService); var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager); RegisterSingleInstance <IFileOrganizationService>(fileOrganizationService); progress.Report(15); ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient); RegisterSingleInstance(ChannelManager); TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager); RegisterSingleInstance(TVSeriesManager); var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger); RegisterSingleInstance <IAppThemeManager>(appThemeManager); var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer); RegisterSingleInstance <IDlnaManager>(dlnaManager); var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient); RegisterSingleInstance <IConnectionManager>(connectionManager); CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager")); RegisterSingleInstance(CollectionManager); var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager); RegisterSingleInstance <IPlaylistManager>(playlistManager); LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer); RegisterSingleInstance(LiveTvManager); UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager); RegisterSingleInstance(UserViewManager); var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager); RegisterSingleInstance <IContentDirectory>(contentDirectory); NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager); RegisterSingleInstance(NotificationManager); SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository); RegisterSingleInstance(SubtitleManager); ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); RegisterSingleInstance(ChapterManager); EncodingManager = new EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager); RegisterSingleInstance(EncodingManager); var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false); RegisterSingleInstance(activityLogRepo); RegisterSingleInstance <IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager)); var authContext = new AuthorizationContext(); RegisterSingleInstance <IAuthorizationContext>(authContext); RegisterSingleInstance <ISessionContext>(new SessionContext(UserManager, authContext, SessionManager)); RegisterSingleInstance <IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager)); RegisterSingleInstance <ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer)); var displayPreferencesTask = Task.Run(async() => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false)); var itemsTask = Task.Run(async() => await ConfigureItemRepositories().ConfigureAwait(false)); var userdataTask = Task.Run(async() => await ConfigureUserDataRepositories().ConfigureAwait(false)); await ConfigureNotificationsRepository().ConfigureAwait(false); progress.Report(92); await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false); progress.Report(100); SetStaticProperties(); await((UserManager)UserManager).Initialize().ConfigureAwait(false); SetKernelProperties(); }
[Read("", false, false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!! public CapabilitiesData GetPortalCapabilities() { var result = new CapabilitiesData { LdapEnabled = false, Providers = null, SsoLabel = string.Empty, SsoUrl = string.Empty }; try { if (SetupInfo.IsVisibleSettings(ManagementType.LdapSettings.ToString()) && (!CoreContext.Configuration.Standalone || CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Ldap)) { var settings = LdapSettings.Load(); result.LdapEnabled = settings.EnableLdapAuthentication; } } catch (Exception ex) { LogManager.GetLogger("ASC").Error(ex.Message); } try { result.Providers = AccountLinkControl.AuthProviders .Where(loginProvider => { var provider = ProviderManager.GetLoginProvider(loginProvider); return(provider != null && provider.IsEnabled); }) .ToList(); } catch (Exception ex) { LogManager.GetLogger("ASC").Error(ex.Message); } try { if (SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString()) && (!CoreContext.Configuration.Standalone || CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Sso)) { var settings = SsoSettingsV2.Load(); if (settings.EnableSso) { var uri = HttpContext.Current.Request.GetUrlRewriter(); var configUrl = GetAppSettings("web.sso.saml.login.url", ""); result.SsoUrl = string.Format("{0}://{1}{2}{3}", uri.Scheme, uri.Host, (uri.Port == 80 || uri.Port == 443) ? "" : ":" + uri.Port, configUrl); result.SsoLabel = settings.SpLoginLabel; } } } catch (Exception ex) { LogManager.GetLogger("ASC").Error(ex.Message); } return(result); }
public void TestInitialize() { EducationContext = new EducationDataContext(); Container = AssemblySetup.CreateWindsorContainer(EducationContext); RepositoryContainer repositoryContainer = new RepositoryContainer(Container, EducationContext); ServiceOfferingManager logicManager = new ServiceOfferingManager(repositoryContainer, new DataTableBinder()); ServiceTypeManager serviceTypeManager = new ServiceTypeManager(repositoryContainer, new DataTableBinder()); ProviderManager providerManager = new ProviderManager(repositoryContainer, new DataTableBinder()); ProgramManager programManager = new ProgramManager(repositoryContainer, new DataTableBinder()); HttpContext context = new HttpContext(new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter())); User userEntity = EducationContext.Users.Include("UserRoles.Role").Include("UserRoles.Schools").Include("UserRoles.Providers").Single(s => s.UserKey == "Bob"); User = new EducationSecurityPrincipal(userEntity); context.User = User; Target = new ServiceOfferingController(logicManager, serviceTypeManager, providerManager, programManager, MockRepository.GenerateMock<IFileProcessor>()); ControllerContext controllerContext = new ControllerContext(new HttpContextWrapper(context), new RouteData(), Target); Target.ControllerContext = controllerContext; }
private void initializeManagers(string organizationName, string providerName, string deactivationName) { orgManager = new OrganizationManager(organizationName); proManager = new ProviderManager(providerName); deaManager = new DeactivationManager(deactivationName); }
/// <summary> /// Consulta a NFSe/RPS que atende os filtros informados. /// /// Obs.: Nem todos provedores suportam este metodo. /// </summary> /// <param name="numero">The numero.</param> /// <param name="serie">The serie.</param> /// <param name="tipo">The tipo.</param> /// <returns>RetornoWebservice.</returns> /// <exception cref="NotImplementedException"></exception> public RetornoWebservice ConsultaNFSeRps(string numero, string serie, TipoRps tipo) { var provider = ProviderManager.GetProvider(Configuracoes); return(provider.ConsultaNFSeRps(numero, serie, tipo, NotasFiscais)); }
/// <summary> /// Consulta a situação do lote de RPS. /// /// Obs.: Nem todos provedores suportam este metodo. /// </summary> /// <param name="lote">The lote.</param> /// <param name="protocolo">The protocolo.</param> /// <returns>RetornoWebservice.</returns> public RetornoWebservice ConsultarSituacao(int lote, string protocolo = "") { var provider = ProviderManager.GetProvider(Configuracoes); return(provider.ConsultarSituacao(lote, protocolo)); }
public static void TestDetail <TEntity, TEntityPool>(string title) where TEntity : Entity where TEntityPool : EntityPool { string _left = ProviderManager.GetProvider(title.ToLower()).GetLeftEscape(); string _right = ProviderManager.GetProvider(title.ToLower()).GetRightEscape(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("=======" + title + " test running======="); var lo = Activator.CreateInstance <TEntityPool>(); DbTransaction tran = lo.BeginTransaction(); #region Betch Deal ShowExecuteTime("TestSave person 1000", () => { for (int i = 0; i < 1000; i++) { dynamic person = Activator.CreateInstance <TEntity>(); person.Name = "China" + i; person.Save(tran); Console.ForegroundColor = ConsoleColor.Cyan; //Console.WriteLine("Save person " + i + " sucessfully!"); } }); ShowExecuteTime("TestListSave no id person 1000", () => { var persons = new List <TEntity>(); for (int i = 0; i < 1000; i++) { dynamic person = Activator.CreateInstance <TEntity>(); person.Name = "China" + i; persons.Add(person); } lo.SaveOnly(tran, persons); }); ShowExecuteTime("TestListSave get id person 1000", () => { var persons = new List <TEntity>(); for (int i = 0; i < 1000; i++) { dynamic person = Activator.CreateInstance <TEntity>(); person.Name = "China" + i; persons.Add(person); } lo.Save(tran, persons); }); #endregion lo.Commit(); #region One dynamic p = Activator.CreateInstance <TEntity>(); ShowExecuteTime("Load one person", () => { p.Load(By.Id(3021)); }); ShowExecuteTime("Load partly condition", () => { p.Load(Partly.Columns("Id", "Name"), Condition.Where("Id", "Name")); }); p.Name = "12中国"; ShowExecuteTime("Update one person", () => { p.Update(); }); ShowExecuteTime("Save one person", () => { p.Save(); }); ShowExecuteTime("Load by sql, person", () => { p.Load(By.Sql("select * from " + _left + "Person" + _right + " order by " + _left + "Id" + _right + " desc")); }); ShowExecuteTime("Del one person", () => p.Del()); ShowExecuteTime("Get person count", () => { //var recordCount = TEntity }); //no trans p.Load(By.Id(3021)); p.Del(); p.Update(); #endregion #region List test ShowExecuteTime("ListTest", () => { var a = lo.List("select * from " + _left + "Person" + _right + ""); //var b = lo.List<TEntity>(By.All()); // var b1 = lo.List<TEntity>(By.All(false)); //var c = lo.List<TEntity>(By.Between(1, 10)); //var c1 = lo.List<TEntity>(By.Between(1, 10, false)); //var d = lo.List<TEntity>(By.Sql("select * from " + _left + "Person" + _right + "")); //var d1 = lo.List<TEntity>(By.Sql("select " + _left + "Name" + _right + " from " + _left + "Person" + _right + "")); //var e = lo.List<TEntity>(By.Top(10)); //var e1 = lo.List<TEntity>(By.Top(10, false)); //var l = lo.List<TEntity>(By.Page(1, 10)); //var l1 = lo.List<TEntity>(By.Page(1, 10, false)); }); #endregion dynamic p1 = Activator.CreateInstance <TEntity>(); dynamic p2 = Activator.CreateInstance <TEntity>(); p2.Name = "p2n"; ShowExecuteTime("TestListSave person 2", () => lo.Save(p1, p2)); p1.Name = "p1g"; p2.Name = "p2g"; ShowExecuteTime("TestListUpate person 2", () => lo.Update(p1, p2)); ShowExecuteTime("TestListDel person 2", () => lo.Del(p1, p2)); }
/// <summary> /// Получить аккаунты /// </summary> /// <param name="Text"></param> /// <param name="Managers"></param> /// <param name="IsApproved"></param> /// <param name="Groups"></param> /// <param name="Regions"></param> /// <param name="Operators"></param> /// <returns></returns> private static IEnumerable <ApplicationAccount> GetAccounts(string Text, int[] Managers, byte?IsApproved, int[] Groups, int[] Regions, int[] Operators, int?Id, string Login) { var AllAccounts = new List <ApplicationAccount>(); // список агентов var Agents = new List <int>(); using (var connection = new MySqlConnection(Const.DatabaseConnectionString)) { using (var command = connection.CreateCommand()) { // запрашиваем аккаунты command.CommandText = $@"SELECT my_aspnet_membership.IsApproved AS IsApproved, my_aspnet_membership.userId AS Id, my_aspnet_users.name AS Login, my_aspnet_roles.Id AS IdRole, my_aspnet_membership.Password AS Password, my_aspnet_membership.PasswordQuestion AS PasswordQuestion, my_aspnet_membership.Email AS Email, my_aspnet_membership.CreationDate AS CreationDate, my_aspnet_membership.LastActivityDate AS LastActivityDate, my_aspnet_membership.LastLoginDate AS LastLoginDate, my_aspnet_membership.LastPasswordChangedDate AS LastPasswordChangedDate, my_aspnet_membership.LastLockedOutDate AS LastLockedOutDate, my_aspnet_membership.IsLockedOut AS IsLockedOut, CONVERT(profile USING utf8) AS profile FROM my_aspnet_roles INNER JOIN my_aspnet_usersinroles ON my_aspnet_usersinroles.roleId = my_aspnet_roles.Id INNER JOIN my_aspnet_membership ON my_aspnet_usersinroles.userId = my_aspnet_membership.userId INNER JOIN my_aspnet_users ON my_aspnet_users.id = my_aspnet_membership.userId LEFT JOIN db_users_profiles ON db_users_profiles.userId = my_aspnet_membership.userId WHERE my_aspnet_roles.id = 4 OR ( {(IsApproved != null ? "my_aspnet_membership.IsApproved = @V1" : "my_aspnet_membership.IsApproved in (0,1)")} {(Groups != null ? " AND my_aspnet_roles.id IN({VGroups})" : string.Empty)} {(Id != null ? " AND my_aspnet_membership.userId = @V2" : string.Empty)} {(!string.IsNullOrEmpty(Login) ? " AND my_aspnet_users.name = V3" : string.Empty)} )"; command.Parameters.Clear(); command.Parameters.AddWithValue("V1", IsApproved); command.AddArrayParameters("VGroups", Groups); command.Parameters.AddWithValue("V2", Id); command.Parameters.AddWithValue("V3", Login); try { if (connection.State == ConnectionState.Closed) { connection.Open(); } using (var dataReader = command.ExecuteReader()) { if (dataReader.HasRows) { while (dataReader.Read()) { var IdRole = dataReader.GetInt32("IdRole"); ApplicationAccount NewAccount; if ((ApplicationAccountRoles)IdRole == ApplicationAccountRoles.Diler) { NewAccount = new SalesPoint(dataReader["profile"].ToString()); } else { NewAccount = new ApplicationUser(dataReader["profile"].ToString()); } NewAccount.Id = Convert.ToInt32(dataReader["Id"].ToString()); NewAccount.Login = dataReader["Login"].ToString(); NewAccount.Email = dataReader["Email"].ToString(); NewAccount.Password = dataReader["Password"].ToString(); NewAccount.PasswordQuestion = dataReader["PasswordQuestion"].ToString(); NewAccount.CreationDate = dataReader["CreationDate"].ToString(); NewAccount.LastPasswordChangedDate = dataReader["LastPasswordChangedDate"].ToString(); NewAccount.LastLockedOutDate = dataReader["LastLockedOutDate"].ToString(); NewAccount.LastActivityDate = dataReader["LastActivityDate"].ToString(); NewAccount.LastLoginDate = dataReader["LastLoginDate"].ToString(); NewAccount.IsLockedOut = dataReader.GetByte("IsLockedOut"); NewAccount.IsApproved = dataReader.GetByte("IsApproved"); NewAccount.IdRole = dataReader.GetInt32("IdRole"); AllAccounts.Add(NewAccount); // формируем список агентов, которые требуется запросить отдельно if (NewAccount is SalesPoint) { if (((SalesPoint)NewAccount).IdAgent != null) { Agents.Add((int)((SalesPoint)NewAccount).IdAgent); } } } } } } catch (Exception exception) { GoldenSIM.Core.Logs.RegisterError(GoldenSIM.Global.Const.DatabaseConnectionString, MethodBase.GetCurrentMethod().DeclaringType, ref exception, new StackTrace(false).GetFrame(0).GetMethod().Name); return(null); } } } //убираем дубли Agents.Distinct(); //получаем агентов List <Provider> Providers = ProviderManager.GetProviders(Agents).ToList(); foreach (var Account in AllAccounts) { //заполняем поле Manager у всех аккаунтов if (Account.IdManager != -1) { Account.Manager = AllAccounts.SingleOrDefault(x => x.Id.Equals(Account.IdManager))?.FullName; } //запоняем сведения об агенте для торговых точек if (Account is SalesPoint) { if (((SalesPoint)Account).IdAgent != null) { ((SalesPoint)Account).provider = Providers.SingleOrDefault(x => x.Id.Equals((int)((SalesPoint)Account).IdAgent)); } } } #region фильтры // *********** применяем фильтры********* if (IsApproved != null) { AllAccounts = AllAccounts.Where(x => x.IsApproved.Equals(IsApproved)).ToList(); } //по группам if (Groups?.Count() > 0) { AllAccounts = AllAccounts.Where(x => Groups.Any(y => y == x.IdRole)).ToList(); } //по тексту if (!string.IsNullOrEmpty(Text)) { AllAccounts = AllAccounts .Where(x => (!string.IsNullOrEmpty(x.Name) && x.Name.ToLower().Contains(Text)) || (!string.IsNullOrEmpty(x.Login) && x.Login.ToLower().Contains(Text)) || (!string.IsNullOrEmpty(x.FullName) && x.FullName.ToLower().Contains(Text)) ).ToList(); } //по менеджерам if (Managers?.Count() > 0) { AllAccounts = AllAccounts.Where(x => Managers.Any(y => y == x.IdManager)).ToList(); } //по региону для торговых точек if (Regions?.Count() > 0) { AllAccounts = AllAccounts.Where(x => x is SalesPoint && Regions.Any(y => y == ((SalesPoint)x).RegionId)).ToList(); } //по оператору для торговых точек if (Operators?.Count() > 0) { AllAccounts = AllAccounts.Where(x => x is SalesPoint && Operators.Any(y => y == ((SalesPoint)x).IdOperator)).ToList(); } //по ID if (Id != null) { AllAccounts = AllAccounts.Where(x => x.Id.Equals(Id)).ToList(); } //по логину if (!string.IsNullOrEmpty(Login)) { AllAccounts = AllAccounts.Where(x => x.Login.Equals(Login)).ToList(); } #endregion // применяем фильтры //AllAccounts = (from x in AllAccounts // where // (IsApproved != null && x.IsApproved.Equals(IsApproved)) & // (Groups?.Count() > 0 && Groups.Any(y => y == x.IdRole)) & // (!string.IsNullOrEmpty(Text) && (x.Name.ToLower().Contains(Text) || x.Login.ToLower().Contains(Text) || x.FullName.ToLower().Contains(Text))) & // (Managers?.Count() > 0 && (x is SalesPoint && Regions.Any(y => y == ((SalesPoint)x).RegionId))) & // (Regions?.Count() > 0 && (x is SalesPoint && Regions.Any(y => y == ((SalesPoint)x).RegionId))) & // (Operators?.Count() > 0 && (x is SalesPoint && Operators.Any(y => y == ((SalesPoint)x).IdOperator))) // select x).ToList(); return(AllAccounts); }
/// <summary> /// Consulta o lote de Rps /// /// Obs.: Nem todos provedores suportam este metodo. /// </summary> /// <param name="protocolo">The protocolo.</param> /// <param name="lote">The lote.</param> /// <returns>RetornoWebservice.</returns> /// <exception cref="NotImplementedException"></exception> public RetornoWebservice ConsultarLoteRps(int lote, string protocolo) { var provider = ProviderManager.GetProvider(Configuracoes); return(provider.ConsultarLoteRps(lote, protocolo, NotasFiscais)); }
/// <summary> /// Gera o Xml Da Rps /// </summary> /// <param name="nota"></param> /// <returns></returns> public string GetXml(NotaFiscal nota) { var provider = ProviderManager.GetProvider(config); return(nota.IdentificacaoNFSe.Numero.IsEmpty() ? provider.GetXmlRps(nota) : provider.GetXmlNFSe(nota)); }
private static UserInfo GetUser(string userName, string password, string provider, string accessToken, out bool viaEmail) { viaEmail = true; var action = MessageAction.LoginFailViaApi; UserInfo user = null; try { if (string.IsNullOrEmpty(provider) || provider == "email") { userName.ThrowIfNull(new ArgumentException(@"userName empty", "userName")); password.ThrowIfNull(new ArgumentException(@"password empty", "password")); int counter; int.TryParse(Cache.Get <String>("loginsec/" + userName), out counter); if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(userName)) { throw new Authorize.BruteForceCredentialException(); } Cache.Insert("loginsec/" + userName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); if (EnableLdap) { var localization = new LdapLocalization(Resource.ResourceManager); var ldapUserManager = new LdapUserManager(localization); ldapUserManager.TryGetAndSyncLdapUserInfo(userName, password, out user); } if (user == null || !CoreContext.UserManager.UserExists(user.ID)) { user = CoreContext.UserManager.GetUsers( CoreContext.TenantManager.GetCurrentTenant().TenantId, userName, Hasher.Base64Hash(password, HashAlg.SHA256)); } if (user == null || !CoreContext.UserManager.UserExists(user.ID)) { throw new Exception("user not found"); } Cache.Insert("loginsec/" + userName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); } else { viaEmail = false; action = MessageAction.LoginFailViaApiSocialAccount; var thirdPartyProfile = ProviderManager.GetLoginProfile(provider, accessToken); userName = thirdPartyProfile.EMail; user = LoginWithThirdParty.GetUserByThirdParty(thirdPartyProfile); } } catch (Authorize.BruteForceCredentialException) { MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce); throw new AuthenticationException("Login Fail. Too many attempts"); } catch { MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, action); throw new AuthenticationException("User authentication failed"); } var tenant = CoreContext.TenantManager.GetCurrentTenant(); var settings = IPRestrictionsSettings.Load(); if (settings.Enable && user.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant)) { throw new IPSecurityException(); } return(user); }
public void InitializeTest() { Target = new ProviderManager(Repositories.MockRepositoryContainer, MockDataTableBinder); }
/// <summary> /// Default constructor for the authorization service /// </summary> /// <param name="logger"></param> /// <param name="providerManager"></param> /// <param name="refreshTokenRespository"></param> public AuthorizationService(ILogger <AuthorizationService> logger, ProviderManager providerManager, IRefreshTokenRepository refreshTokenRespository) : base(logger) { this.providerManager = providerManager; this.refreshTokenRespository = refreshTokenRespository; }