Example #1
0
        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());
        }
Example #2
0
        public void ClientScheduledResourceModel_SaveScheduledResource_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 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---------------------------
            string errorMessage;
            var    saved = clientScheduledResourceModel.Save(scheduledResourceForTest, out errorMessage);

            //------------Assert Results-------------------------
            mockConnection.Verify(connection => connection.ExecuteCommand(It.IsAny <StringBuilder>(), It.IsAny <Guid>(), It.IsAny <Guid>()), Times.Once());
            Assert.IsTrue(saved);
        }
        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));
        }
Example #4
0
            private static EsbExecuteRequest CreateEsbExecuteRequestFromWebRequest(WebRequestTO webRequest, string serviceName)
            {
                var esbExecuteRequest = new EsbExecuteRequest
                {
                    ServiceName = serviceName,
                };

                foreach (string key in webRequest.Variables)
                {
                    esbExecuteRequest.AddArgument(key, new StringBuilder(webRequest.Variables[key]));
                }

                return(esbExecuteRequest);
            }
Example #5
0
        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;
                    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));
            }
        }
Example #6
0
        protected static IResponseWriter CreateForm(WebRequestTO webRequest, string serviceName, string workspaceId, NameValueCollection headers, IPrincipal user)
        {
            var executePayload = "";

            var workspaceRepository = _repository ?? WorkspaceRepository.Instance;
            var workspaceGuid       = SetWorkspaceId(workspaceId, workspaceRepository);

            var allErrors  = new ErrorResultTO();
            var dataObject = CreateNewDsfDataObject(webRequest, serviceName, user, workspaceGuid);

            dataObject.SetupForWebDebug(webRequest);
            webRequest.BindRequestVariablesToDataObject(ref dataObject);
            dataObject.SetupForRemoteInvoke(headers);
            dataObject.SetEmitionType(webRequest, serviceName, headers);
            dataObject.SetupForTestExecution(serviceName, headers);
            if (dataObject.ServiceName == null)
            {
                dataObject.ServiceName = serviceName;
            }

            dataObject.SetResourceNameAndId(_resourceCatalog, serviceName, out IResource resource);
            dataObject.SetTestResourceIds(_resourceCatalog, webRequest, serviceName);
            dataObject.WebUrl = webRequest.WebServerUrl;
            var serializer  = new Dev2JsonSerializer();
            var esbEndpoint = new EsbServicesEndpoint();

            dataObject.EsbChannel = esbEndpoint;

            var instance   = _authorizationService ?? ServerAuthorizationService.Instance;
            var canExecute = dataObject.CanExecuteCurrentResource(resource, instance);

            // Build EsbExecutionRequest - Internal Services Require This ;)
            var esbExecuteRequest = new EsbExecuteRequest {
                ServiceName = serviceName
            };

            foreach (string key in webRequest.Variables)
            {
                esbExecuteRequest.AddArgument(key, new StringBuilder(webRequest.Variables[key]));
            }

            var executionDlid = GlobalConstants.NullDataListID;
            var formatter     = DataListFormat.CreateFormat("XML", EmitionTypes.XML, "text/xml");

            if (canExecute && dataObject.ReturnType != EmitionTypes.SWAGGER)
            {
                ErrorResultTO errors = null;
                Thread.CurrentPrincipal = user;
                var userPrinciple = user;
                if ((dataObject.ReturnType == EmitionTypes.TEST || dataObject.ReturnType == EmitionTypes.TRX) && dataObject.TestName == "*")
                {
                    formatter = ServiceTestExecutor.ExecuteTests(serviceName, dataObject, formatter, userPrinciple, workspaceGuid, serializer, _testCatalog, _resourceCatalog, ref executePayload);
                    return(new StringResponseWriter(executePayload, formatter.ContentType));
                }

                Common.Utilities.PerformActionInsideImpersonatedContext(userPrinciple, () => { executionDlid = esbEndpoint.ExecuteRequest(dataObject, esbExecuteRequest, workspaceGuid, out errors); });
            }
            else
            {
                if (!canExecute)
                {
                    dataObject.Environment.AddError(string.Format(Warewolf.Resource.Errors.ErrorResource.UserNotAuthorizedToExecuteOuterWorkflowException, dataObject.ExecutingUser.Identity.Name, dataObject.ServiceName));
                }
            }

            formatter = DataListFormat.CreateFormat("JSON", EmitionTypes.JSON, "application/json");
            if (dataObject.IsServiceTestExecution)
            {
                executePayload = ServiceTestExecutor.SetupForTestExecution(serializer, esbExecuteRequest, dataObject);
                if (!canExecute)
                {
                    return(new StringResponseWriter(dataObject.Environment.FetchErrors(), formatter.ContentType));
                }
                return(new StringResponseWriter(executePayload, formatter.ContentType));
            }
            if (dataObject.IsDebugFromWeb)
            {
                var serialize = SetupForWebExecution(dataObject, serializer);
                return(new StringResponseWriter(serialize, formatter.ContentType));
            }

            var unionedErrors = dataObject.Environment?.Errors?.Union(dataObject.Environment?.AllErrors) ?? new List <string>();

            foreach (var error in unionedErrors)
            {
                if (error.Length > 0)
                {
                    allErrors.AddError(error, true);
                }
            }

            var executionDto = new ExecutionDto
            {
                WebRequestTO   = webRequest,
                ServiceName    = serviceName,
                DataObject     = dataObject,
                Request        = esbExecuteRequest,
                DataListIdGuid = executionDlid,
                WorkspaceID    = workspaceGuid,
                Resource       = resource,
                DataListFormat = formatter,
                PayLoad        = executePayload,
                Serializer     = serializer,
                ErrorResultTO  = allErrors
            };

            return(executionDto.CreateResponseWriter());
        }
        private IEnumerable <DeployResult> DeployResource(Guid resourceId, StringBuilder roles, Dev2JsonSerializer serializer, IHubProxy proxy, bool doTestDeploy)
        {
            var toReturn        = new List <DeployResult>();
            var savePath        = new StringBuilder();
            var resourceContent = ResourceCatalog.GetResourceContents(GlobalConstants.ServerWorkspaceID, resourceId);
            var resource        = ResourceCatalog.GetResource(GlobalConstants.ServerWorkspaceID, resourceId);

            if (!resource.IsService)
            {
                var fetchResourceService = new FetchResourceDefinition();
                resourceContent = fetchResourceService.DecryptAllPasswords(resourceContent);
            }
            savePath.Append(resource.GetSavePath());

            var esbExecuteRequest = new EsbExecuteRequest {
                ServiceName = "DeployResourceService"
            };

            esbExecuteRequest.AddArgument("savePath", savePath);
            esbExecuteRequest.AddArgument("ResourceDefinition", resourceContent);
            esbExecuteRequest.AddArgument("Roles", roles);
            Envelope envelope = new Envelope
            {
                Content = serializer.SerializeToBuilder(esbExecuteRequest).ToString(),
                PartID  = 0,
                Type    = typeof(Envelope)
            };
            var messageId = Guid.NewGuid();

            proxy.Invoke <Receipt>("ExecuteCommand", envelope, true, Guid.Empty, Guid.Empty, messageId).Wait();
            Task <string> fragmentInvoke = proxy.Invoke <string>("FetchExecutePayloadFragment", new FutureReceipt {
                PartID = 0, RequestID = messageId
            });
            var fragmentInvokeResult = fragmentInvoke.Result;
            var execResult           = serializer.Deserialize <ExecuteMessage>(fragmentInvokeResult) ?? new ExecuteMessage {
                HasError = true, Message = new StringBuilder("Deploy Fialed")
            };

            toReturn.Add(new DeployResult(execResult, resource.ResourceName));

            if (doTestDeploy)
            {
                var testsToDeploy = TestCatalog.Fetch(resourceId);
                CompressedExecuteMessage message = new CompressedExecuteMessage();
                message.SetMessage(serializer.Serialize(testsToDeploy));
                var testDeployRequest = new EsbExecuteRequest {
                    ServiceName = "SaveTests"
                };
                testDeployRequest.AddArgument("resourceID", resourceId.ToString().ToStringBuilder());
                testDeployRequest.AddArgument("resourcePath", savePath);
                testDeployRequest.AddArgument("testDefinitions", serializer.SerializeToBuilder(message));
                Envelope deployEnvelope = new Envelope
                {
                    Content = serializer.SerializeToBuilder(testDeployRequest).ToString(),
                    PartID  = 0,
                    Type    = typeof(Envelope)
                };
                var deployMessageId = Guid.NewGuid();
                proxy.Invoke <Receipt>("ExecuteCommand", deployEnvelope, true, Guid.Empty, Guid.Empty, deployMessageId).Wait();
                Task <string> deployFragmentInvoke = proxy.Invoke <string>("FetchExecutePayloadFragment", new FutureReceipt {
                    PartID = 0, RequestID = deployMessageId
                });
                var deployFragmentInvokeResult = deployFragmentInvoke.Result;
                var deployExecResult           = serializer.Deserialize <ExecuteMessage>(deployFragmentInvokeResult) ?? new ExecuteMessage {
                    HasError = true, Message = new StringBuilder("Deploy Fialed")
                };
                toReturn.Add(new DeployResult(deployExecResult, $"{resource.ResourceName} Tests"));
            }
            return(toReturn);
        }