Internal Service Request Object - Used mainly by the studio, but server can send request if service is web based
 protected EsbExecutionContainer(ServiceAction sa, IDSFDataObject dataObject, IWorkspace theWorkspace, IEsbChannel esbChannel, EsbExecuteRequest request)
 {
     ServiceAction = sa;
     DataObject = dataObject;
     TheWorkspace = theWorkspace;
     EsbChannel = esbChannel;
     Request = request;
     DataObject.EsbChannel = EsbChannel;
 }
        public void InternalServiceRequestHandler_ProcessRequest_WhenNullExecutingUser_ExpectException()
        {
            //------------Setup for test--------------------------
            EsbExecuteRequest eer = new EsbExecuteRequest { ServiceName = "Ping" };

            var internalServiceRequestHandler = new InternalServiceRequestHandler { ExecutingUser = null };

            //------------Execute Test---------------------------
            internalServiceRequestHandler.ProcessRequest(eer, Guid.Empty, Guid.Empty, Guid.NewGuid().ToString());

        }
        public void InternalServiceRequestHandler_ProcessRequest_WhenMalformedConnectionId_ExpectException()
        {
            //------------Setup for test--------------------------
            Mock<IPrincipal> principle = new Mock<IPrincipal>();
            principle.Setup(p => p.Identity.Name).Returns("FakeUser");
            EsbExecuteRequest eer = new EsbExecuteRequest { ServiceName = "Ping" };

            var internalServiceRequestHandler = new InternalServiceRequestHandler { ExecutingUser = principle.Object };

            //------------Execute Test---------------------------
            internalServiceRequestHandler.ProcessRequest(eer, Guid.Empty, Guid.Empty, "1");

        }
