/// <summary> /// Check the path and perform various corrections /// </summary> /// <param name="virtualPath">primary path to use</param> /// <param name="relativePath">optional second path to which the primary one would be attached to</param> /// <returns>null if all is ok, or an error message if not</returns> private string CheckIfPathsOkAndCleanUp(ref string virtualPath, string relativePath) { if (string.IsNullOrWhiteSpace(virtualPath)) { return("no path/name provided"); } // if path relative, merge with shared code path virtualPath = virtualPath.Replace("\\", "/"); if (!virtualPath.StartsWith("/")) { Log.Add($"Trying to resolve relative path: '{virtualPath}' using '{relativePath}'"); if (relativePath == null) { return("Unexpected null value on relativePath"); } // if necessary, add trailing slash if (!relativePath.EndsWith("/")) { relativePath += "/"; } virtualPath = _serviceProvider.Build <ILinkPaths>().ToAbsolute(relativePath, virtualPath); Log.Add($"final virtual path: '{virtualPath}'"); } if (virtualPath.IndexOf(":", StringComparison.InvariantCultureIgnoreCase) > -1) { return($"Tried to get .cs file, but found '{virtualPath}' containing ':', (not allowed)"); } return(null); }
public static IApp Init(this App app, IServiceProvider sp, int appId, ILog log, bool showDrafts = false) { var appIdentity = new AppIdentity(SystemRuntime.ZoneIdOfApp(appId), appId); var confProvider = sp.Build <AppConfigDelegate>().Init(log); return(app.Init(confProvider, appIdentity, log, showDrafts)); }
private IBlock GetBlock() { var context = _oqtTempInstanceContext.CreateContext(Page.PageId, Module, Log); var block = _serviceProvider.Build <BlockFromModule>().Init(context, Log); return(block); }
public override ISite SiteOfZone(int zoneId) { var sites = _siteRepository.GetSites().ToList(); var found = sites.FirstOrDefault(p => HasZoneId(p.SiteId, out var zoneOfSite) && zoneOfSite == zoneId); return(found != null?_serviceProvider.Build <OqtSite>().Init(found) : null); }
/// <summary> /// Initializes the object and performs all the initial security checks /// </summary> public virtual AdamContext Init(IContextOfApp context, string contentType, string fieldName, Guid entityGuid, bool usePortalRoot, ILog parentLog) { Log.LinkTo(parentLog); var appId = context.AppState.AppId; var callLog = Log.Call <AdamContext>($"app: {context.AppState.Show()}, field:{fieldName}, guid:{entityGuid}"); Context = context; Permissions = ServiceProvider.Build <MultiPermissionsTypes>() .Init(context, context.AppState, contentType, Log); // only do checks on field/guid if it's actually accessing that, if it's on the portal root, don't. UseSiteRoot = usePortalRoot; if (!usePortalRoot) { ItemField = fieldName; ItemGuid = entityGuid; } Security = ServiceProvider.Build <AdamSecurityChecksBase>().Init(this, usePortalRoot, Log); if (Security.MustThrowIfAccessingRootButNotAllowed(usePortalRoot, out var exception)) { throw exception; } Log.Add("check if feature enabled"); if (Security.UserIsRestricted && !Eav.Configuration.Features.Enabled(FeaturesForRestrictedUsers)) { throw HttpException.PermissionDenied( $"low-permission users may not access this - {Eav.Configuration.Features.MsgMissingSome(FeaturesForRestrictedUsers)}"); } if (string.IsNullOrEmpty(contentType) || string.IsNullOrEmpty(fieldName)) { return(callLog(null, this)); } Attribute = AttributeDefinition(appId, contentType, fieldName); if (!Security.FileTypeIsOkForThisField(out var exp)) { throw exp; } return(callLog(null, this)); }
public IContextOfBlock CreateContext(int pageId, Module module, ILog parentLog) { var ctx = _serviceProvider.Build <IContextOfBlock>(); ctx.Init(parentLog); ctx.Page.Init(pageId); ((OqtContainer)ctx.Module).Init(module, parentLog); return(ctx); }
public bool Create(int appId, string path, FileContentsDto content, bool global = false) { Log.Add($"create a#{appId}, path:{path}, global:{global}, cont-length:{content.Content?.Length}"); path = path.Replace("/", "\\"); var thisApp = _serviceProvider.Build <Apps.App>().InitNoData(new AppIdentity(Eav.Apps.App.AutoLookupZone, appId), Log); if (content.Content == null) { content.Content = ""; } path = SanitizePathAndContent(path, content); var isAdmin = _user.IsAdmin; var assetEditor = _assetEditorLazy.Value.Init(thisApp, path, _user.IsSuperUser, isAdmin, global, Log); assetEditor.EnsureUserMayEditAssetOrThrow(path); return(assetEditor.Create(content.Content)); }
public static IApp Init(this App app, IServiceProvider sp, int appId, ILog log, IBlock optionalBlock = null, bool showDrafts = false) { var appIdentity = new AppIdentity(SystemRuntime.ZoneIdOfApp(appId), appId); var confProvider = sp.Build <AppConfigDelegate>().Init(log); if (optionalBlock == null) { return(app.Init(confProvider, appIdentity, log, showDrafts)); } var buildConfig = confProvider.Build(optionalBlock); return(app.Init(appIdentity, buildConfig, log)); }
public static IContextOfBlock CreateContext(IServiceProvider sp, int zoneId, int pageId, int containerId, int appId, Guid blockGuid) { var ctx = sp.Build <IContextOfBlock>(); ctx.Init(null); ctx.Site.Init(zoneId); ctx.Page.Init(pageId); ((MvcModule)ctx.Module).Init(tenantId: zoneId, id: containerId, appId: appId, block: blockGuid); return(ctx); //var publishing = sp.Build<IPagePublishingResolver>(); //return new ContextOfBlock( // sp, // sp.Build<ISite>().Init(zoneId), // //new SxcPage(pageId, null, http.RequestServices.Build<IHttp>().QueryStringKeyValuePairs()), // //new MvcContainer(tenantId: zoneId, id: containerId, appId: appId, block: blockGuid), // new MvcUser() // //publishing.GetPublishingState(containerId) //).Init( // sp.Build<SxcPage>().Init(pageId), // new MvcContainer(tenantId: zoneId, id: containerId, appId: appId, block: blockGuid), // publishing.GetPublishingState(containerId) //); }
public WorkflowExecutor(IServiceProvider sp) { this.sp = sp; this.workflow = sp.Build <T>(); }
/// <summary> /// Get search info for each dnn module containing 2sxc data /// </summary> /// <returns></returns> public IList <SearchDocument> GetModifiedSearchDocuments(IModule module, DateTime beginDate) { var searchDocuments = new List <SearchDocument>(); var dnnModule = (module as Module <ModuleInfo>)?.UnwrappedContents; // always log with method, to ensure errors are caught Log.Add($"start search for mod#{dnnModule?.ModuleID}"); // turn off logging into history by default - the template code can reactivate this if desired Log.Preserve = false; if (dnnModule == null) { return(searchDocuments); } // New Context because Portal-Settings.Current is null var appId = module.BlockIdentifier.AppId; if (appId == AppConstants.AppIdNotFound || appId == Eav.Constants.NullId) { return(searchDocuments); } // Since Portal-Settings.Current is null, instantiate with modules' portal id (which can be a different portal!) //var portalSettings = new PortalSettings(dnnModule.OwnerPortalID); var site = new DnnSite().TrySwap(dnnModule);//.Swap(portalSettings); // Ensure cache builds up with correct primary language var cache = State.Cache; cache.Load(module.BlockIdentifier, site.DefaultCultureCode); var dnnContext = Eav.Factory.StaticBuild <IContextOfBlock>().Init(dnnModule, Log); var modBlock = _serviceProvider.Build <BlockFromModule>() .Init(dnnContext, Log); //.Init(DnnContextOfBlock.Create(site, container, Eav.Factory.GetServiceProvider()), Log); var language = dnnModule.CultureCode; var view = modBlock.View; if (view == null) { return(searchDocuments); } // This list will hold all EAV entities to be indexed var dataSource = modBlock.Data; // 2020-03-12 Try to attach DNN Lookup Providers so query-params like [DateTime:Now] or [Portal:PortalId] will work if (dataSource?.Configuration?.LookUpEngine != null) { Log.Add("Will try to attach dnn providers to DataSource LookUps"); try { var getLookups = (DnnLookUpEngineResolver)_serviceProvider.Build <DnnLookUpEngineResolver>().Init(Log); var dnnLookUps = getLookups.GenerateDnnBasedLookupEngine(site.UnwrappedContents, dnnModule.ModuleID); ((LookUpEngine)dataSource.Configuration.LookUpEngine).Link(dnnLookUps); } catch (Exception e) { Log.Add("Ran into an issue with an error: " + e.Message); } } var engine = EngineFactory.CreateEngine(view); engine.Init(modBlock, Purpose.IndexingForSearch, Log); // see if data customization inside the cshtml works try { engine.CustomizeData(); } catch (Exception e) // Catch errors here, because of references to Request etc. { Exceptions.LogException(new SearchIndexException(dnnModule, e)); } var searchInfoDictionary = new Dictionary <string, List <ISearchItem> >(); // Get DNN SearchDocuments from 2Sexy SearchInfos foreach (var stream in dataSource.Out.Where(p => p.Key != ViewParts.Presentation && p.Key != ViewParts.ListPresentation)) { var entities = stream.Value.Immutable; var searchInfoList = searchInfoDictionary[stream.Key] = new List <ISearchItem>(); searchInfoList.AddRange(entities.Select(entity => { var searchInfo = new SearchItem { Entity = entity, Url = "", Description = "", Body = GetJoinedAttributes(entity, language), Title = entity.Title?[language]?.ToString() ?? "(no title)", ModifiedTimeUtc = (entity.Modified == DateTime.MinValue ? DateTime.Now.Date.AddHours(DateTime.Now.Hour) : entity.Modified).ToUniversalTime(), UniqueKey = "2sxc-" + dnnModule.ModuleID + "-" + (entity.EntityGuid != new Guid() ? entity.EntityGuid.ToString() : (stream.Key + "-" + entity.EntityId)), IsActive = true, TabId = dnnModule.TabID, PortalId = dnnModule.PortalID }; return(searchInfo); })); } // check if the cshtml has search customizations try { engine.CustomizeSearch(searchInfoDictionary, _serviceProvider.Build <DnnModule>().Init(dnnModule, Log), beginDate); } catch (Exception e) { Exceptions.LogException(new SearchIndexException(dnnModule, e)); } // add it to insights / history. It will only be preserved, if the inner code ran a Log.Preserve = true; History.Add("dnn-search", Log); // reduce load by only keeping recently modified items foreach (var searchInfoList in searchInfoDictionary) { // Filter by Date - take only SearchDocuments that changed since beginDate var searchDocumentsToAdd = searchInfoList.Value.Where(p => p.ModifiedTimeUtc >= beginDate.ToUniversalTime()).Select(p => (SearchDocument)p); searchDocuments.AddRange(searchDocumentsToAdd); } return(searchDocuments); }
protected IContextOfSite GetSiteContext() { return(ServiceProvider.Build <IContextOfSite>()); }
private AppRuntime AppRt(int?appId) => _serviceProvider.Build <AppRuntime>().Init(State.Identity(null, appId.Value), true, Log);
public void Publish(int instanceId, int version) { Log.Add($"Publish(m:{instanceId}, v:{version})"); try { // publish all entites of this content block var dnnModule = ModuleController.Instance.GetModule(instanceId, Null.NullInteger, true); //var container = _serviceProvider.Build<DnnContainer>().Init(dnnModule, Log); // must find tenant through module, as the Portal-Settings.Current is null in search mode //var tenant = new DnnSite().Init(dnnModule.OwnerPortalID); var dnnContext = _serviceProvider.Build <IContextOfBlock>().Init(dnnModule, Log); var cb = _serviceProvider.Build <BlockFromModule>().Init(dnnContext, Log); //.Init(DnnContextOfBlock.Create(tenant, container, _serviceProvider), Log); Log.Add($"found dnn mod {dnnContext.Module.Id}, tenant {dnnContext.Site.Id}, cb exists: {cb.ContentGroupExists}"); if (cb.ContentGroupExists) { Log.Add("cb exists"); var appManager = _serviceProvider.Build <AppManager>().Init(cb, Log); // Add content entities IEnumerable <IEntity> list = new List <IEntity>(); list = TryToAddStream(list, cb.Data, Eav.Constants.DefaultStreamName); list = TryToAddStream(list, cb.Data, "ListContent"); list = TryToAddStream(list, cb.Data, "PartOfPage"); // ReSharper disable PossibleMultipleEnumeration // Find related presentation entities var attachedPresItems = list .Where(e => (e as EntityInBlock)?.Presentation != null) .Select(e => ((EntityInBlock)e).Presentation); Log.Add($"adding presentation item⋮{attachedPresItems.Count()}"); list = list.Concat(attachedPresItems); // ReSharper restore PossibleMultipleEnumeration var ids = list.Where(e => !e.IsPublished).Select(e => e.EntityId).ToList(); // publish BlockConfiguration as well - if there already is one if (cb.Configuration != null) { Log.Add($"add group id:{cb.Configuration.Id}"); ids.Add(cb.Configuration.Id); } Log.Add(() => $"will publish id⋮{ids.Count} ids:[{ string.Join(",", ids.Select(i => i.ToString()).ToArray()) }]"); if (ids.Any()) { appManager.Entities.Publish(ids.ToArray()); } else { Log.Add("no ids found, won\'t publish items"); } } // Set published version new ModuleVersions(instanceId, Log).PublishLatestVersion(); Log.Add("publish completed"); } catch (Exception ex) { DnnLogging.LogToDnn("exception", "publishing", Log, force: true); DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); throw; } }
public override ISite SiteOfZone(int zoneId) => _serviceProvider.Build <ISite>().Init(zoneId);
/// <inheritdoc /> public TService GetService <TService>() => _serviceProvider.Build <TService>();
internal object InstantiateClass(string virtualPath, string className = null, string relativePath = null, bool throwOnError = true) { var wrapLog = Log.Call($"{virtualPath}, {nameof(className)}:{className}, {nameof(relativePath)}:{relativePath}, {throwOnError}"); string errorMsg = null; // Perform various checks on the path values var hasErrorMessage = CheckIfPathsOkAndCleanUp(ref virtualPath, relativePath); if (hasErrorMessage != null) { Log.Add($"Error: {hasErrorMessage}"); wrapLog("failed"); if (throwOnError) { throw new Exception(hasErrorMessage); } return(null); } var pathLowerCase = virtualPath.ToLowerInvariant(); var isCs = pathLowerCase.EndsWith(CsFileExtension); var isCshtml = pathLowerCase.EndsWith(CsHtmlFileExtension); Type compiledType = null; if (isCshtml && string.IsNullOrEmpty(className)) { #if NETSTANDARD throw new Exception("On-the Fly / Runtime Compile Not Yet Implemented in .net standard #TodoNetStandard"); #else compiledType = BuildManager.GetCompiledType(virtualPath); #endif if (compiledType == null) { errorMsg = $"Couldn't create instance of {virtualPath}. Compiled type == null"; } } // compile .cs files else if (isCs || isCshtml) { // if no name provided, use the name which is the same as the file name className = className ?? Path.GetFileNameWithoutExtension(virtualPath) ?? "unknown"; Assembly assembly = null; #if NETSTANDARD var fullPath = _serviceProvider.Build <IServerPaths>().FullContentPath(virtualPath.Backslash()); try { assembly = new Compiler().Compile(fullPath, className); } catch { errorMsg = $"can't compile '{className}' in {virtualPath}"; } #else assembly = BuildManager.GetCompiledAssembly(virtualPath); #endif if (errorMsg == null) { compiledType = assembly?.GetType(className, throwOnError, true); if (compiledType == null) { errorMsg = $"didn't find type '{className}' in {virtualPath}"; } } } else { errorMsg = $"Error: given path '{virtualPath}' doesn't point to a .cs or .cshtml"; } if (errorMsg != null) { Log.Add(errorMsg + $"; throw error: {throwOnError}"); wrapLog("failed"); if (throwOnError) { throw new Exception(errorMsg); } return(null); } var instance = RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType)); AttachRelativePath(virtualPath, instance); wrapLog($"found: {instance != null}"); return(instance); }