private Node GetUserByActivationId() { var activationId = HttpContext.Current.Request.Params["ActivationId"]; if (String.IsNullOrEmpty(activationId)) { return(null); } if (!IsGuid(activationId)) { return(null); } AccessProvider.ChangeToSystemAccount(); List <Node> result = GetUserByActivationIdInternal(activationId); AccessProvider.RestoreOriginalUser(); if (result.Count == 0) { WriteAlreadyActivatedMessage(); return(null); // write message: user is already activated } return(result.First()); }
/// <summary> /// Sets the access provider responsible for user-related technical operations in the system. /// </summary> /// <param name="accessProvider">AccessProvider instance.</param> public RepositoryBuilder UseAccessProvider(AccessProvider accessProvider) { Configuration.Providers.Instance.AccessProvider = accessProvider; WriteLog("AccessProvider", accessProvider); return(this); }
/// <summary> /// Gets ICollection of Device /// </summary> /// <param name="accessProvider">Implementation of AccessProvider to provide access to devices</param> /// <param name="hostNames">To lookup and gather information</param> /// <param name="cancellationToken">To cancel the Tasks started by calling the method</param> /// <returns>Returns awaitable Task with ICollection of Device</returns> public async Task <List <Device> > GetDevicesAsync(AccessProvider accessProvider, IEnumerable <string> hostNames, CancellationToken cancellationToken = new CancellationToken()) { if (accessProvider == null) { throw new ArgumentNullException(nameof(accessProvider)); } var devices = new List <Device>(); var deviceAdds = new List <Task>(); foreach (var hostName in hostNames) { var task = Task.Run(async() => { var device = await TryGetDeviceAsync(accessProvider, hostName, cancellationToken, InformationCategories, InformationTypes).ConfigureAwait(false); if (device != null) { devices.Add(device); } }, cancellationToken); deviceAdds.Add(task); } await Task.WhenAll(deviceAdds).ConfigureAwait(false); Devices = devices; return(Devices); }
private async Task <Device> TryGetDeviceAsync(AccessProvider accessProvider, string hostName, CancellationToken cancellationToken = new CancellationToken(), InformationCategory[] informationCategories = null, params InformationType[] informationTypes) { return(await Task.Run(async() => { try { if (accessProvider != null) { var wmiAccessService = await accessProvider.GetAccessAsync(hostName).ConfigureAwait(false); if (wmiAccessService != null) { return await TryGetDeviceAsync(wmiAccessService, cancellationToken, informationCategories, informationTypes).ConfigureAwait(false); } } } catch (OperationCanceledException operationCanceledException) { LogEventHandler.TaskIncompleted(operationCanceledException); } catch (Exception exception) { var wmiException = new WMIGeneralException(hostName, exception); LogEventHandler.Exception(wmiException); } return null; }, cancellationToken).ConfigureAwait(false)); }
public SetLoginStartAction(AccessProvider accessProvider) { AccessProvider = accessProvider; Status = Status.Setting; User = null; Error = null; }
private User GetRegisteredUser(string resetEmail, string domain) { if (String.IsNullOrEmpty(resetEmail)) { throw new ArgumentNullException("resetEmail"); } if (String.IsNullOrEmpty(domain)) { throw new ArgumentNullException("domain"); } var query = new NodeQuery(); var expressionList = new ExpressionList(ChainOperator.And); expressionList.Add(new TypeExpression(ActiveSchema.NodeTypes[Configuration.UserTypeName], false)); expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, string.Concat(Repository.ImsFolderPath, RepositoryPath.PathSeparator, domain, RepositoryPath.PathSeparator))); expressionList.Add(new StringExpression(ActiveSchema.PropertyTypes["Email"], StringOperator.Equal, resetEmail)); query.Add(expressionList); AccessProvider.ChangeToSystemAccount(); var resultList = query.Execute(); AccessProvider.RestoreOriginalUser(); // no user has beeen found if (resultList.Count == 0) { return(null); } var u = resultList.Nodes.First() as User; return(u); }
/// <summary> /// Executes the boot sequence of the Repository by the passed <see cref="RepositoryStartSettings"/>. /// </summary> /// <example> /// Use the following code in your tool or other outer application: /// <code> /// var startSettings = new RepositoryStartSettings /// { /// PluginsPath = pluginsPath, // Local directory path of plugins if it is different from your tool's path. /// Console = Console.Out // Startup sequence will be traced to given writer. /// }; /// using (ContentRepository.Repository.Start(startSettings)) /// { /// // your code /// } /// </code> /// </example> /// <remarks> /// Repository will be stopped if the returned <see cref="RepositoryStartSettings"/> instance is disposed. /// </remarks> /// <returns>A new IDisposable <see cref="RepositoryInstance"/> instance.</returns> /// <returns></returns> public static RepositoryInstance Start(RepositoryStartSettings settings) { var instance = RepositoryInstance.Start(settings); AccessProvider.ChangeToSystemAccount(); Repository._root = (PortalRoot)Node.LoadNode(RootPath); AccessProvider.RestoreOriginalUser(); return(instance); }
public void TestCoinRetrievalLocal() { var AccessProvider = new AccessProvider(testProvider); var coins1 = AccessProvider.GetCoins(start_test); Assert.AreEqual(3, coins1.Count); Assert.AreEqual(coins1, testProvider.Coins); }
public override IUser GetCurrentUser() { if (!_initialized) { _initialized = true; AccessProvider.ChangeToSystemAccount(); CurrentUser = User.Administrator; } return(CurrentUser); }
public Downloader(Logger logger, AccessProvider accessProvider, DownloadProvider downloadProvider, SettingsProvider settingsProvider, FileService fileService) { _logger = logger; _accessProvider = accessProvider; _downloadProvider = downloadProvider; _settingsProvider = settingsProvider; _fileService = fileService; _driveService = new DriveService(); }
public static void RedirectTo(this Page page) { AccessProvider.ChangeToSystemAccount(); var sitepath = PortalContext.Current.Site.Path; var pagepath = PortalContext.Current.Site.StartPage.Path; pagepath = pagepath.Substring(sitepath.Length); AccessProvider.RestoreOriginalUser(); HttpContext.Current.Response.Redirect(pagepath); }
public Task <Tuple <User, string> > GetUser(string uri, AccessProvider accessProvider) { if (accessProvider == AccessProvider.Facebook) { return(facebookUserProvider.GetUserAndAccessToken(uri)); } else if (accessProvider == AccessProvider.Google) { return(googleUserProvider.GetUserAndAccessToken(uri)); } throw new ArgumentException(); }
public override IUser GetCurrentUser() { if (!_initialized) { _initialized = true; //TODO: if the repository is not running, return a placeholder user // instead of trying to load the user or the admin from the database. AccessProvider.ChangeToSystemAccount(); CurrentUser = User.Administrator; } return(CurrentUser); }
private IRepositoryBuilder CreateRepositoryBuilder(AccessProvider accessProvider = null, ISearchEngine searchEngine = null) { var services = CreateServiceProviderForTest(); Providers.Instance = new Providers(services); var dbProvider = services.GetRequiredService <DataProvider>(); return(new RepositoryBuilder(services) .UseAccessProvider(accessProvider ?? new DesktopAccessProvider()) .UseInitialData(GetInitialData()) .UseBlobMetaDataProvider(new InMemoryBlobStorageMetaDataProvider(dbProvider)) .UseBlobProviderSelector(new InMemoryBlobProviderSelector()) .AddBlobProvider(new InMemoryBlobProvider()) .UseSearchEngine(searchEngine ?? services.GetRequiredService <ISearchEngine>()) .StartIndexingEngine(false) .StartWorkflowEngine(false) .UseTraceCategories("Test", "Web", "System")); }
private static async void ProcessQueue() { while (true) { var sendThis = Queue.Take(); var sheetName = (string)sendThis[0][0]; var accessProvider = new AccessProvider(AccessType.ServiceAccount); bool isSent; do { isSent = accessProvider.WriteData(sendThis, sheetName); if (isSent) { continue; } Console.WriteLine("Try data trasfer after 2s!"); await Task.Delay(2000); } while (!isSent); } }
private File LoadOrCreateFile(string path) { AccessProvider.ChangeToSystemAccount(); var file = Node.LoadNode(path) as File; AccessProvider.RestoreOriginalUser(); if (file != null) return file; var parentPath = RepositoryPath.GetParentPath(path); var parentFolder = (Folder)Node.LoadNode(parentPath) ?? LoadOrCreateFolder(parentPath); file = new File(parentFolder) { Name = RepositoryPath.GetFileName(path), Binary = TestTools.CreateTestBinary() }; file.Save(); AddPathToDelete(path); return file; }
private static IHttpAction GetExternalPageAction(IHttpActionFactory factory, PortalContext portalContext, NodeHead contextNode, string actionName, string appNodePath) { if (contextNode == null) { return(null); } if (actionName != null) { return(null); } if (appNodePath != null) { return(null); } string outerUrl = null; AccessProvider.ChangeToSystemAccount(); try { Page page = Node.LoadNode(contextNode.Id) as Page; if (page != null) { if (Convert.ToBoolean((page["IsExternal"]))) { outerUrl = page.GetProperty <string>("OuterUrl"); } } } finally { AccessProvider.RestoreOriginalUser(); } if (outerUrl != null) { return(factory.CreateRedirectAction(portalContext, contextNode, null, outerUrl, false, true)); } return(null); }
protected void Page_Load(object sender, EventArgs e) { Dictionary <string, string> param = PluginBuilderFactory.getProperties(Request); PluginBuilder pb = PluginBuilderFactory.newPluginBuilder(Request, Response); AccessProvider accessProvider = pb.getAccessProvider(); if (accessProvider != null && !accessProvider.requireAccess()) { return; } // Adding - if necessary - CORS headers com.wiris.system.service.HttpResponse res = new com.wiris.system.service.HttpResponse(this.Response); String origin = this.Request.Headers.Get("origin"); pb.addCorsHeaders(res, origin); Response.ContentType = "application/json"; string r = pb.getConfiguration().getJavaScriptConfigurationJson(); this.Response.Write(r); }
public DeviceCollection(ICredentialsProvider credentialsProvider, InformationCategory[] informationCategories = null, params InformationType[] informationTypes) : this() { _accessProvider = new AccessProvider(credentialsProvider); InformationCategories = informationCategories; InformationTypes = informationTypes; }
private void CreateControls() { this.Controls.Clear(); if (string.IsNullOrEmpty(CvPath)) { return; } try { var qv = Page.LoadControl(CvPath) as QueryView; if (qv == null) { return; } var contentQuery = GetQuery(); if (contentQuery == null) { return; } if (IsSystemAccount) { AccessProvider.ChangeToSystemAccount(); } //get full result list, without loading the nodes var result = contentQuery.Execute(); var fullCount = result.Count; if (EnablePaging) { //Get results for current page only. //Merge two mechanisms: url params and paging if (this.CQPParamsExist) { contentQuery.Settings.Skip = (this.CurrentPage - 1) * this.PageSize + this.SkipFirst + this.CQPStartIndex - 1; contentQuery.Settings.Top = this.CQPPageSize; } else { contentQuery.Settings.Skip = (this.CurrentPage - 1) * this.PageSize + this.SkipFirst; contentQuery.Settings.Top = this.PageSize > 0 ? this.PageSize : NodeQuery.UnlimitedPageSize - 1; } result = contentQuery.Execute(); } //refresh pager controls foreach (var pc in qv.PagerControls) { if (EnablePaging) { pc.ResultCount = fullCount; pc.PageSize = contentQuery.Settings.Top; pc.CurrentPage = this.CurrentPage; pc.EnableSettingPageSize = this.EnableSettingPageSize; pc.OnPageSelected += PagerControl_OnPageSelected; pc.OnPageSizeChanged += PagerControl_OnPageSizeChanged; } else { pc.Visible = false; } } if (IsSystemAccount) { AccessProvider.RestoreOriginalUser(); } qv.ID = "QueryView"; //qv.NodeItemList = result.CurrentPage.ToList(); qv.NodeItemList = result.Nodes.ToList(); this.Controls.Add(qv); } catch (Exception ex) { Logger.WriteException(ex); this.Controls.Add(new LiteralControl(ex.ToString())); } }
public OneWireAdapter(OneWireAdapterConfiguration config) { adapter = AccessProvider.GetAdapter(config.AdapterName, config.PortName); }
private static string RegisterHost() { string resultMessage; try { AccessProvider.ChangeToSystemAccount(); var query = new NodeQuery(); ContentRepository.Storage.Schema.NodeType nt = ActiveSchema.NodeTypes["Site"]; query.Add(new TypeExpression(nt, false)); var result = query.Execute(); AccessProvider.RestoreOriginalUser(); if (result.Count > 0) { var defSiteName = System.Web.Configuration.WebConfigurationManager.AppSettings["DefaultSiteName"] ?? "Default Site"; var authoryity = HttpContext.Current.Request.Url.Authority; var site = (from n in result.Nodes where n.Name == defSiteName select n).FirstOrDefault() as Site; if (site == null) { return(string.Format("No site exists in the repository with the name {0}", defSiteName)); } if (!site.UrlList.ContainsKey(authoryity)) { // default authentication mode var authMode = System.Web.Configuration.WebConfigurationManager.AppSettings["DefaultAuthenticationMode"]; var newList = new Dictionary <string, string>(site.UrlList) { { authoryity, authMode } }; site.UrlList = newList; AccessProvider.Current.SetCurrentUser(ContentRepository.User.Administrator); site.Save(); resultMessage = string.Format( "The host '{0}' has been succesfully assigned to the site '{1}'.", authoryity, site.Path); } else { resultMessage = string.Format("The host '{0}' is already assigned to the site '{1}'.", authoryity, site.Path); } } else { resultMessage = string.Format("You cannot use RegisterHost if you don't have a Site in your ContentRepositoy."); } } catch (Exception ex) //logged { Logger.WriteException(ex); resultMessage = ex.Message; } return(resultMessage); }
/// <summary> /// DeviceCollection to use the provided CredentialsProvider to get access /// </summary> /// <param name="credentialsProvider">Provides credential</param> /// <returns>Returns this with provided CredentialsProvider</returns> public IDeviceCollection WithCredentials(ICredentialsProvider credentialsProvider) { Setup(HasExecuted()); _accessProvider = new AccessProvider(credentialsProvider); return(this); }
public Sensor(string adapterName, string portName) { adapter = AccessProvider.GetAdapter(adapterName, portName); }
public AuthenticationProvider() { this._provider = new AccessProvider(); }
private void btnPovezi_Click(object sender, RoutedEventArgs e) { try { if (berem == false) { if ((String.IsNullOrEmpty(tbComPort.Text)) || (String.IsNullOrEmpty(tbRazmikProzenja.Text))) { MessageBox.Show("Potrebno je vnesti COM port in razmik proženja!"); return; } GeoCoordinateWatcher lokacija = new GeoCoordinateWatcher(); int stPonovitev = 0; while (stPonovitev <= 10) { lokacija.TryStart(false, TimeSpan.FromMilliseconds(10000)); GeoCoordinate koordinate = lokacija.Position.Location; if (koordinate.IsUnknown != true) { var latitude = koordinate.Latitude; var longitude = koordinate.Longitude; string[] lokacijaArray = DobiNaslovIzGMaps(latitude.ToString(new CultureInfo("en-US")), longitude.ToString(new CultureInfo("en-US"))); lokacijaStr = lokacijaArray[0]; drzavaStr = lokacijaArray[1]; break; } Thread.Sleep(2000); stPonovitev++; } adapter = AccessProvider.GetAdapter("{DS9097}", tbComPort.Text); OneWireContainer container = adapter.GetDeviceContainer(StringToByteArray("28FF945B521604BF")); string owcType = container.GetType().ToString(); if (owcType.Equals("DalSemi.OneWire.Container.OneWireContainer28")) { // imamo DS18S20 adapter.SelectDevice(container.Address); ZapisiLog("Pričenjam brati ..."); timer = new DispatcherTimer(); timer.Tick += Timer_Tick; timer.Interval = new TimeSpan(0, 0, Int32.Parse(tbRazmikProzenja.Text)); timer.Start(); berem = true; btnPovezi.Content = "Končaj brati"; } Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); if (config.AppSettings.Settings["tbComPort"] == null) { config.AppSettings.Settings.Add("tbComPort", tbComPort.Text); } else { config.AppSettings.Settings["tbComPort"].Value = tbComPort.Text; } if (config.AppSettings.Settings["tbRazmikProzenja"] == null) { config.AppSettings.Settings.Add("tbRazmikProzenja", tbRazmikProzenja.Text); } else { config.AppSettings.Settings["tbRazmikProzenja"].Value = tbRazmikProzenja.Text; } if (config.AppSettings.Settings["tbAPIUrl"] == null) { config.AppSettings.Settings.Add("tbAPIUrl", tbAPIUrl.Text); } else { config.AppSettings.Settings["tbAPIUrl"].Value = tbAPIUrl.Text; } if (config.AppSettings.Settings["tbStrukturaPodatkov"] == null) { config.AppSettings.Settings.Add("tbStrukturaPodatkov", tbStrukturaPodatkov.Text); } else { config.AppSettings.Settings["tbStrukturaPodatkov"].Value = tbStrukturaPodatkov.Text; } if (config.AppSettings.Settings["tbMin"] == null) { config.AppSettings.Settings.Add("tbMin", tbMin.Text); } else { config.AppSettings.Settings["tbMin"].Value = tbMin.Text; } if (config.AppSettings.Settings["tbMax"] == null) { config.AppSettings.Settings.Add("tbMax", tbMax.Text); } else { config.AppSettings.Settings["tbMax"].Value = tbMax.Text; } if (config.AppSettings.Settings["tbTarget"] == null) { config.AppSettings.Settings.Add("tbTarget", tbTarget.Text); } else { config.AppSettings.Settings["tbTarget"].Value = tbTarget.Text; } config.Save(ConfigurationSaveMode.Minimal); } else { timer.Stop(); ZapisiLog("Končal sem brati ..."); berem = false; btnPovezi.Content = "Poveži in beri"; } } catch (Exception _ex) { ZapisiLog("NAPAKA: " + _ex.Message); ZapisiLog(_ex.StackTrace); } }
public StoreExtensions.AsyncActionCreator <ApplicationState> Login(string uri, AccessProvider accessProvider) { return(async(dispatch, getState) => { try { dispatch(new SetLoginStartAction(accessProvider)); Tuple <User, string> externalServerUserTuple = await externalServiceUserProvider.GetUser(uri, accessProvider); User userFromExternalService = externalServerUserTuple.Item1; string externalAccessToken = externalServerUserTuple.Item2; var loggedInUserWithoutTokens = await userService.LoginOrRegisterAndLoginExternalUserAsync(userFromExternalService, externalAccessToken); var tokens = await userService.GetTokensAsync(loggedInUserWithoutTokens.Id.ToString(), "externaluser"); var loggedInUserWithTokens = loggedInUserWithoutTokens .Set(v => v.AccessToken, tokens.Item1) .Set(v => v.RefreshToken, tokens.Item2) .Build(); dispatch(new SetLoggedInUserAction(loggedInUserWithTokens)); dispatch(new SetLoginCompleteAction(loggedInUserWithTokens)); } catch (Exception e) { dispatch(new SetLoginCompleteAction(new Exception("Sorry, something went wrong :(. Try again later." + e.Message))); } }); }
private List <Node> RunSearch(string queryString) { NodeQuery query = new NodeQuery(); if (string.IsNullOrEmpty(queryString)) { queryString = string.Empty; } if (string.IsNullOrEmpty(FullQueryXML)) { StringBuilder queryXML = new StringBuilder(); queryXML.Append("<SearchExpression xmlns=\"").Append(NodeQuery.XmlNamespace).AppendLine("\">"); queryXML.AppendLine(" <And>"); if (!string.IsNullOrEmpty(queryString)) { queryXML.AppendLine(string.Concat(" <FullText>\"", queryString, "*\"</FullText>")); } queryXML.AppendLine(" <Not><String op=\"StartsWith\" property=\"Path\">/Root/System</String></Not>"); //queryXML.AppendLine(" <Type nodeType=\"Page\" />"); //queryXML.AppendLine(string.Concat(" <String op=\"StartsWith\" property=\"Path\">", Portal.Virtualization.PortalContext.Current.Site.Path, "</String>")); queryXML.AppendLine(ExtraQueryXML); queryXML.AppendLine(" </And>"); queryXML.AppendLine("</SearchExpression>"); query = NodeQuery.Parse(queryXML.ToString()); } else { if (AllowEmptySearch && string.IsNullOrEmpty(queryString)) { int start = FullQueryXML.IndexOf("<FullText"); if (start > -1) { int end = FullQueryXML.IndexOf("</FullText>"); query = NodeQuery.Parse(string.Concat(FullQueryXML.Substring(0, start), FullQueryXML.Substring(end + 11))); } else { query = NodeQuery.Parse(FullQueryXML.Replace("#SEARCH_STRING", queryString)); } } else { query = NodeQuery.Parse(FullQueryXML.Replace("#SEARCH_STRING", queryString)); } } var nodeList = new List <Node>(); try { if (IsSystemAccount) { AccessProvider.ChangeToSystemAccount(); } nodeList = query.Execute().Nodes.ToList(); } catch (Exception ex) //logged { Logger.WriteException(ex); Controls.Add(new LiteralControl(string.Concat("!<!--", ex.Message, " ", ex.StackTrace, "-->"))); } finally { if (IsSystemAccount) { AccessProvider.RestoreOriginalUser(); } } return(nodeList); }