protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { List <Dictionary <string, object> > result = new List <Dictionary <string, object> >(); if (!string.IsNullOrEmpty(execContext.CurrentNode.Read.Select?.Query) && execContext.CurrentNode.Read.Select.Query.Equals("bearer", System.StringComparison.OrdinalIgnoreCase)) { if (execContext.ProcessingContext.InputModel.SecurityModel.IsAuthenticated)//Try to get bearer token only when user is logged in { string accessToken = GetAuthAccessToken(execContext); KraftGlobalConfigurationSettings kraftGlobalConfigurationSettings = execContext.PluginServiceManager.GetService <KraftGlobalConfigurationSettings>(typeof(KraftGlobalConfigurationSettings)); string authority = kraftGlobalConfigurationSettings.GeneralSettings.Authority; authority = authority.TrimEnd('/'); Dictionary <string, object> resultAuth = new Dictionary <string, object>(); resultAuth.Add("key", $"{authority}/api/avatar"); resultAuth.Add("token", accessToken); resultAuth.Add("servicename", "avatarimage"); result.Add(resultAuth); resultAuth = new Dictionary <string, object>(); resultAuth.Add("key", $"{authority}"); resultAuth.Add("token", accessToken); resultAuth.Add("servicename", "authorizationserver"); result.Add(resultAuth); resultAuth = new Dictionary <string, object>(); resultAuth.Add("key", $"{authority}/api/user"); resultAuth.Add("token", accessToken); resultAuth.Add("servicename", "user"); result.Add(resultAuth); } } return(result); }
/* * sealed public override void Execute(IDataLoaderContext execContext) * { * // TODO: Needs a bit more effort to pack exception from the called methods * if (execContext.Action == ACTION_READ) * { * ExecuteRead(execContext as IDataLoaderReadContext); * } * else if (execContext.Action == ACTION_WRITE) * { * ExecuteWrite(execContext as IDataLoaderWriteContext); * } * else * { * throw new Exception("Unknown action " + (execContext.Action ?? "null")); * } * } */ sealed protected override void ExecuteRead(IDataLoaderReadContext execContext) { var results = Read(execContext); if (results != null && results.Count > 0) { execContext.Results.AddRange(results); } }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { Node node = (Node)execContext.CurrentNode; string directoryPath = Path.Combine( execContext.ProcessingContext.InputModel.KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder(execContext.ProcessingContext.InputModel.Module), execContext.ProcessingContext.InputModel.Module, "Public"); var filename = execContext.Evaluate("rawfilename"); if (filename.Value == null) { PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); return(new List <Dictionary <string, object> >() { new Dictionary <string, object>() { { "files", Directory.GetFiles(directoryPath) } } }); } string fileName = filename.Value.ToString(); string filePath = Path.Combine(directoryPath, fileName); string cacheKey = $"{filePath}_Raw"; ICachingService cachingService = execContext.PluginServiceManager.GetService <ICachingService>(typeof(ICachingService)); string cachedRaw = cachingService.Get <string>(cacheKey); if (cachedRaw == null) { PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); try { cachedRaw = File.ReadAllText(filePath); } catch (Exception ex) { execContext.ProcessingContext.ReturnModel.Status.StatusResults.Add(new StatusResult { StatusResultType = EStatusResult.StatusResultError, Message = ex.Message }); throw; } cachingService.Insert(cacheKey, cachedRaw, fileProvider.Watch(fileName)); } return(new List <Dictionary <string, object> >() { new Dictionary <string, object>() { { "filename", fileName }, { "content", cachedRaw }, { "length", cachedRaw.Length } } }); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { Node node = (Node)execContext.CurrentNode; Dictionary <string, object> currentResult = null; JsonDataSynchronizeContextScopedImp jsonDataSynchronizeContextScopedImp = execContext.OwnContextScoped as JsonDataSynchronizeContextScopedImp; if (jsonDataSynchronizeContextScopedImp == null) { throw new NullReferenceException("The contextScoped is not JsonSyncronizeContextScopedImp"); } /* * string directoryPath = contextScoped.CustomSettings[START_FOLDER_PATH_JSON_DATA] * .Replace("@wwwroot@", processingContext.InputModel.EnvironmentSettings.WebRootPath) * .Replace("@treenodename@", loaderContext.NodeSet.Name); */ string directoryPath = Path.Combine( execContext.ProcessingContext.InputModel.KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder(execContext.ProcessingContext.InputModel.Module), execContext.ProcessingContext.InputModel.Module, "Data"); if (node?.Read?.Select?.HasFile() == true) { string filePath = Path.Combine(directoryPath, node.Read.Select.File); string cacheKey = $"{execContext.ProcessingContext.InputModel.NodeSet}{execContext.ProcessingContext.InputModel.Nodepath}{node.NodeKey}_Json"; ICachingService cachingService = execContext.PluginServiceManager.GetService <ICachingService>(typeof(ICachingService)); string cachedJson = cachingService.Get <string>(cacheKey); if (cachedJson == null) { PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); try { cachedJson = File.ReadAllText(filePath); } catch (Exception ex) { execContext.ProcessingContext.ReturnModel.Status.StatusResults.Add(new StatusResult { StatusResultType = EStatusResult.StatusResultError, Message = ex.Message }); throw; } cachingService.Insert(cacheKey, cachedJson, fileProvider.Watch(node.Read.Select.File)); } currentResult = new Dictionary <string, object>(JsonConvert.DeserializeObject <Dictionary <string, object> >(cachedJson, new DictionaryConverter())); } return(new List <Dictionary <string, object> >() { currentResult }); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { List <Dictionary <string, object> > result = new List <Dictionary <string, object> >(); CancellationToken cancellationToken = new CancellationToken(); string targetUrl = GetAuthUrl(execContext, "select"); AuthenticationHeaderValue authenticationHeaderValue = new AuthenticationHeaderValue("Bearer", GetAuthAccessToken(execContext)); Task <Dictionary <string, object> > resultAuth = Loader.LoadAsync <Dictionary <string, object> >(cancellationToken, authenticationHeaderValue, HttpMethod.Get, null, targetUrl); resultAuth.ConfigureAwait(false); result.Add(resultAuth.Result); return(result); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { List <Dictionary <string, object> > returnResult = null; Configuration cfg = ReadConfiguration(execContext); if (!string.IsNullOrEmpty(cfg.Statement)) { returnResult = new List <Dictionary <string, object> >() { ProcessStatement(cfg.Statement, execContext) }; } return(returnResult); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { /* Expected parameters coming from the NodeSet * JSON: * { * Headers: * { * Key: Value, * Authorization: Bearer %@AuthToken@% * }, * Body: * { * File: "", * Inline: * { * } * }, * Url: * { * Url: "http://gitccf.cleancode.factory:82/Cleancodefactory/Board/src/branch?key=%@AuthToken@%&key1=value1" * Verb: "GET|POST" * } * } */ //string baseUrl = execContext.DataLoaderContextScoped.CustomSettings["BaseUrl"]; //ParameterResolverValue endpoint = execContext.Evaluate("endpoint"); //ParameterResolverValue method = execContext.Evaluate("method"); List <Dictionary <string, object> > result = new List <Dictionary <string, object> >(); //if (!(endpoint.Value is string)) //{ // KraftLogger.LogError("HttpServiceImp endpoint parameter value must be string"); // throw new Exception("endpoint value must be string"); //} //string url = baseUrl + endpoint.Value; string test = "delete later"; result.Add(new Dictionary <string, object>() { { "key", test } }); return(result); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { string baseUrl = execContext.DataLoaderContextScoped.CustomSettings["BaseUrl"]; ParameterResolverValue endpoint = execContext.Evaluate("endpoint"); ParameterResolverValue method = execContext.Evaluate("method"); var result = new List <Dictionary <string, object> >(); if (!(endpoint.Value is string)) { KraftLogger.LogError("HttpServiceImp endpoint parameter value must be string"); throw new Exception("endpoint value must be string"); } string url = baseUrl + endpoint.Value; var obj = this.GetHttpContent(url); result.Add(new Dictionary <string, object>() { { "key", obj } }); return(result); }
/// <summary> /// Reads uploaded file in predefined directory, /// sets the response builder of the return model of the processing context to BinaryResponseBuilder. /// </summary> /// <param name="execContext">Execution context</param> /// <returns>null</returns> protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { ReadCustomSettings settings = new ReadCustomSettings(execContext, execContext.PluginServiceManager.GetService <KraftGlobalConfigurationSettings>(typeof(KraftGlobalConfigurationSettings))); string filePreviewName = "FILE_preview.svg"; string previewName = "preview"; string file = execContext.Evaluate("path").Value.ToString(); string configuredDir = settings.UploadFolder; string defaultDir = settings.DefaultFolder; if (File.Exists(Path.Combine(configuredDir, file))) { ParameterResolverValue preview = execContext.Evaluate(previewName); if (preview.Value != null) { string previewValue = preview.Value.ToString(); if (previewValue == "1") { string previewFileName = GeneratePreviewName(file); if (File.Exists(Path.Combine(configuredDir, previewFileName))) { file = previewFileName; } else { string extension = Path.GetExtension(file); if (!string.IsNullOrWhiteSpace(extension)) { previewFileName = extension.Replace(".", string.Empty).ToUpper() + "_preview.svg"; if (File.Exists(Path.Combine(defaultDir, previewFileName))) { file = previewFileName; configuredDir = defaultDir; } else { file = filePreviewName; configuredDir = defaultDir; } } else { file = filePreviewName; configuredDir = defaultDir; } } } } } else { if (File.Exists(Path.Combine(defaultDir, settings.FileNotFoundIcon))) { configuredDir = defaultDir; file = settings.FileNotFoundIcon; } else { KraftLogger.LogError($"FileUploadImp-Read: File with name {file} was not found."); } } file = Path.Combine(configuredDir, file); string contentType; new FileExtensionContentTypeProvider().TryGetContentType(file, out contentType); execContext.ProcessingContext.ReturnModel.BinaryData = new PostedFile(contentType, 0, "currentlyNotSet", file, path => { return(File.Open(path as string, FileMode.Open)); }, file); execContext.ProcessingContext.ReturnModel.ResponseBuilder = new BinaryResponseBuilder(new ProcessingContextCollection(new List <IProcessingContext> { execContext.ProcessingContext })); return(null); }
protected abstract void ExecuteRead(IDataLoaderReadContext execContext);
/// <summary> /// Calls and executes plugin in read operation. /// </summary> /// <param name="execContext">Data loader context.</param> /// <returns>Called plugin result.</returns> protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { Dictionary <string, object> parameters = ParseAdditionalParameters(execContext.CurrentNode.Read); return(ExecuteOperation(execContext, parameters, false)); }
/* Considerations: * We have to read the configuration in a single turn and consume it from the internal configuration container * in order to avoid direct hard coded dependency on the system configuration structure - most notably dependency on its * structure and interpreatation. * Solution: * We have a nested class in which the configuration values used by this loader are collected (sometimes with some preprocessing) * Lifecycle: * The configuration (part of it at least) has a lifecycle equal to the node execution which is shorter than the life of the dataloader (at least potentially), * so the configuration has to be reread on each node executio and thus is not persisted in the loader's instance, but passed to the main overridable methods. * */ //protected class Configuration { // public string Statement { get; set; } //} /// <summary> /// /// </summary> /// <param name="execContext"></param> /// <returns></returns> //protected virtual Configuration ReadConfiguration(IDataLoaderContext execContext) { // var cfg = new Configuration(); // if (execContext.Action == ACTION_READ) { // cfg.Statement = execContext.CurrentNode.Read.Select.HasStatement?execContext.CurrentNode.Read.Select.Query:null; // } else if (execContext.Action == ACTION_WRITE) { // switch (execContext.Operation) { // case OPERATION_INSERT: // if (execContext.CurrentNode.Write.Insert.HasStatement) { // cfg.Statement = execContext.CurrentNode.Write.Insert.Query; // } // break; // case OPERATION_UPDATE: // if (execContext.CurrentNode.Write.Update.HasStatement) { // cfg.Statement = execContext.CurrentNode.Write.Update.Query; // } // break; // case OPERATION_DELETE: // if (execContext.CurrentNode.Write.Delete.HasStatement) { // cfg.Statement = execContext.CurrentNode.Write.Delete.Query; // } // break; // } // } // return cfg; /////////////////////////////// //} #endregion //public async Task<object> ExecuteAsync(IDataLoaderContext execContext) { // // The procedure is different enough to deserve splitting by read/write // Configuration cfg = ReadConfiguration(execContext); // object result; // if (execContext.Action == ACTION_WRITE) { // result = ExecuteWrite(execContext, cfg); // } else if (execContext.Action == ACTION_READ) { // result = ExecuteRead(execContext, cfg); // } else { // // unknown action // throw new Exception("Unknown action (only read/write) are supported"); // } // return await Task.FromResult(result); //} protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { // TODO: What to return if there is no statement: // I think we should have two policies - empty object which enables children extraction if logically possible and // null wich stops the processing here. List <Dictionary <string, object> > results = new List <Dictionary <string, object> >(); string sqlQuery = null; try { Node node = execContext.CurrentNode; if (!string.IsNullOrWhiteSpace(Action(execContext).Query)) { // Scope context for the same loader // Check it is valid if (!(execContext.OwnContextScoped is IADOTransactionScope scopedContext)) { throw new NullReferenceException("Scoped synchronization and transaction context is not available."); } // Configuration settings Should be set to the scoped context during its creation/obtainment - see ExternalServiceImp // No tranaction in read mode - lets not forget that closing the transaction also closes the connection - so the ;ifecycle control will do this using the transaction based notation // from ITransactionScope DbConnection conn = scopedContext.Connection; using (DbCommand cmd = conn.CreateCommand()) { cmd.Transaction = scopedContext.CurrentTransaction; // if we decide to open transaction in future this will guarantee we only have to open it and will take effect throughout the code. cmd.Parameters.Clear(); // This will set the resulting command text if everything is Ok. // The processing will make replacements in the SQL and bind parameters by requesting them from the resolver expressions configured on this node. // TODO: Some try...catching is necessary. sqlQuery = ProcessCommand(cmd, Action(execContext).Query, execContext); using (DbDataReader reader = cmd.ExecuteReader()) { do { if (reader.HasRows) { // Read a result (many may be contained) row by row while (reader.Read()) { Dictionary <string, object> currentResult = new Dictionary <string, object>(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) { string fldname = reader.GetName(i); if (fldname == null) { continue; } // TODO: May be configure that or at least create a compile time definition fldname = fldname.ToLower().Trim(); // TODO: lowercase //fldname = fldname.Trim(); if (fldname.Length == 0) { throw new Exception($"Empty name when reading the output of a query. The field index is {i}. The query is: {cmd.CommandText}"); } if (currentResult.ContainsKey(fldname)) { throw new Exception($"Duplicated field name in the output of a query. The field is:{fldname}, the query is: {cmd.CommandText}"); } object v = reader.GetValue(i); currentResult.Add(fldname, (v is DBNull) ? null : v); } // Mark the records unchanged, because they are just picked up from the data store (rdbms in this case). execContext.DataState.SetUnchanged(currentResult); results.Add(currentResult); if (!node.IsList) { break; } } } } while (reader.NextResult()); } } } } catch (Exception ex) { if (!string.IsNullOrEmpty(sqlQuery)) { KraftLogger.LogError($"Read(IDataLoaderReadContext execContext) >> SQL: {Environment.NewLine}{sqlQuery}", ex, execContext); } throw; } return(results); // TODO: Decide what behavior we want with empty statements. I for one prefer null result, effectively stopping the operation. }
protected abstract List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext);
protected override void ExecuteRead(IDataLoaderReadContext execContext) { ExecuteQuery(execContext); }
protected override void ExecuteRead(IDataLoaderReadContext execContext) { bool trace = execContext.CurrentNode.Trace; string qry = GetQuery(execContext); if (qry != null) { try { var runner = Compiler.Compile(qry); if (runner.ErrorText != null) { KraftLogger.LogError($"{execContext.LocationInfo(PLUGIN_INTERNAL_NAME)}\n{runner.ErrorText}"); throw new Exception(runner.ErrorText); } using (var host = new ActionQueryHost <IDataLoaderReadContext>(execContext) { { nameof(IsPostedFile), IsPostedFile }, { nameof(PostedFileSize), PostedFileSize }, { nameof(PostedFileName), PostedFileName }, { nameof(PostedFileType), PostedFileType }, { nameof(CombinePaths), CombinePaths }, { nameof(DeleteFile), DeleteFile }, { nameof(SaveFile), SaveFile }, { nameof(PrependFileName), PrependFileName }, { nameof(CreateDirectory), CreateDirectory }, { nameof(SaveFileToSpread), SaveFileToSpread }, { nameof(PostedFile), this.PostedFile }, { nameof(FileResponse), FileResponse }, { nameof(FileExists), FileExists } }) { host.AddLibrary(new BasicImageLib <IDataLoaderReadContext>()); if (trace) { host.Trace = true; } try { var result = runner.ExecuteScalar(host, ActionQueryHost <IDataLoaderReadContext> .HardLimit(execContext)); } catch { if (trace) { var traceInfo = host.GetTraceInfo(); if (traceInfo != null) { KraftLogger.LogError($"{execContext.LocationInfo(PLUGIN_INTERNAL_NAME)}\n"); KraftLogger.LogError(traceInfo.ToString()); } KraftLogger.LogError($"{runner.DumpProgram()}\n"); } throw; } } } catch (Exception ex) { KraftLogger.LogError(ActionQueryTrace.ExceptionToString(ex)); throw; } } // Else nothing to do. }