Ejemplo n.º 4
0
        public EsbServiceInvoker(IEsbChannel esbChannel,
                                      IFrameworkDuplexDataChannel managementChannel,
                                      IWorkspace workspace, EsbExecuteRequest request)
        {
            _esbChannel = esbChannel;
            if(managementChannel != null)
            {
            }

            // 2012.10.17 - 5782: TWR - Added workspace parameter
            _workspace = workspace;

            _request = request;
        }
 public void ClientScheduledResourceModel_DeleteScheduledResource_CallsCommunicationsController()
 {
     //------------Setup for test--------------------------
     var scheduledResourceForTest = new ScheduledResourceForTest();
     Dev2JsonSerializer serializer = new Dev2JsonSerializer();
     var serializeObject = serializer.SerializeToBuilder(scheduledResourceForTest);
     var esbPayLoad = new EsbExecuteRequest { ServiceName = "DeleteScheduledResourceService" };
     esbPayLoad.AddArgument("Resource", serializeObject);
     var mockEnvironmentModel = new Mock<IEnvironmentModel>();
     var mockConnection = new Mock<IEnvironmentConnection>();
     mockConnection.Setup(connection => connection.IsConnected).Returns(true);
     mockConnection.Setup(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>(), It.IsAny<Guid>())).Verifiable();
     mockConnection.Setup(connection => connection.WorkspaceID).Returns(Guid.NewGuid());
     mockEnvironmentModel.Setup(model => model.Connection).Returns(mockConnection.Object);
     var clientScheduledResourceModel = new ClientScheduledResourceModel(mockEnvironmentModel.Object);
     //------------Execute Test---------------------------
     clientScheduledResourceModel.DeleteSchedule(scheduledResourceForTest);
     //------------Assert Results-------------------------
     mockConnection.Verify(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>(), It.IsAny<Guid>()), Times.Once());
 }
 public InternalServiceContainer(ServiceAction sa, IDSFDataObject dataObj, IWorkspace theWorkspace, IEsbChannel esbChannel, EsbExecuteRequest request)
     : base(sa, dataObj, theWorkspace, esbChannel, request)
 {
     var dataListTO = new DataListTO(sa.DataListSpecification.ToString());
     if(request.Args == null)
     {
         request.Args = new Dictionary<string, StringBuilder>();
         foreach(var input in dataListTO.Inputs)
         {
             var warewolfEvalResult = dataObj.Environment.Eval(DataListUtil.AddBracketsToValueIfNotExist(input),0,false);
             if(warewolfEvalResult.IsWarewolfAtomResult)
             {
                 var scalarResult = warewolfEvalResult as WarewolfDataEvaluationCommon.WarewolfEvalResult.WarewolfAtomResult;
                 if(scalarResult != null && !scalarResult.Item.IsNothing)
                 {
                     request.Args.Add(input, new StringBuilder(scalarResult.Item.ToString()));
                 }
             }
         }
     }
 }
        public void JsonSerializer_SerializeToBuffer_WhenEsbExecuteRequest_ValidObjectStringBuffer()
        {
            //------------Setup for test--------------------------
            Dev2JsonSerializer js = new Dev2JsonSerializer();
            EsbExecuteRequest request = new EsbExecuteRequest { ServiceName = "Foobar" };
            request.AddArgument("key1", new StringBuilder("value1"));
            request.AddArgument("key2", new StringBuilder("value2"));

            //------------Execute Test---------------------------
            var result = js.SerializeToBuilder(request);

            //------------Assert Results-------------------------
            Assert.AreEqual(679, result.Length);
            var resultObj = js.Deserialize<EsbExecuteRequest>(result);

            // check service name hydration
            Assert.AreEqual(request.ServiceName, resultObj.ServiceName);

            // ensure args hydrate ;)
            Assert.AreEqual(request.Args["key1"].ToString(), resultObj.Args["key1"].ToString());
            Assert.AreEqual(request.Args["key2"].ToString(), resultObj.Args["key2"].ToString());
        }
 public void ClientScheduledResourceModel_SaveScheduledResource_HasError_CallsCommunicationsController()
 {
     //------------Setup for test--------------------------
     var scheduledResourceForTest = new ScheduledResourceForTest();
     Dev2JsonSerializer serializer = new Dev2JsonSerializer();
     var serializeObject = serializer.SerializeToBuilder(scheduledResourceForTest);
     var esbPayLoad = new EsbExecuteRequest { ServiceName = "AddScheduledResourceService" };
     esbPayLoad.AddArgument("Resource", serializeObject);
     var returnMessage = new ExecuteMessage { HasError = true, Message = new StringBuilder("Error occurred") };
     var serializedReturnMessage = serializer.SerializeToBuilder(returnMessage);
     var mockEnvironmentModel = new Mock<IEnvironmentModel>();
     var mockConnection = new Mock<IEnvironmentConnection>();
     mockConnection.Setup(connection => connection.IsConnected).Returns(true);
     mockConnection.Setup(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>())).Verifiable();
     mockConnection.Setup(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>())).Returns(serializedReturnMessage);
     mockConnection.Setup(connection => connection.WorkspaceID).Returns(Guid.NewGuid());
     mockEnvironmentModel.Setup(model => model.Connection).Returns(mockConnection.Object);
     var clientScheduledResourceModel = new ClientScheduledResourceModel(mockEnvironmentModel.Object);
     //------------Execute Test---------------------------
     string errorMessage;
     var saved = clientScheduledResourceModel.Save(scheduledResourceForTest, out errorMessage);
     //------------Assert Results-------------------------
     mockConnection.Verify(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>()), Times.Once());
     Assert.IsFalse(saved);
     Assert.AreEqual("Error occurred", errorMessage);
 }
        public StringBuilder ProcessRequest(EsbExecuteRequest request, Guid workspaceID, Guid dataListID, string connectionId)
        {
            var channel = new EsbServicesEndpoint();
            var xmlData = string.Empty;
            if(request.Args != null && request.Args.ContainsKey("DebugPayload"))
            {
                xmlData = request.Args["DebugPayload"].ToString();
                xmlData = xmlData.Replace("<DataList>", "<XmlData>").Replace("</DataList>", "</XmlData>");
            }

            // we need to adjust for the silly xml structure this system was init built on ;(
            if(string.IsNullOrEmpty(xmlData))
            {
                xmlData = "<DataList></DataList>";
            }

            IDSFDataObject dataObject = new DsfDataObject(xmlData, dataListID);
            dataObject.StartTime = DateTime.Now;
            dataObject.EsbChannel = channel;
            dataObject.ServiceName = request.ServiceName;
           
            var resource = ResourceCatalog.Instance.GetResource(workspaceID, request.ServiceName);
            if(resource != null)
            {
                dataObject.ResourceID = resource.ResourceID;
            }
            dataObject.ClientID = Guid.Parse(connectionId);
            dataObject.ExecutingUser = ExecutingUser;
            // we need to assign new ThreadID to request coming from here, because it is a fixed connection and will not change ID on its own ;)
            if(!dataObject.Environment.HasErrors())
            {
                ErrorResultTO errors;

                if(ExecutingUser == null)
                {
                    throw new Exception("Null Executing User");
                }

                try
                {
                    // Execute in its own thread to give proper context ;)
                    var t = new Thread(() =>
                    {
                        Thread.CurrentPrincipal = ExecutingUser;
                        channel.ExecuteRequest(dataObject, request, workspaceID, out errors);
                    });

                    t.Start();

                    t.Join();
                }
                catch(Exception e)
                {
                    Dev2Logger.Log.Error(e.Message,e);
                }



                if(request.ExecuteResult.Length > 0)
                {
                    return request.ExecuteResult;
                }

                return new StringBuilder();
            }

            ExecuteMessage msg = new ExecuteMessage { HasError = true };
            msg.SetMessage(String.Join(Environment.NewLine, dataObject.Environment.Errors));

            Dev2JsonSerializer serializer = new Dev2JsonSerializer();
            return serializer.SerializeToBuilder(msg);
        }
        protected static IResponseWriter CreateForm(WebRequestTO webRequest, string serviceName, string workspaceId, NameValueCollection headers, List<DataListFormat> publicFormats, IPrincipal user = null)
        {
            //lock(ExecutionObject)
            {
                string executePayload = "";
                IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();
                Guid workspaceGuid;

                if(workspaceId != null)
                {
                    if(!Guid.TryParse(workspaceId, out workspaceGuid))
                    {
                        workspaceGuid = WorkspaceRepository.Instance.ServerWorkspace.ID;
                    }
                }
                else
                {
                    workspaceGuid = WorkspaceRepository.Instance.ServerWorkspace.ID;
                }

                var allErrors = new ErrorResultTO();
                var dataObject = new DsfDataObject(webRequest.RawRequestPayload, GlobalConstants.NullDataListID, webRequest.RawRequestPayload) { IsFromWebServer = true, ExecutingUser = user, ServiceName = serviceName, WorkspaceID = workspaceGuid };

                // now bind any variables that are part of the path arguments ;)
                BindRequestVariablesToDataObject(webRequest, ref dataObject);

                // now process headers ;)
                if(headers != null)
                {
                    Dev2Logger.Log.Debug("Remote Invoke");

                    var isRemote = headers.Get(HttpRequestHeader.Cookie.ToString());
                    var remoteId = headers.Get(HttpRequestHeader.From.ToString());

                    if(isRemote != null && remoteId != null)
                    {
                        if(isRemote.Equals(GlobalConstants.RemoteServerInvoke))
                        {
                            // we have a remote invoke ;)
                            dataObject.RemoteInvoke = true;
                        }

                        dataObject.RemoteInvokerID = remoteId;
                    }
                }

                // now set the emition type ;)
                int loc;
                if(!String.IsNullOrEmpty(serviceName) && (loc = serviceName.LastIndexOf(".", StringComparison.Ordinal)) > 0)
                {
                    // default it to xml
                    dataObject.ReturnType = EmitionTypes.XML;

                    if(loc > 0)
                    {
                        var typeOf = serviceName.Substring((loc + 1)).ToUpper();
                        EmitionTypes myType;
                        if(Enum.TryParse(typeOf, out myType))
                        {
                            dataObject.ReturnType = myType;
                        }

                        // adjust the service name to drop the type ;)

                        // avoid .wiz amendments ;)
                        if(!typeOf.ToLower().Equals(GlobalConstants.WizardExt))
                        {
                            serviceName = serviceName.Substring(0, loc);
                            dataObject.ServiceName = serviceName;
                        }

                    }
                }
                else
                {
                    // default it to xml
                    dataObject.ReturnType = EmitionTypes.XML;
                }

                // ensure service gets set ;)
                if(dataObject.ServiceName == null)
                {
                    dataObject.ServiceName = serviceName;
                }
                IResource resource = null;
                if(!String.IsNullOrEmpty(dataObject.ServiceName))
                {
                    resource = ResourceCatalog.Instance.GetResource(dataObject.WorkspaceID, dataObject.ServiceName);
                    if(resource != null)
                    {
                        dataObject.ResourceID = resource.ResourceID;

                    }
                }
                var esbEndpoint = new EsbServicesEndpoint();
                dataObject.EsbChannel = esbEndpoint;
                var canExecute = true;
                if(ServerAuthorizationService.Instance != null)
                {
                    var authorizationService = ServerAuthorizationService.Instance;
                    var hasView = authorizationService.IsAuthorized(AuthorizationContext.View, dataObject.ResourceID.ToString());
                    var hasExecute = authorizationService.IsAuthorized(AuthorizationContext.Execute, dataObject.ResourceID.ToString());
                    canExecute = (hasExecute && hasView) || (dataObject.RemoteInvoke && hasExecute) || (resource != null && resource.ResourceType == ResourceType.ReservedService);
                }
                // Build EsbExecutionRequest - Internal Services Require This ;)
                EsbExecuteRequest esbExecuteRequest = new EsbExecuteRequest { ServiceName = serviceName };

                Dev2Logger.Log.Debug("About to execute web request [ " + serviceName + " ] DataObject Payload [ " + dataObject.RawPayload + " ]");
                var executionDlid = GlobalConstants.NullDataListID;
                if(canExecute)
                {
                    ErrorResultTO errors;
                    executionDlid = esbEndpoint.ExecuteRequest(dataObject, esbExecuteRequest, workspaceGuid, out errors);
                    allErrors.MergeErrors(errors);
                }
                else
                {
                    allErrors.AddError("Executing a service externally requires View and Execute permissions");
                }
                foreach(var error in dataObject.Environment.Errors)
                {
                    allErrors.AddError(error,true);
                }
                // Fetch return type ;)
                var formatter = publicFormats.FirstOrDefault(c => c.PublicFormatName == dataObject.ReturnType)
                                ?? publicFormats.FirstOrDefault(c => c.PublicFormatName == EmitionTypes.XML);

                // force it to XML if need be ;)

                // Fetch and convert DL ;)
                if(executionDlid != GlobalConstants.NullDataListID && !dataObject.Environment.HasErrors())
                {
                    // a normal service request
                    if(!esbExecuteRequest.WasInternalService)
                    {
                        dataObject.DataListID = executionDlid;
                        dataObject.WorkspaceID = workspaceGuid;
                        dataObject.ServiceName = serviceName;


                        // some silly chicken thinks web request where a good idea for debug ;(
                        if(!dataObject.IsDebug || dataObject.RemoteInvoke)
                        {
                            if (dataObject.ReturnType == EmitionTypes.JSON)
                            {
                                executePayload = ExecutionEnvironmentUtils.GetJsonOutputFromEnvironment(dataObject, workspaceGuid,resource.DataList.ToString());
                            }
                            else if (dataObject.ReturnType == EmitionTypes.XML)
                            {
                                executePayload = ExecutionEnvironmentUtils.GetXmlOutputFromEnvironment(dataObject, workspaceGuid,resource.DataList.ToString());
                            }
                            dataObject.Environment.AddError(allErrors.MakeDataListReady());
                        }
                        else
                        {
                            executePayload = string.Empty;
                        }

                    }
                    else
                    {
                        // internal service request we need to return data for it from the request object ;)
                        var serializer = new Dev2JsonSerializer();
                        executePayload = string.Empty;
                        var msg = serializer.Deserialize<ExecuteMessage>(esbExecuteRequest.ExecuteResult);

                        if(msg != null)
                        {
                            executePayload = msg.Message.ToString();
                        }

                        // out fail safe to return different types of data from services ;)
                        if(string.IsNullOrEmpty(executePayload))
                        {
                            executePayload = esbExecuteRequest.ExecuteResult.ToString();
                        }
                    }
                }
                else
                {
                    if(dataObject.ReturnType == EmitionTypes.XML)
                    {

                        executePayload =
                            "<FatalError> <Message> An internal error occurred while executing the service request </Message>";
                        executePayload += allErrors.MakeDataListReady();
                        executePayload += "</FatalError>";
                    }
                    else
                    {
                        // convert output to JSON ;)
                        executePayload =
                            "{ \"FatalError\": \"An internal error occurred while executing the service request\",";
                        executePayload += allErrors.MakeDataListReady(false);
                        executePayload += "}";
                    }
                }


                Dev2Logger.Log.Debug("Execution Result [ " + executePayload + " ]");

                // Clean up the datalist from the server
                if(!dataObject.WorkflowResumeable && executionDlid != GlobalConstants.NullDataListID)
                {
                    compiler.ForceDeleteDataListByID(executionDlid);
                    if(dataObject.IsDebug && !dataObject.IsRemoteInvoke && !dataObject.RunWorkflowAsync)
                    {
                        DataListRegistar.ClearDataList();
                    }
                    else
                    {
                        foreach(var thread in dataObject.ThreadsToDispose)
                        {
                            DataListRegistar.DisposeScope(thread.Key, executionDlid);
                        }

                        DataListRegistar.DisposeScope(Thread.CurrentThread.ManagedThreadId, executionDlid);
                    }
                }

                // old HTML throw back ;)
                if(dataObject.ReturnType == EmitionTypes.WIZ)
                {
                    int start = (executePayload.IndexOf("<Dev2System.FormView>", StringComparison.Ordinal) + 21);
                    int end = (executePayload.IndexOf("</Dev2System.FormView>", StringComparison.Ordinal));
                    int len = (end - start);
                    if(len > 0)
                    {
                        if(dataObject.ReturnType == EmitionTypes.WIZ)
                        {
                            string tmp = executePayload.Substring(start, (end - start));
                            string result = CleanupHtml(tmp);
                            const string DocType = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">";
                            return new StringResponseWriter(String.Format("{0}\r\n{1}", DocType, result), ContentTypes.Html);
                        }
                    }
                }

                // JSON Data ;)
                if(executePayload.IndexOf("</JSON>", StringComparison.Ordinal) >= 0)
                {
                    int start = executePayload.IndexOf(GlobalConstants.OpenJSON, StringComparison.Ordinal);
                    if(start >= 0)
                    {
                        int end = executePayload.IndexOf(GlobalConstants.CloseJSON, StringComparison.Ordinal);
                        start += GlobalConstants.OpenJSON.Length;

                        executePayload = CleanupHtml(executePayload.Substring(start, (end - start)));
                        if(!String.IsNullOrEmpty(executePayload))
                        {
                            return new StringResponseWriter(executePayload, ContentTypes.Json);
                        }
                    }
                }
                Dev2DataListDecisionHandler.Instance.RemoveEnvironment(dataObject.DataListID);
                dataObject.Environment = null;
                // else handle the format requested ;)
                return new StringResponseWriter(executePayload, formatter.ContentType);
            }
        }
        protected static IResponseWriter CreateForm(WebRequestTO webRequest, string serviceName, string workspaceId, NameValueCollection headers, IPrincipal user = null)
        {
            //lock(ExecutionObject)
            {
                string executePayload = "";
                Guid workspaceGuid;

                if(workspaceId != null)
                {
                    if(!Guid.TryParse(workspaceId, out workspaceGuid))
                    {
                        workspaceGuid = WorkspaceRepository.Instance.ServerWorkspace.ID;
                    }
                }
                else
                {
                    workspaceGuid = WorkspaceRepository.Instance.ServerWorkspace.ID;
                }

                var allErrors = new ErrorResultTO();
                var dataObject = new DsfDataObject(webRequest.RawRequestPayload, GlobalConstants.NullDataListID, webRequest.RawRequestPayload) { IsFromWebServer = true, ExecutingUser = user, ServiceName = serviceName, WorkspaceID = workspaceGuid };

                // now bind any variables that are part of the path arguments ;)
                BindRequestVariablesToDataObject(webRequest, ref dataObject);

                // now process headers ;)
                if(headers != null)
                {
                    Dev2Logger.Log.Debug("Remote Invoke");

                    var isRemote = headers.Get(HttpRequestHeader.Cookie.ToString());
                    var remoteId = headers.Get(HttpRequestHeader.From.ToString());

                    if(isRemote != null && remoteId != null)
                    {
                        if (isRemote.Equals(GlobalConstants.RemoteServerInvoke) )
                        {
                            // we have a remote invoke ;)
                            dataObject.RemoteInvoke = true;
                        }
                        if (isRemote.Equals(GlobalConstants.RemoteDebugServerInvoke))
                        {
                            // we have a remote invoke ;)
                            dataObject.RemoteNonDebugInvoke = true;
                        }

                        dataObject.RemoteInvokerID = remoteId;
                    }
                }

                // now set the emition type ;)
                int loc;
                if(!String.IsNullOrEmpty(serviceName) && (loc = serviceName.LastIndexOf(".", StringComparison.Ordinal)) > 0)
                {
                    // default it to xml
                    dataObject.ReturnType = EmitionTypes.XML;

                    if(loc > 0)
                    {
                        var typeOf = serviceName.Substring((loc + 1)).ToUpper();
                        EmitionTypes myType;
                        if(Enum.TryParse(typeOf, out myType))
                        {
                            dataObject.ReturnType = myType;
                        }

                        // adjust the service name to drop the type ;)

                        // avoid .wiz amendments ;)
                        if(!typeOf.ToLower().Equals(GlobalConstants.WizardExt))
                        {
                            serviceName = serviceName.Substring(0, loc);
                            dataObject.ServiceName = serviceName;
                        }

                        if(typeOf.Equals("api", StringComparison.OrdinalIgnoreCase))
                        {
                            dataObject.ReturnType = EmitionTypes.SWAGGER;
                    }

                }
                }
                else
                {
                    // default it to xml
                    dataObject.ReturnType = EmitionTypes.XML;
                }

                // ensure service gets set ;)
                if(dataObject.ServiceName == null)
                {
                    dataObject.ServiceName = serviceName;
                }
                IResource resource = null;
                if(!String.IsNullOrEmpty(dataObject.ServiceName))
                {
                    resource = ResourceCatalog.Instance.GetResource(dataObject.WorkspaceID, dataObject.ServiceName);
                    if(resource != null)
                    {
                        dataObject.ResourceID = resource.ResourceID;

                    }
                }
                var esbEndpoint = new EsbServicesEndpoint();
                dataObject.EsbChannel = esbEndpoint;
                var canExecute = true;
                if(ServerAuthorizationService.Instance != null)
                {
                    var authorizationService = ServerAuthorizationService.Instance;
                    var hasView = authorizationService.IsAuthorized(AuthorizationContext.View, dataObject.ResourceID.ToString());
                    var hasExecute = authorizationService.IsAuthorized(AuthorizationContext.Execute, dataObject.ResourceID.ToString());
                    canExecute = (hasExecute && hasView) || ((dataObject.RemoteInvoke || dataObject.RemoteNonDebugInvoke) && hasExecute) || (resource != null && resource.ResourceType == ResourceType.ReservedService);
                }
                // Build EsbExecutionRequest - Internal Services Require This ;)
                EsbExecuteRequest esbExecuteRequest = new EsbExecuteRequest { ServiceName = serviceName };
                foreach(string key in webRequest.Variables)
                {
                    esbExecuteRequest.AddArgument(key, new StringBuilder(webRequest.Variables[key]));
                }
                Dev2Logger.Log.Debug("About to execute web request [ " + serviceName + " ] DataObject Payload [ " + dataObject.RawPayload + " ]");
                var executionDlid = GlobalConstants.NullDataListID;
                if (canExecute && dataObject.ReturnType != EmitionTypes.SWAGGER)
                {
                    ErrorResultTO errors = null;
                    // set correct principle ;)
                    Thread.CurrentPrincipal = user;
                    var userPrinciple = user;                   
                    Common.Utilities.PerformActionInsideImpersonatedContext(userPrinciple, () => { executionDlid = esbEndpoint.ExecuteRequest(dataObject, esbExecuteRequest, workspaceGuid, out errors); });
                    allErrors.MergeErrors(errors);
                }
                else if(!canExecute)
                {
                    allErrors.AddError("Executing a service externally requires View and Execute permissions");
                }
                foreach(var error in dataObject.Environment.Errors)
                {
                    allErrors.AddError(error,true);
                }
                // Fetch return type ;)
                var formatter = DataListFormat.CreateFormat("XML", EmitionTypes.XML, "text/xml");

                // force it to XML if need be ;)

                // Fetch and convert DL ;)
                if(!dataObject.Environment.HasErrors())
                {
                    // a normal service request
                    if(!esbExecuteRequest.WasInternalService)
                    {
                        dataObject.DataListID = executionDlid;
                        dataObject.WorkspaceID = workspaceGuid;
                        dataObject.ServiceName = serviceName;
                        
                        if(!dataObject.IsDebug || dataObject.RemoteInvoke ||  dataObject.RemoteNonDebugInvoke)
                        {
                            if (dataObject.ReturnType == EmitionTypes.JSON)
                            {
                                formatter = DataListFormat.CreateFormat("JSON", EmitionTypes.JSON, "application/json");
                                executePayload = ExecutionEnvironmentUtils.GetJsonOutputFromEnvironment(dataObject, resource.DataList.ToString(),0);
                            }
                            else if (dataObject.ReturnType == EmitionTypes.XML)
                            {
                                executePayload = ExecutionEnvironmentUtils.GetXmlOutputFromEnvironment(dataObject,Guid.Empty , resource.DataList.ToString(),0);
                            }else if(dataObject.ReturnType == EmitionTypes.SWAGGER)
                            {
                                formatter = DataListFormat.CreateFormat("SWAGGER", EmitionTypes.SWAGGER, "application/json");
                                executePayload = ExecutionEnvironmentUtils.GetSwaggerOutputForService(resource, resource.DataList.ToString());
                            }
                        }
                        else
                        {
                            executePayload = string.Empty;
                        }
                    }
                    else
                    {
                        // internal service request we need to return data for it from the request object ;)
                        var serializer = new Dev2JsonSerializer();
                        executePayload = string.Empty;
                        var msg = serializer.Deserialize<ExecuteMessage>(esbExecuteRequest.ExecuteResult);

                        if(msg != null)
                        {
                            executePayload = msg.Message.ToString();
                        }

                        // out fail safe to return different types of data from services ;)
                        if(string.IsNullOrEmpty(executePayload))
                        {
                            executePayload = esbExecuteRequest.ExecuteResult.ToString();
                        }
                    }
                }
                else
                {
                    if(dataObject.ReturnType == EmitionTypes.XML)
                    {

                        executePayload =
                            "<FatalError> <Message> An internal error occurred while executing the service request </Message>";
                        executePayload += allErrors.MakeDataListReady();
                        executePayload += "</FatalError>";
                    }
                    else
                    {
                        // convert output to JSON ;)
                        executePayload =
                            "{ \"FatalError\": \"An internal error occurred while executing the service request\",";
                        executePayload += allErrors.MakeDataListReady(false);
                        executePayload += "}";
                    }
                }


                Dev2Logger.Log.Debug("Execution Result [ " + executePayload + " ]");


                // JSON Data ;)
                if(executePayload.IndexOf("</JSON>", StringComparison.Ordinal) >= 0)
                {
                    int start = executePayload.IndexOf(GlobalConstants.OpenJSON, StringComparison.Ordinal);
                    if(start >= 0)
                    {
                        int end = executePayload.IndexOf(GlobalConstants.CloseJSON, StringComparison.Ordinal);
                        start += GlobalConstants.OpenJSON.Length;

                        executePayload = CleanupHtml(executePayload.Substring(start, (end - start)));
                        if(!String.IsNullOrEmpty(executePayload))
                        {
                            return new StringResponseWriter(executePayload, ContentTypes.Json);
                        }
                    }
                }
                Dev2DataListDecisionHandler.Instance.RemoveEnvironment(dataObject.DataListID);
                dataObject.Environment = null;
                return new StringResponseWriter(executePayload, formatter.ContentType);
            }
        }
        private StringBuilder CreateDataObject(string serviceName, string resourceName = null, string xmlFileLocation = null)
        {
            var request = new EsbExecuteRequest { ServiceName = serviceName };

            if(serviceName == "FindResourceService" || serviceName == "GetResourceService")
            {
                request.AddArgument("ResourceName", new StringBuilder(resourceName));
                request.AddArgument("ResourceType", new StringBuilder(ResourceType.WorkflowService.ToString()));
            }
            else if(serviceName == "AddResourceService")
            {
                if(xmlFileLocation != null)
                {
                    request.AddArgument("ResourceXml", new StringBuilder(XmlReader.Create(xmlFileLocation).ReadContentAsString()));
                }
            }

            var serializer = new Dev2JsonSerializer();

            return serializer.SerializeToBuilder(request);
        }
        public StringBuilder ProcessRequest(EsbExecuteRequest request, Guid workspaceID, Guid dataListID, string connectionId)
        {
            var channel = new EsbServicesEndpoint();
            var xmlData = string.Empty;
            if(request.Args != null && request.Args.ContainsKey("DebugPayload"))
            {
                xmlData = request.Args["DebugPayload"].ToString();
                xmlData = xmlData.Replace("<DataList>", "<XmlData>").Replace("</DataList>", "</XmlData>");
            }

            // we need to adjust for the silly xml structure this system was init built on ;(
            if(string.IsNullOrEmpty(xmlData))
            {
                xmlData = "<DataList></DataList>";
            }

            IDSFDataObject dataObject = new DsfDataObject(xmlData, dataListID);
            dataObject.EsbChannel = channel;
            dataObject.ServiceName = request.ServiceName;
            var resource = ResourceCatalog.Instance.GetResource(workspaceID, request.ServiceName);
            if(resource != null)
            {
                dataObject.ResourceID = resource.ResourceID;
            }
            dataObject.ClientID = Guid.Parse(connectionId);
            dataObject.ExecutingUser = ExecutingUser;
            // we need to assign new ThreadID to request coming from here, because it is a fixed connection and will not change ID on its own ;)
            if(!dataObject.Errors.HasErrors())
            {
                var dlID = Guid.Empty;
                ErrorResultTO errors;

                if(ExecutingUser == null)
                {
                    throw new Exception("Null Executing User");
                }

                try
                {
                    // Execute in its own thread to give proper context ;)
                    var t = new Thread(() =>
                    {
                        Thread.CurrentPrincipal = ExecutingUser;
                        dlID = channel.ExecuteRequest(dataObject, request, workspaceID, out errors);
                    });

                    t.Start();

                    t.Join();
                }
                catch(Exception e)
                {
                    Dev2Logger.Log.Error(e.Message,e);
                }


                var compiler = DataListFactory.CreateDataListCompiler();

                if(request.ExecuteResult.Length > 0)
                {
                    return request.ExecuteResult;
                }

                // return the datalist ;)
                if(dataObject.IsDebugMode())
                {
                    compiler.ForceDeleteDataListByID(dlID);
                    return new StringBuilder("Completed Debug");
                }

                var result = compiler.ConvertFrom(dlID, DataListFormat.CreateFormat(GlobalConstants._XML_Without_SystemTags), enTranslationDepth.Data, out errors);
                compiler.ForceDeleteDataListByID(dlID);
                return result;
            }

            ExecuteMessage msg = new ExecuteMessage { HasError = true };
            msg.SetMessage(dataObject.Errors.MakeDisplayReady());

            Dev2JsonSerializer serializer = new Dev2JsonSerializer();
            return serializer.SerializeToBuilder(msg);
        }
        public InternalServiceContainer(ServiceAction sa, IDSFDataObject dataObj, IWorkspace theWorkspace, IEsbChannel esbChannel, EsbExecuteRequest request)
            : base(sa, dataObj, theWorkspace, esbChannel, request)
        {

        }