public ActionResult Load(int id) {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            ConfigurationPart part;
            ApiRequest request;

            foreach (var rejection in _apiService.Rejections(id, out request, out part)) {
                return rejection.ContentResult(_query["format"], _query["flavor"]);
            }

            request.RequestType = ApiRequestType.Execute;
            var root = new TflRoot(part.Configuration, _query);
            
            TransformConfigurationForLoad(root);

            var errors = root.Errors();
            if (errors.Any()) {
                request.Status = 500;
                request.Message = string.Join(Environment.NewLine, errors);
                return new ApiResponse(request, root.ToString(), new TransformalizeResponse()).ContentResult(_query["format"], _query["flavor"]);
            }

            var transformalizeRequest = new TransformalizeRequest(part, _query, null, Logger, root);

            return Run(request, transformalizeRequest)
                .ContentResult(_query["format"], _query["flavor"]);
        }
        public ActionResult MetaData(int id) {

            Response.AddHeader("Access-Control-Allow-Origin", "*");
            ConfigurationPart part;
            ApiRequest request;

            var query = _transformalize.GetQuery();

            foreach (var rejection in _apiService.Rejections(id, out request, out part)) {
                return rejection.ContentResult(
                    query["format"],
                    query["flavor"]
                );
            }

            request.RequestType = ApiRequestType.MetaData;
            var transformalizeRequest = new TransformalizeRequest(part, query, null, Logger);
            var logger = new TransformalizeLogger(transformalizeRequest.Part.Title(), part.LogLevel, Logger, OrchardVersion, _moduleVersion);

            var errors = transformalizeRequest.Root.Errors();
            if (errors.Any()) {
                var bad = new TransformalizeResponse();
                request.Status = 501;
                request.Message = "Configuration Problem" + errors.Length.Plural();
                bad.Log.AddRange(errors.Select(p => new[] { DateTime.Now.ToString(CultureInfo.InvariantCulture), "error", ".", ".", p }));
                return new ApiResponse(request, "<tfl></tfl>", bad).ContentResult(
                    query["format"],
                    query["flavor"]
                );
            }

            var metaData = new MetaDataWriter(ProcessFactory.CreateSingle(transformalizeRequest.Root.Processes[0], logger, new Options { Mode = "metadata" })).Write();
            return new ApiResponse(request, metaData).ContentResult(
                query["format"],
                query["flavor"]
            );
        }
        public TransformalizeResponse Run(TransformalizeRequest request) {

            var moduleVersion = _extensionManager.GetExtension("Transformalize.Orchard").Version;
            var logger = new TransformalizeLogger(request.Part.Title(), request.Part.LogLevel, Logger, OrchardVersion, moduleVersion);
            var processes = new List<Process>();

            //transitioning to using TflRoot instead of string configuration
            if (request.Root != null) {
                processes.AddRange(ProcessFactory.Create(request.Root, logger, request.Options));
            } else {  //legacy
                processes.AddRange(ProcessFactory.Create(request.Configuration, logger, request.Options, request.Query));
            }

            for (var i = 0; i < processes.Count; i++) {
                var process = processes[i];
                CreateInputOperation(process, request);
                process.ExecuteScaler();
            }

            return new TransformalizeResponse() {
                Processes = processes.ToArray(),
                Log = logger.Dump().ToList()
            };
        }
        protected ApiResponse Run(
            ApiRequest request,
            TransformalizeRequest transformalizeRequest
        ) {

            var errorNumber = 500;
            try {
                errorNumber++;
                var tflResponse = _transformalize.Run(transformalizeRequest);

                errorNumber++;
                return new ApiResponse(
                    request,
                    transformalizeRequest.Configuration,
                    tflResponse
                );
            } catch (Exception ex) {
                request.Status = errorNumber;
                request.Message = ex.Message;
                return new ApiResponse(
                    request,
                    transformalizeRequest.Configuration,
                    new TransformalizeResponse()
                );
            }
        }
        public ActionResult Save(int id) {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            ConfigurationPart part;
            ApiRequest request;

            foreach (var rejection in _apiService.Rejections(id, out request, out part)) {
                return rejection.ContentResult(_query["format"], _query["flavor"]);
            }

            request.RequestType = ApiRequestType.Execute;
            _query.Add("data", Request.Form["data"]);
            var transformalizeRequest = new TransformalizeRequest(part, _query, null, Logger);

            return Run(request, transformalizeRequest).ContentResult(_query["format"], _query["flavor"]);
        }
        private ExecuteViewModel Run(TransformalizeRequest request) {

            var model = new ExecuteViewModel { DisplayLog = request.Part.DisplayLog };

            if (request.Part.TryCatch) {
                try {
                    model.TransformalizeResponse = _transformalize.Run(request);
                } catch (Exception ex) {
                    model.DisplayLog = true;
                    model.TransformalizeResponse.Log.Add(new[]{DateTime.Now.ToString(), "error","orchard", ".", ex.Message});
                    model.TransformalizeResponse.Log.Add(new[] { DateTime.Now.ToString(), "debug", "orchard", ".", ex.StackTrace });
                    Logger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                }
            } else {
                model.TransformalizeResponse = _transformalize.Run(request);
            }

            return model;
        }
        public ActionResult Execute(int id) {

            Response.AddHeader("Access-Control-Allow-Origin", "*");
            ConfigurationPart part;
            ApiRequest request;

            var query = _transformalize.GetQuery();

            foreach (var rejection in _apiService.Rejections(id, out request, out part)) {
                return rejection.ContentResult(
                    query["format"],
                    query["flavor"]
                );
            }

            request.RequestType = ApiRequestType.Execute;
            _transformalize.InitializeFiles(part, query);

            // ready
            var processes = new TransformalizeResponse();
            var transformalizeRequest = new TransformalizeRequest(part, query, null, Logger);

            try {
                processes = _transformalize.Run(transformalizeRequest);
            } catch (Exception ex) {
                request.Status = 500;
                request.Message = ex.Message + " " + WebUtility.HtmlEncode(ex.StackTrace);
            }

            return new ApiResponse(request, transformalizeRequest.Configuration, processes).ContentResult(
                transformalizeRequest.Query["format"].ToString(),
                transformalizeRequest.Query["flavor"].ToString()
            );
        }
        private static void CreateInputOperation(Process process, TransformalizeRequest request) {

            if (!request.Query.ContainsKey("data")) {
                return;
            }

            if (!process.Connections.Contains("input"))
                return;
            if (process.Connections.GetConnectionByName("input").Connection.Type != ProviderType.Internal)
                return;

            var rows = new List<Row>();
            var sr = new StringReader(request.Query["data"].ToString());
            var reader = new JsonTextReader(sr);
            reader.Read();
            if (reader.TokenType != JsonToken.StartArray)
                throw new JsonException("The data passed into this process must be an array of arrays that contain input data matching the configured fields.  E.g. [['Dale','Newman', 34],['Gavin','Newman', 3]]");

            var entity = process.Entities.First();
            var inputFields = entity.InputFields();
            var conversion = Common.GetObjectConversionMap();

            // Note: Input 
            while (reader.Read()) {
                if (reader.TokenType == JsonToken.StartArray) {
                    var row = new Row();
                    foreach (var field in inputFields) {
                        reader.Read();
                        row[field.Name] = conversion[field.SimpleType](reader.Value);
                    }
                    rows.Add(row);
                } else if (reader.TokenType == JsonToken.StartObject) {
                    var row = new Row();
                    do {
                        reader.Read();
                        if (reader.TokenType == JsonToken.PropertyName) {
                            var name = reader.Value.ToString();
                            reader.Read();
                            row[name] = reader.Value;
                        }
                    } while (reader.TokenType != JsonToken.EndObject);

                    foreach (var field in inputFields) {
                        row[field.Name] = conversion[field.SimpleType](row[field.Name]);
                    }
                    rows.Add(row);
                }
            }

            entity.InputOperation = new RowsOperation(rows);
        }
        public void Run(string args) {

            var split = args.Split(',');
            var id = Convert.ToInt32(split[0]);
            var mode = split[1];

            var part = GetConfiguration(id);
            var request = new TransformalizeRequest(part, GetQuery(), null, Logger) { Options = new Options() { Mode = mode } };

            if (request.Root.Errors().Any()) {
                foreach (var error in request.Root.Errors()) {
                    Logger.Error(error);
                }
            } else {
                var response = Run(request);

                if (!response.Log.Any())
                    return;

                var name = TransformalizeTaskHandler.GetName(part.Title());
                var reportId = _reportsManager.CreateReport(mode.Left(1).ToUpper() + mode.Substring(1), name);
                var report = _reportsManager.Get(reportId);

                var status = string.Empty;
                foreach (var log in response.Log) {
                    var level = log[1].Left(4);
                    var utc = Convert.ToDateTime(log[0]).ToUniversalTime();
                    var data = log.Skip(3);
                    switch (level) {
                        case "erro":
                            report.Entries.Add(new ReportEntry { Message = string.Join(" | ", data), Type = ReportEntryType.Error, Utc = utc });
                            status = "with Error(s)";
                            break;
                        case "warn":
                            report.Entries.Add(new ReportEntry { Message = string.Join(" | ", data), Type = ReportEntryType.Warning, Utc = utc });
                            if (status != "with Error(s)") {
                                status = "with Warning(s)";
                            }
                            break;
                        default:
                            report.Entries.Add(new ReportEntry { Message = string.Join(" | ", data), Type = ReportEntryType.Information, Utc = utc });
                            break;
                    }
                }
                report.ActivityName += " " + status;
                _reportsManager.Flush();
            }
        }