public void PerformanceCounterPersistence_Load_ResourceCounters() { var _file = new Mock <IFile>(); var register = new Mock <IWarewolfPerformanceCounterRegister>(); PerformanceCounterPersistence obj = new PerformanceCounterPersistence(_file.Object); IList <IResourcePerformanceCounter> counters = new List <IResourcePerformanceCounter>(); counters.Add(new TestResourceCounter()); var serialiser = new Dev2JsonSerializer(); var fileName = Path.GetTempFileName(); _file.Setup(a => a.Exists(fileName)).Returns(true); _file.Setup(a => a.ReadAllText(fileName)).Returns(serialiser.Serialize(counters)); File.WriteAllText(fileName, serialiser.Serialize(counters)); var persisted = obj.LoadOrCreateResourceCounters(fileName); Assert.AreEqual(0, obj.DefaultResourceCounters.Count); Assert.AreEqual(persisted.Count, 1); File.Delete(fileName); }
public override IEnumerable <StateVariable> GetState() { var serializer = new Dev2JsonSerializer(); return(new[] { new StateVariable { Name = "Switch", Type = StateVariable.StateType.Input, Value = Switch }, new StateVariable { Name = "Switches", Type = StateVariable.StateType.Output, Value = serializer.Serialize(Switches) }, new StateVariable { Name = "Default", Type = StateVariable.StateType.Output, Value = serializer.Serialize(Default) }, new StateVariable { Name = "Result", Value = Result, Type = StateVariable.StateType.Output } }); }
public void AddItemMessage(IExplorerItem addedItem) { if (addedItem != null) { addedItem.ServerId = HostSecurityProvider.Instance.ServerID; var item = _serializer.Serialize(addedItem); var hubCallerConnectionContext = Clients; hubCallerConnectionContext.Others.ItemAddedMessage(item); } }
public void Workflow_WorkflowNodesForHtml_FlowDecision_HandlingNested_FlowDecision_ShouldSuccess() { var dev2DecisionStackParent = GetDecisionStackParent(); var dev2DecisionStackChild = GetDecisionChild(); var jsonSerializer = new Dev2JsonSerializer(); var flowNodes = new Collection <FlowNode> { new FlowDecision() { Condition = new DsfFlowDecisionActivity { ExpressionText = jsonSerializer.Serialize(dev2DecisionStackParent) }, DisplayName = "Decision (parent)", True = new FlowStep { Action = new DsfMultiAssignActivity { DisplayName = "Assign (success)" } }, False = new FlowDecision() { Condition = new DsfFlowDecisionActivity { ExpressionText = jsonSerializer.Serialize(dev2DecisionStackChild) }, DisplayName = "Decision (child)", True = new FlowStep { Action = new DsfMultiAssignActivity { DisplayName = "Assign (Decision child)-True Arm" } }, False = new FlowStep { Action = new DsfMultiAssignActivity { DisplayName = "Assign (Decision child)-False Arm" } } } } }; var sut = new Workflow(flowNodes); var nodes = sut.WorkflowNodesForHtml; Assert.AreEqual(1, nodes.Count); Assert.AreEqual(2, nodes[0].NextNodes.Count); Assert.AreEqual(5, sut.WorkflowNodes.Count); }
public void AuditingSettingsData_Set_Get_LoggingDataSource() { var dependency = new Depends(Depends.ContainerType.AnonymousElasticsearch); var hostName = "http://" + dependency.Container.IP; var source = new ElasticsearchSource { AuthenticationType = AuthenticationType.Anonymous, Port = dependency.Container.Port, HostName = hostName, SearchIndex = "warewolflogstests" }; var serializer = new Dev2JsonSerializer(); var jsonSource = serializer.Serialize(source); var expectedAuditingSettingsData = new AuditingSettingsData { Endpoint = "ws://127.0.0.1:5000/ws", EncryptDataSource = true, LoggingDataSource = new NamedGuidWithEncryptedPayload { Name = "Data Source", Value = Guid.Empty, Payload = jsonSource }, }; IDeserializer deserializer = new JsonSerializer(); var bytes = UTF8Encoding.UTF8.GetBytes(expectedAuditingSettingsData.LoggingDataSource.Payload); var result = deserializer.Deserialize <ElasticsearchSource>(bytes); Assert.AreEqual(expectedAuditingSettingsData.LoggingDataSource.Value, Guid.Empty); Assert.AreEqual(expectedAuditingSettingsData.LoggingDataSource.Name, "Data Source"); Assert.AreEqual(source, result); }
public override StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { try { string directory = null; var result = new StringBuilder(); if (values == null) { throw new InvalidDataContractException(ErrorResource.NoParameter); } values.TryGetValue("Directory", out StringBuilder tmp); if (tmp != null) { directory = tmp.ToString(); } if (string.IsNullOrEmpty(directory)) { throw new InvalidDataContractException(ErrorResource.DirectoryIsRequired); } Dev2Logger.Info("Get Directories Relative to Server. " + directory, GlobalConstants.WarewolfInfo); result.Append("<JSON>"); var explorerItem = ServerExplorerRepo.Load("Folder", string.Empty); var jsonTreeNode = new JsonTreeNode(explorerItem); var serializer = new Dev2JsonSerializer(); var directoryInfoAsJson = serializer.Serialize(jsonTreeNode); result.Append(directoryInfoAsJson); result.Append("</JSON>"); return(result); } catch (Exception e) { Dev2Logger.Error(e, GlobalConstants.WarewolfError); throw; } }
public override StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { try { var guidCsv = string.Empty; string type = null; values.TryGetValue("GuidCsv", out StringBuilder tmp); if (tmp != null) { guidCsv = tmp.ToString(); } values.TryGetValue("ResourceType", out tmp); if (tmp != null) { type = tmp.ToString(); } var resources = ResourceCatalog.Instance.GetResourceList(theWorkspace.ID, new Dictionary <string, string> { { "guidCsv", guidCsv }, { "type", type } }); IList <SerializableResource> resourceList = resources.Select(r => new FindResourceHelper().SerializeResourceForStudio(r, theWorkspace.ID)).ToList(); var serializer = new Dev2JsonSerializer(); var message = new CompressedExecuteMessage(); message.SetMessage(serializer.Serialize(resourceList)); return(serializer.SerializeToBuilder(message)); } catch (Exception err) { Dev2Logger.Error(err, GlobalConstants.WarewolfError); throw; } }
public void ExecutionDtoExtentions_CreateResponseWriter_WasInternalService_And_ExecuteMessageXML_PayLoadIsNullOrEmpty_Success() { //-------------------------------Arrange---------------------------------- var mockDSFDataObject = new Mock <IDSFDataObject>(); mockDSFDataObject.Setup(o => o.Environment.HasErrors()).Returns(false); var esbExecuteRequestMessage = "<xml>test message</xml>"; var jsonSerializer = new Dev2JsonSerializer(); var serExecuteMessage = jsonSerializer.Serialize(esbExecuteRequestMessage); var executionDto = new ExecutionDto { DataObject = mockDSFDataObject.Object, DataListFormat = DataListFormat.CreateFormat("XML", EmitionTypes.XML, "application/xml"), ErrorResultTO = new ErrorResultTO(), Request = new EsbExecuteRequest { WasInternalService = true, ExecuteResult = new StringBuilder(serExecuteMessage) }, Serializer = jsonSerializer, }; var executionDtoExtentions = new ExecutionDtoExtentions(executionDto); //-------------------------------Act-------------------------------------- executionDtoExtentions.CreateResponseWriter(new StringResponseWriterFactory()); //-------------------------------Assert----------------------------------- Assert.AreEqual(expected: "\"<xml>test message</xml>\"", actual: executionDto.PayLoad); }
public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { var serializer = new Dev2JsonSerializer(); try { Dev2Logger.Info("Fetch Tests Service", GlobalConstants.WarewolfInfo); values.TryGetValue("resourceID", out StringBuilder resourceIdString); if (resourceIdString == null) { throw new InvalidDataContractException("resourceID is missing"); } if (!Guid.TryParse(resourceIdString.ToString(), out Guid resourceId)) { throw new InvalidDataContractException("resourceID is not a valid GUID."); } var tests = TestCatalog.Fetch(resourceId); var message = new CompressedExecuteMessage(); message.SetMessage(serializer.Serialize(tests)); message.HasError = false; return(serializer.SerializeToBuilder(message)); } catch (Exception err) { Dev2Logger.Error(err, GlobalConstants.WarewolfError); var res = new CompressedExecuteMessage { HasError = true, Message = new StringBuilder(err.Message) }; return(serializer.SerializeToBuilder(res)); } }
public void SaveTriggers_Execute_GivenResourceDefinition_ShouldReturnResourceDefinitionMsg() { //---------------Set up test pack------------------- var serializer = new Dev2JsonSerializer(); var triggerQueues = new List <ITriggerQueue> { new TriggerQueue { QueueName = "Test Queue" } }; var compressedExecuteMessage = new CompressedExecuteMessage(); compressedExecuteMessage.SetMessage(serializer.Serialize(triggerQueues)); var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder(Guid.NewGuid().ToString()) }, { "resourcePath", "Home".ToStringBuilder() } }; var saveTriggers = new SaveTriggers(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var jsonResult = saveTriggers.Execute(values, null); var result = serializer.Deserialize <ExecuteMessage>(jsonResult); //---------------Test Result ----------------------- Assert.IsTrue(result.HasError); Assert.AreEqual("triggerDefinitions is missing", result.Message.ToString()); }
public void FindResourcesByType_Execute_ExpectIDb() { var expected = new IDb[] { new DbSource() }; var mockResourceCatalog = new Mock <IResourceCatalog>(); mockResourceCatalog.Setup(o => o.FindByType(typeof(IDb).FullName)).Returns(expected); //------------Setup for test------------------------- var service = new FindResourcesByType(new Lazy <IResourceCatalog>(() => mockResourceCatalog.Object)); IWorkspace workspace = null; var values = new Dictionary <string, StringBuilder>(); values.Add("Type", new StringBuilder(typeof(IDb).FullName)); //------------Execute Test--------------------------- var result = service.Execute(values, workspace); //------------Assert Results------------------------- var serializer = new Dev2JsonSerializer(); var expectedString = serializer.Serialize(expected, Newtonsoft.Json.Formatting.None); Assert.AreEqual(expectedString, result.ToString()); }
public AuditLog(IDSFDataObject dsfDataObject, string auditType, string detail, IDev2Activity previousActivity, IDev2Activity nextActivity) { var dev2Serializer = new Dev2JsonSerializer(); WorkflowID = dsfDataObject.ResourceID.ToString(); ExecutionID = dsfDataObject.ExecutionID.ToString(); ExecutionOrigin = Convert.ToInt64(dsfDataObject.ExecutionOrigin); IsSubExecution = Convert.ToBoolean(dsfDataObject.IsSubExecution); IsRemoteWorkflow = Convert.ToBoolean(dsfDataObject.IsRemoteWorkflow()); WorkflowName = dsfDataObject.ServiceName; ServerID = dsfDataObject.ServerID.ToString(); ParentID = dsfDataObject.ParentID.ToString(); ExecutingUser = dsfDataObject.ExecutingUser?.ToString(); ExecutionOriginDescription = dsfDataObject.ExecutionOriginDescription; ExecutionToken = dev2Serializer.Serialize(ExecutionToken); Environment = dsfDataObject.Environment.ToJson(); VersionNumber = dsfDataObject.VersionNumber.ToString(); AuditDate = DateTime.Now; AuditType = auditType; AdditionalDetail = detail; if (previousActivity != null) { PreviousActivity = previousActivity.GetDisplayName(); PreviousActivityType = previousActivity.GetType().ToString(); PreviousActivityId = previousActivity.UniqueID; } if (nextActivity != null) { NextActivity = nextActivity.GetDisplayName(); NextActivityType = nextActivity.GetType().ToString(); NextActivityId = nextActivity.UniqueID; } }
public static DataListFormat RunCoverageAndReturnJSON(this ICoverageDataObject coverageData, ITestCoverageCatalog testCoverageCatalog, ITestCatalog testCatalog, IResourceCatalog catalog, Guid workspaceGuid, Dev2JsonSerializer serializer, out string executePayload) { var(allCoverageReports, _) = RunListOfCoverage(coverageData, testCoverageCatalog, testCatalog, workspaceGuid, catalog); var formatter = DataListFormat.CreateFormat("JSON", EmitionTypes.JSON, "application/json"); var objArray = allCoverageReports.AllCoverageReportsSummary .Where(o => o.HasTestReports) .Select(o => { var name = o.Resource.ResourceName; if (o.Resource is IFilePathResource filePath) { name = filePath.Path; } return(new JObject { { "ResourceID", o.Resource.ResourceID }, { "Name", name }, { "Reports", new JArray(o.Reports.Select(o1 => o1.BuildTestResultJSONForWebRequest())) } }); }); var obj = new JObject { { "StartTime", allCoverageReports.StartTime }, { "EndTime", allCoverageReports.EndTime }, { "Results", new JArray(objArray) }, }; executePayload = serializer.Serialize(obj); return(formatter); }
public static DataListFormat RunMultipleTestBatches(this IDSFDataObject dataObject, IPrincipal userPrinciple, Guid workspaceGuid, Dev2JsonSerializer serializer, DataListFormat formatter, IResourceCatalog catalog, ITestCatalog testCatalog, ref string executePayload) { foreach (var testsResourceId in dataObject.TestsResourceIds) { var allTests = testCatalog.Fetch(testsResourceId); var taskList = new List <Task>(); var testResults = new List <IServiceTestModelTO>(); foreach (var test in allTests) { dataObject.ResourceID = testsResourceId; var dataObjectClone = dataObject.Clone(); dataObjectClone.Environment = new ExecutionEnvironment(); dataObjectClone.TestName = test.TestName; var res = catalog.GetResource(GlobalConstants.ServerWorkspaceID, testsResourceId); var resourcePath = res.GetResourcePath(GlobalConstants.ServerWorkspaceID).Replace("\\", "/"); var lastTask = ServiceTestExecutor.GetTaskForTestExecution(resourcePath, userPrinciple, workspaceGuid, serializer, testResults, dataObjectClone); taskList.Add(lastTask); } Task.WaitAll(taskList.ToArray()); formatter = DataListFormat.CreateFormat("JSON", EmitionTypes.JSON, "application/json"); var objArray = (from testRunResult in testResults where testRunResult != null select testRunResult.BuildTestResultForWebRequest() ).ToList(); executePayload = executePayload + Environment.NewLine + serializer.Serialize(objArray); } return(formatter); }
public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { var msg = new ExecuteMessage(); var serializer = new Dev2JsonSerializer(); try { Dev2Logger.Info("Test Redis Source", GlobalConstants.WarewolfInfo); msg.HasError = false; values.TryGetValue(Warewolf.Service.TestRedisSource.RedisSource, out StringBuilder resourceDefinition); var redisServiceSourceDefinition = serializer.Deserialize <RedisSourceDefinition>(resourceDefinition); var con = new RedisSources(); var result = con.Test(new RedisSource { HostName = redisServiceSourceDefinition.HostName, Port = redisServiceSourceDefinition.Port, AuthenticationType = redisServiceSourceDefinition.AuthenticationType, Password = redisServiceSourceDefinition.Password }); msg.HasError = false; msg.Message = new StringBuilder(result.IsValid ? serializer.Serialize(result.Result) : result.ErrorMessage); msg.HasError = !result.IsValid; } catch (Exception err) { msg.HasError = true; msg.Message = new StringBuilder(err.Message); Dev2Logger.Error(err, GlobalConstants.WarewolfError); } return(serializer.SerializeToBuilder(msg)); }
void ConfigureDecisionExpression(ModelItem mi) { var condition = mi; var expression = condition.Properties[GlobalConstants.ExpressionPropertyText]; var ds = DataListConstants.DefaultStack; if (expression?.Value != null) { var eval = Dev2DecisionStack.ExtractModelFromWorkflowPersistedData(expression.Value.ToString()); if (!string.IsNullOrEmpty(eval)) { ExpressionText = eval; } } else { var ser = new Dev2JsonSerializer(); ExpressionText = ser.Serialize(ds); } var displayName = mi.Properties[GlobalConstants.DisplayNamePropertyText]; if (displayName?.Value != null) { ds.DisplayText = displayName.Value.ToString(); } Tos = ToObservableCollection(); }
public override StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { IWebSocketWrapper client = null; try { var serializer = new Dev2JsonSerializer(); var result = new List <IExecutionHistory>(); if (values == null) { throw new InvalidDataContractException(ErrorResource.NoParameter); } values.TryGetValue("ResourceId", out StringBuilder triggerID); if (triggerID != null) { client = _webSocketPool.Acquire(Config.Auditing.Endpoint).Connect(); Dev2Logger.Info("Get Execution History Data from Logger Service. " + triggerID, GlobalConstants.WarewolfInfo); var response = ""; var message = new AuditCommand { Type = "TriggerQuery", Query = values }; try { var ewh = new EventWaitHandle(false, EventResetMode.ManualReset); client.OnMessage((msgResponse, socket) => { response = msgResponse; result.AddRange(serializer.Deserialize <List <ExecutionHistory> >(response)); ewh.Set(); }); client.SendMessage(serializer.Serialize(message)); ewh.WaitOne(_waitTimeOut); return(serializer.SerializeToBuilder(result)); } catch (Exception e) { Dev2Logger.Info("Get Execution History Data ServiceError", e, GlobalConstants.WarewolfInfo); } return(serializer.SerializeToBuilder(result)); } Dev2Logger.Debug("No QueueName Provided", GlobalConstants.WarewolfDebug); return(serializer.SerializeToBuilder(new List <IExecutionHistory>())); } catch (Exception err) { Dev2Logger.Error(err, GlobalConstants.WarewolfError); throw; } finally { if (client != null) { _webSocketPool.Release(client); } } }
public void ExecutionDtoExtentions_CreateResponseWriter_WasInternalService_And_ExecuteMessageXML_Success() { //-------------------------------Arrange---------------------------------- var mockDSFDataObject = new Mock <IDSFDataObject>(); mockDSFDataObject.Setup(o => o.Environment.HasErrors()).Returns(false); var esbExecuteRequestMessage = "<xml>test message</xml>"; var executeMessage = new ExecuteMessage(); executeMessage.Message.Append(esbExecuteRequestMessage); var jsonSerializer = new Dev2JsonSerializer(); var serExecuteMessage = jsonSerializer.Serialize(executeMessage); var executionDto = new ExecutionDto { DataObject = mockDSFDataObject.Object, ErrorResultTO = new ErrorResultTO(), Request = new EsbExecuteRequest { WasInternalService = true, ExecuteResult = new StringBuilder(serExecuteMessage) }, Serializer = jsonSerializer, }; var executionDtoExtentions = new ExecutionDtoExtentions(executionDto); //-------------------------------Act-------------------------------------- executionDtoExtentions.CreateResponseWriter(new StringResponseWriterFactory()); //-------------------------------Assert----------------------------------- Assert.AreEqual(expected: esbExecuteRequestMessage, actual: executionDto.PayLoad); }
public void LogAdditionalDetail(object detail, string callerName) { var serializer = new Dev2JsonSerializer(); var auditLog = new Audit(_dsfDataObject, "LogAdditionalDetail", serializer.Serialize(detail, Formatting.None), null, null); LogAuditState(auditLog); }
public void Execute_GivenResourceDefination_ShouldReturnResourceDefinationMsg() { //---------------Set up test pack------------------- var serializer = new Dev2JsonSerializer(); var listOfTests = new List <ServiceTestModelTO> { new ServiceTestModelTO { AuthenticationType = AuthenticationType.Public, Enabled = true, TestName = "Test MyWF" } }; var compressedExecuteMessage = new CompressedExecuteMessage(); compressedExecuteMessage.SetMessage(serializer.Serialize(listOfTests)); var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder(Guid.NewGuid().ToString()) }, { "resourcePath", "Home".ToStringBuilder() } }; var saveTests = new SaveTests(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var jsonResult = saveTests.Execute(values, null); var result = serializer.Deserialize <ExecuteMessage>(jsonResult); //---------------Test Result ----------------------- Assert.IsTrue(result.HasError); Assert.AreEqual("testDefinition is missing", result.Message.ToString()); }
public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { var serializer = new Dev2JsonSerializer(); try { Dev2Logger.Info("Fetch Trigger Queue Service", GlobalConstants.WarewolfInfo); var triggerQueues = TriggersCatalog.Queues; var message = new CompressedExecuteMessage { HasError = false }; message.SetMessage(serializer.Serialize(triggerQueues)); message.HasError = false; return(serializer.SerializeToBuilder(message)); } catch (Exception err) { var msg = new ExecuteMessage { HasError = true, Message = new StringBuilder(err.Message) }; Dev2Logger.Error("Fetch Queue Service Failed: " + err.Message, GlobalConstants.WarewolfError); return(serializer.SerializeToBuilder(msg)); } }
public List <IFileListing> GetComDllListings(IFileListing listing) { var serializer = new Dev2JsonSerializer(); var comsController = CommunicationControllerFactory.CreateController("GetComDllListingsService"); comsController.AddPayloadArgument("currentDllListing", serializer.Serialize(listing)); var workspaceId = Connection.WorkspaceID; var result = comsController.ExecuteCommand <ExecuteMessage>(Connection, workspaceId); if (result == null || result.HasError) { if (!Connection.IsConnected) { ShowServerDisconnectedPopup(); return(new List <IFileListing>()); } if (result != null) { throw new WarewolfSupportServiceException(result.Message.ToString(), null); } throw new WarewolfSupportServiceException(ErrorResource.ServiceDoesNotExist, null); } var dllListings = serializer.Deserialize <List <IFileListing> >(result.Message.ToString()); return(dllListings); }
private static void CheckServerVersion(IHubProxy proxy) { Dev2JsonSerializer serializer = new Dev2JsonSerializer(); var esbExecuteRequest = new EsbExecuteRequest { ServiceName = "GetServerVersion" }; Envelope envelope = new Envelope { Content = serializer.Serialize(esbExecuteRequest), 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 serverVersion = fragmentInvoke.Result; if (!string.IsNullOrEmpty(serverVersion)) { Version sourceVersionNumber; Version.TryParse(serverVersion, out sourceVersionNumber); Version destVersionNumber; Version.TryParse("0.0.0.6", out destVersionNumber); if (sourceVersionNumber != null && destVersionNumber != null) { if (sourceVersionNumber < destVersionNumber) { throw new VersionConflictException(sourceVersionNumber, destVersionNumber); } } } }
string CreateFixedData() { var serializer = new Dev2JsonSerializer(); var result = serializer.Serialize(DataMappingListFactory.CreateListInputMapping(DataMappingViewModel.GetInputString(DataMappingViewModel.Inputs))); return(string.Concat("<Input>", result, "</Input>")); }
CompressedExecuteMessage GetExplorerItems(Dev2JsonSerializer serializer, bool reloadResourceCatalogue) { var item = ServerExplorerRepo.Load(GlobalConstants.ServerWorkspaceID, reloadResourceCatalogue); var message = new CompressedExecuteMessage(); message.SetMessage(serializer.Serialize(item)); return(message); }
private void ExecuteLogQuery(Dictionary <string, StringBuilder> query, IWebSocketConnection socket, IWriter writer) { var serializer = new Dev2JsonSerializer(); var auditQueryable = GetAuditQueryable(); var results = auditQueryable.QueryLogData(query); writer.WriteLine("sending QueryLog to server: " + results + "..."); socket.Send(serializer.Serialize(results)); }
public static string SetpForTestExecution(Dev2JsonSerializer serializer, EsbExecuteRequest esbExecuteRequest, IDSFDataObject dataObject) { var result = serializer.Deserialize <ServiceTestModelTO>(esbExecuteRequest.ExecuteResult); string executePayload; if (result != null) { var resObj = result.BuildTestResultForWebRequest(); executePayload = serializer.Serialize(resObj); Dev2DataListDecisionHandler.Instance.RemoveEnvironment(dataObject.DataListID); dataObject.Environment = null; } else { executePayload = serializer.Serialize(new JObject()); } return(executePayload); }
public void DsfCreateJsonActivity_GetState_ReturnsStateVariable() { //---------------Set up test pack------------------- var uniqueId = Guid.NewGuid().ToString(); var mappings = new List <JsonMappingTo> { new JsonMappingTo { DestinationName = "Some Name" } }; //------------Setup for test-------------------------- var activity = new DsfCreateJsonActivity() { UniqueID = uniqueId, JsonMappings = mappings, JsonString = "{ Json String }" }; //------------Execute Test--------------------------- var stateItems = activity.GetState(); Assert.AreEqual(2, stateItems.Count()); var serializer = new Dev2JsonSerializer(); var mappingItems = serializer.Serialize(activity.JsonMappings); var expectedResults = new[] { new StateVariable { Name = "JsonMappings", Type = StateVariable.StateType.Input, Value = mappingItems }, new StateVariable { Name = "JsonString", Type = StateVariable.StateType.Output, Value = "{ Json String }" } }; var iter = activity.GetState().Select( (item, index) => new { value = item, expectValue = expectedResults[index] } ); //------------Assert Results------------------------- foreach (var entry in iter) { Assert.AreEqual(entry.expectValue.Name, entry.value.Name); Assert.AreEqual(entry.expectValue.Type, entry.value.Type); Assert.AreEqual(entry.expectValue.Value, entry.value.Value); } }
public void Execute_ValidValues_ValidResults() { //------------Setup for test-------------------------- var serializer = new Dev2JsonSerializer(); var inputs = new Dictionary <string, StringBuilder>(); var resourceID = Guid.NewGuid(); var directDeploy = new DirectDeploy(); var resourceMock = new Mock <IResource>(); resourceMock.SetupGet(resource => resource.ResourceID).Returns(resourceID); resourceMock.Setup(resource => resource.GetResourcePath(It.IsAny <Guid>())).Returns("Home"); var testCatalogMock = new Mock <ITestCatalog>(); var resourceCatalog = new Mock <IResourceCatalog>(); resourceCatalog.Setup(catalog => catalog.GetResource(GlobalConstants.ServerWorkspaceID, resourceID)).Returns(resourceMock.Object); resourceCatalog.Setup(catalog => catalog.GetResourceContents(GlobalConstants.ServerWorkspaceID, resourceID)).Returns(new StringBuilder("Content")); testCatalogMock.Setup(a => a.Fetch(It.IsAny <Guid>())).Verifiable(); var connectionsMock = new Mock <IConnections>(); connectionsMock.Setup(connection => connection.CanConnectToServer(It.IsAny <Data.ServiceModel.Connection>())).Returns(new ValidationResult { IsValid = true }); var hubProxy = new Mock <IHubProxy>(); hubProxy.Setup(proxy => proxy.Invoke("ExecuteCommand", It.IsAny <Envelope>(), It.IsAny <bool>(), It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(Task.FromResult(new Receipt())); var executeMessage = new ExecuteMessage(); executeMessage.HasError = false; executeMessage.Message = new StringBuilder("Great Succesess"); var execMsg = serializer.Serialize(executeMessage); hubProxy.Setup(proxy => proxy.Invoke <string>("FetchExecutePayloadFragment", It.IsAny <FutureReceipt>())).Returns(Task.FromResult(execMsg)); connectionsMock.Setup(connection => connection.CreateHubProxy(It.IsAny <Data.ServiceModel.Connection>())).Returns(hubProxy.Object); directDeploy.Connections = connectionsMock.Object; inputs.Add("resourceIDsToDeploy", serializer.SerializeToBuilder(new List <Guid> { resourceID })); inputs.Add("destinationEnvironmentId", serializer.SerializeToBuilder(new Data.ServiceModel.Connection { Address = "ABC", UserName = "******", Password = "******", AuthenticationType = AuthenticationType.Anonymous })); inputs.Add("deployTests", serializer.SerializeToBuilder(true)); inputs.Add("deployTriggers", serializer.SerializeToBuilder(true)); directDeploy.TestCatalog = testCatalogMock.Object; directDeploy.ResourceCatalog = resourceCatalog.Object; //------------Execute Test--------------------------- var jsonResult = directDeploy.Execute(inputs, null); var result = serializer.Deserialize <IEnumerable <DeployResult> >(jsonResult); //------------Assert Results------------------------- Assert.IsTrue(result.All(r => !r.HasError)); }
static string SetupForWebExecution(IDSFDataObject dataObject, Dev2JsonSerializer serializer) { var fetchDebugItems = WebDebugMessageRepo.Instance.FetchDebugItems(dataObject.ClientID, dataObject.DebugSessionID); var remoteDebugItems = fetchDebugItems?.Where(state => state.StateType != StateType.Duration).ToArray() ?? new IDebugState[] { }; var debugStates = DebugStateTreeBuilder.BuildTree(remoteDebugItems); var serialize = serializer.Serialize(debugStates); return(serialize); }
public void ResourceTypeConvertor_ConvertToJson_EnumAsString_ExpectConvert() { //------------Setup for test-------------------------- Dev2JsonSerializer serializer = new Dev2JsonSerializer(); var data = serializer.Serialize(new ServerExplorerItem("a", Guid.Empty, ResourceType.DbService, null, Permissions.Administrator, "bob")); //------------Execute Test--------------------------- Assert.IsTrue(data.Contains("DbService")); //------------Assert Results------------------------- }
public void ResourceTypeConvertor_ConvertToJson_EnumAsString_Deserialise_ExpectConvert_OldServer_IsServer() { //------------Setup for test-------------------------- Dev2JsonSerializer serializer = new Dev2JsonSerializer(); var data = serializer.Serialize(new ServerExplorerItem("a", Guid.Empty, ResourceType.DbService, null, Permissions.Administrator, "bob")); //------------Execute Test--------------------------- Assert.IsTrue(data.Contains("DbService")); data = data.Replace(@"""ResourceType"": ""DbService""", @"""ResourceType"": ""1024"""); var item = (ServerExplorerItem)serializer.Deserialize(data, typeof(ServerExplorerItem)); Assert.AreEqual(ResourceType.Server, item.ResourceType); //------------Assert Results------------------------- }
// ReSharper disable InconsistentNaming public void RemoteDebugItemParser_Parse_WhenValidJsonList_ExpectItems() // ReSharper restore InconsistentNaming { //------------Setup for test-------------------------- List<IDebugState> items = new List<IDebugState> { new DebugState {ActivityType = ActivityType.Workflow, ClientID = Guid.Empty, DisplayName = "DebugState"} }; Dev2JsonSerializer serializer = new Dev2JsonSerializer(); var data = serializer.Serialize(items); //------------Execute Test--------------------------- var result = RemoteDebugItemParser.ParseItems(data); //------------Assert Results------------------------- Assert.AreEqual(1, result.Count); Assert.AreEqual("DebugState", result[0].DisplayName); Assert.AreEqual(ActivityType.Workflow, result[0].ActivityType); }
/// <summary> /// Executes the service /// </summary> /// <param name="values">The values.</param> /// <param name="theWorkspace">The workspace.</param> /// <returns></returns> public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace) { try { string directory = null; StringBuilder result = new StringBuilder(); if(values == null) { throw new InvalidDataContractException("No parameter values provided."); } StringBuilder tmp; values.TryGetValue("Directory", out tmp); if(tmp != null) { directory = tmp.ToString(); } if(String.IsNullOrEmpty(directory)) { throw new InvalidDataContractException("No value provided for Directory parameter."); } Dev2Logger.Log.Info("Get Directories Relative to Server. "+directory); result.Append("<JSON>"); var explorerItem = ServerExplorerRepo.Load(ResourceType.Folder, string.Empty); var jsonTreeNode = new JsonTreeNode(explorerItem); var serializer = new Dev2JsonSerializer(); var directoryInfoAsJson = serializer.Serialize(jsonTreeNode); result.Append(directoryInfoAsJson); result.Append("</JSON>"); return result; } catch (Exception e) { Dev2Logger.Log.Error(e); throw; } }
static Mock<IEnvironmentConnection> SetupConnectionWithCompileMessageList(List<ICompileMessageTO> compileMessageTos, List<string> deps) { CompileMessageList compileMessageList = new CompileMessageList { MessageList = compileMessageTos, Dependants = deps }; var jsonSer = new Dev2JsonSerializer(); string serializeObject = jsonSer.Serialize(compileMessageList); var envConnection = new Mock<IEnvironmentConnection>(); envConnection.Setup(e => e.IsConnected).Returns(true); envConnection.Setup(c => c.ServerEvents).Returns(new EventPublisher()); envConnection.Setup(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>())).Returns(new StringBuilder(serializeObject)); return envConnection; }