Example #1
0
        public void Init2WayTest()
        {
            using (Init2WayMockMessagingService twoWayTarget = new Init2WayMockMessagingService
            {
                StepName = "Init 2-Way mock service",
                ServiceURI = "http://*****:*****@"BizWTF.Testing.Sample.Messages.Mock-Demo-ServiceResponse.xml",
                                                                                    System.Reflection.Assembly.GetExecutingAssembly());
                twoWayTarget.ResolutionSettings.Clear();
                twoWayTarget.ResolutionSettings.Add(setting);
                // Add as many resolution setting as needed

                /// OPTIONAL : if you need to fire some custom code when a message is received
                //MockServiceEventHub.ResetMessageReceivedEventHandler(); // Optional, if you need to flush all event handlers
                MockServiceEventHub.OnMessageReceived += this.messageReceived;

                /// OPTIONAL : if you need to fire some custom code when a message is resolved
                //MockServiceEventHub.ResetMessageResolvedEventHandler(); // Optional, if you need to flush all event handlers
                MockServiceEventHub.OnMessageResolved += (string uri, MultipartMessageDefinition message) =>
                {
                    if (uri == twoWayTarget.ServiceURI)
                    {
                        // Do something
                    }
                };

                /// Following code must complete (this is were we start the mock service)
                /// In case of any error, the user that runs the test may need som additional right to reserve the URL.
                /// If so, consider using the following command : netsh http add urlacl url=... user=...
                if (!twoWayTarget.ExecuteStep())
                {
                    Assert.Fail(twoWayTarget.ResultDescription);
                }
                #endregion



                /// Add the rest of your test here
                // Do something
                SubmitMockMessage2WayStep sendStep = new SubmitMockMessage2WayStep("Mock submission test"); // TODO: Initialize to an appropriate value
                sendStep.DestURI                = "http://*****:*****@"BizWTF.Testing.Sample.Messages.Mock-Demo-2WayMockService.xml";
                sendStep.SourceResourceAssembly = System.Reflection.Assembly.GetExecutingAssembly().FullName;
                sendStep.TargetContextProperty  = "Init2WayTest_Response";

                if (!sendStep.ExecuteStep())
                {
                    Assert.Fail(sendStep.ResultDescription);
                }

                Assert.AreEqual(twoWayTarget.ReceivedMessages.Count, 1);
                Assert.IsNotNull(BTSTestContext.GetParam(sendStep.TargetContextProperty));
            }
        }
        //public override object GetData()
        //{
        //    // Not implemented
        //    return null;
        //}

        public override bool ExecuteStep()
        {
            this.AppendResultDescription(0, "Executing step [{0}] ({1}):", this.StepName, this.StepType);
            this.AppendResultDescription(1, "Context Properties :");
            foreach (ControlProperty prop in this.ContextProps)
            {
                this.AppendResultDescription(2, "{0}/{1} : {2}", prop.Namespace, prop.Property, prop.Value);
                if (!String.IsNullOrEmpty(prop.TargetContextProperty))
                {
                    this.AppendResultDescription(3, "(overrided by context prop '{0}')", prop.TargetContextProperty);
                }
            }
            this.AppendResultDescription(1, "XPath Values :");
            foreach (ControlField field in this.XPathProps)
            {
                this.AppendResultDescription(2, "{0} : {1}", field.XPath, field.Value);
            }


            using (BizTalkDTADbEntities btsDTA = new BizTalkDTADbEntities(System.Configuration.ConfigurationManager.ConnectionStrings["BizTalkDTADbEntities"].ConnectionString))
            {
                TrackingDatabase dta = new TrackingDatabase(BTSTestContext.BizTalkDbServer,
                                                            BTSTestContext.BizTalkDTADb);
                BizTalkOperations       operations = new BizTalkOperations(BTSTestContext.BizTalkDbServer, BTSTestContext.BizTalkMgmtDb);
                List <MatchingPartInfo> partList   = MatchingPartInfo.GetMatchingPartInfo(btsDTA, dta, operations, this.ContextProps, this.XPathProps, this.ProcessName, null);

                if (partList.Count > 0)
                {
                    List <MultipartMessageDefinition> msgs = new List <MultipartMessageDefinition>();
                    foreach (MatchingPartInfo part in partList)
                    {
                        this.AppendResultDescription(1, "[OK] Matching service instance found, messageID={0}", part.MessageInstanceId);
                        IBaseMessage trackedMsg = operations.GetTrackedMessage(part.MessageInstanceId, dta);

                        MultipartMessageDefinition tempMsg = MultipartMessageManager.GenerateFromMessage(trackedMsg);
                        tempMsg.Description = String.Format("Service : {0} - Message instance: {1}", part.ServiceName, part.MessageInstanceId);
                        msgs.Add(tempMsg);
                    }

                    BTSTestContext.AddParam(this.TargetContextProperty, msgs);
                    this.Result = StepResult.OK;
                }
                else
                {
                    this.AppendResultDescription(1, "[KO] No matching service instance found", EventLogEntryType.Error);
                    this.Result = StepResult.Error;
                }
            }

            return(this.Result == StepResult.OK);
        }
Example #3
0
        public void Test2WayFaultedService()
        {
            using (Init2WayMockMessagingService twoWayTarget = new Init2WayMockMessagingService
            {
                StepName = "Init 2-Way mock service",
                ServiceURI = "http://*****:*****@"BizWTF.Testing.Sample.Messages.Mock-Demo-2WayMockService-Direct.xml";
                sendStep.SourceResourceAssembly = System.Reflection.Assembly.GetExecutingAssembly().FullName;
                sendStep.TargetContextProperty  = "Init2WayTest_Response";

                if (!sendStep.ExecuteStep())
                {
                    Assert.Fail(sendStep.ResultDescription);
                }

                Assert.AreEqual(twoWayTarget.ReceivedMessages.Count, 1);
                Assert.IsNotNull(BTSTestContext.GetParam(sendStep.TargetContextProperty));
            }
        }
Example #4
0
        public override bool ExecuteStep()
        {
            MultipartMessageDefinition tempMsg = null;
            XmlTextReader xmlBodyReader        = null;

            this.AppendResultDescription(0, "Executing step {0} ({1}):", this.StepName, this.StepType);

            if (!File.Exists(this.SourceFile) && String.IsNullOrEmpty(this.SourceResource))
            {
                this.AppendResultDescription(1, "File {0} does not exist.", this.SourceFile);
                this.Result = StepResult.Error;
            }
            else if (File.Exists(this.SourceFile))
            {
                //xmlBodyReader = new XmlTextReader(this.SourceFile);
                tempMsg = MultipartMessageSerializer.RetrieveDocument(this.SourceFile);
            }
            else
            {
                Assembly asmb = Assembly.Load(this.SourceResourceAssembly);
                //xmlBodyReader = new XmlTextReader(asmb.GetManifestResourceStream(this.SourceResource));
                tempMsg = MultipartMessageSerializer.RetrieveDocument(this.SourceResource, asmb);
            }

            if (this.Result != StepResult.Error)
            {
                if (!string.IsNullOrEmpty(this.TestID))
                {
                    List <ContextProperty> props = tempMsg.PropertyBag.ToList <ContextProperty>();
                    props.Add(new ContextProperty
                    {
                        Name      = BTSProperties.testID.Name.Name,
                        Namespace = BTSProperties.testID.Name.Namespace,
                        Promoted  = false,
                        Value     = this.TestID
                    });
                    tempMsg.PropertyBag = props.ToArray();
                }
                XmlDocument doc = MultipartMessageSerializer.Serialize(tempMsg);
                xmlBodyReader = new XmlTextReader(new StringReader(doc.OuterXml));

                BizTalk2WayReference.TwoWayAsyncClient client = new BizTalk2WayReference.TwoWayAsyncClient();
                try
                {
                    client.Endpoint.Address = new System.ServiceModel.EndpointAddress(this.DestURI);
                    client.Open();

                    Message request = Message.CreateMessage(MessageVersion.Soap11, "Get2WayMultipartMessage", xmlBodyReader);

                    Message response = client.BizTalkSubmit(request);
                    this.AppendResultDescription(1, "[OK] Send file {0}, received response from {1}", this.SourceFile, DestURI);



                    HttpResponseMessageProperty httpResponse = (HttpResponseMessageProperty)response.Properties["httpResponse"];
                    if (httpResponse.StatusCode != System.Net.HttpStatusCode.InternalServerError)
                    {
                        MemoryStream ms = new MemoryStream();
                        XmlWriter    xw = XmlWriter.Create(ms, new XmlWriterSettings {
                            Indent = true, IndentChars = "  ", OmitXmlDeclaration = true
                        });
                        XmlDictionaryReader bodyReader = response.GetReaderAtBodyContents();

                        while (bodyReader.NodeType != XmlNodeType.EndElement && bodyReader.LocalName != "Body" && bodyReader.NamespaceURI != "http://schemas.xmlsoap.org/soap/envelope/")
                        {
                            if (bodyReader.NodeType != XmlNodeType.Whitespace)
                            {
                                xw.WriteNode(bodyReader, true);
                            }
                            else
                            {
                                bodyReader.Read(); // ignore whitespace; maintain if you want
                            }
                        }
                        xw.Flush();

                        XmlSerializer serializer = new XmlSerializer(typeof(MultipartMessageDefinition));
                        ms.Seek(0, SeekOrigin.Begin);
                        BTSTestContext.AddParam(this.TargetContextProperty, serializer.Deserialize(ms));
                    }
                    else
                    {
                        MessageFault fault       = MessageFault.CreateFault(response, 10000000);
                        string       faultString = fault.Reason.ToString();

                        //XmlDocument faultDoc = new XmlDocument();
                        //faultDoc.Load(bodyReader);

                        this.AppendResultDescription(1, "[KO] Error when sending file {0} to {1} : {2}", this.SourceFile, DestURI, faultString);
                        this.Result = StepResult.Error;
                    }
                }
                catch (Exception exc)
                {
                    this.AppendResultDescription(1, "[KO] Error when sending file {0} to {1} : {2}", this.SourceFile, DestURI, exc.Message);
                    this.Result = StepResult.Error;
                }
                finally
                {
                    if (client != null)
                    {
                        if (client.State == System.ServiceModel.CommunicationState.Opened)
                        {
                            client.Close();
                        }
                    }
                }
            }
            if (this.Result == StepResult.Working)
            {
                this.Result = StepResult.OK;
            }

            return(this.Result != StepResult.Error);
        }
        //public override List<OrchestrationInstanceInfo> GetData<List<OrchestrationInstanceInfo>>()
        //{
        //    return this.InstanceList;
        //}

        public override bool ExecuteStep()
        {
            this.AppendResultDescription(0, "Executing step [{0}] ({1}):", this.StepName, this.StepType);
            this.AppendResultDescription(1, "Context Properties :");
            foreach (ControlProperty prop in this.ContextProps)
            {
                this.AppendResultDescription(2, "{0}/{1} : {2}", prop.Namespace, prop.Property, prop.Value);
                if (!String.IsNullOrEmpty(prop.TargetContextProperty))
                {
                    this.AppendResultDescription(2, "(overrided by context prop '{0}')", prop.TargetContextProperty);
                }
            }
            this.AppendResultDescription(1, "XPath Values :");
            foreach (ControlField field in this.XPathProps)
            {
                this.AppendResultDescription(2, "{0} : {1}", field.XPath, field.Value);
            }


            using (BizTalkDTADbEntities btsDTA = new BizTalkDTADbEntities(System.Configuration.ConfigurationManager.ConnectionStrings["BizTalkDTADbEntities"].ConnectionString))
            {
                TrackingDatabase dta = new TrackingDatabase(BTSTestContext.BizTalkDbServer,
                                                            BTSTestContext.BizTalkDTADb);
                BizTalkOperations       operations = new BizTalkOperations(BTSTestContext.BizTalkDbServer, BTSTestContext.BizTalkMgmtDb);
                List <MatchingPartInfo> partList   = MatchingPartInfo.GetMatchingPartInfo(btsDTA, dta, operations,
                                                                                          this.ContextProps,
                                                                                          this.XPathProps,
                                                                                          this.ProcessName,
                                                                                          this.SourceContextProperty
                                                                                          ).Distinct <MatchingPartInfo>(new MatchingPartServiceIDComparer()).ToList();

                if (partList.Count > 0)
                {
                    this.AppendResultDescription(1, "[OK] Matching service {0} instances found ", partList.Count);
                    foreach (MatchingPartInfo part in partList)
                    {
                        this.AppendResultDescription(2, "Matching service instance : {0}", part.ServiceInstanceId);

                        OrchestrationInstanceInfo currentInstance = new OrchestrationInstanceInfo(part.txtSymbol);
                        currentInstance.FlowDefinition.ProcessName = this.ProcessName;

                        var filteredMsgIds = from me in btsDTA.dta_MessageInOutEvents
                                             where me.uidServiceInstanceId == part.ServiceInstanceId
                                             orderby me.dtInsertionTimeStamp descending
                                             select new
                        {
                            me.uidMessageInstanceId
                        };
                        foreach (var msg in filteredMsgIds)
                        {
                            currentInstance.Messages.Add(operations.GetTrackedMessage(msg.uidMessageInstanceId, dta));
                        }
                        this.AppendResultDescription(3, "Found {0} attached messages", filteredMsgIds.Count());

                        this.AppendResultDescription(3, "Pre-processing DebugShapes", filteredMsgIds.Count());
                        var debugTraces = from dt in btsDTA.dta_DebugTrace
                                          where dt.uidServiceInstanceId == part.ServiceInstanceId
                                          orderby dt.dtInsertionTimeStamp ascending
                                          select new DebugShape
                        {
                            ShapeID    = dt.vtInstructionId,
                            StartTime  = dt.dtBeginTimeStamp,
                            FinishTime = dt.dtEndTimeStamp
                        };
                        foreach (DebugShape trace in debugTraces)
                        {
                            string    shapePath = String.Empty;
                            ShapeInfo shape     = currentInstance.FlowDefinition.GetShape(trace.ShapeID, ref shapePath);
                            trace.shapeText = shape.shapeText;
                            trace.shapeType = shape.shapeType;
                            trace.ShapePath = shapePath;

                            currentInstance.Trace.TraceDetails.Add(trace);
                            this.AppendResultDescription(4, "Processed shape '{0}' ({1})", trace.shapeText, trace.ShapePath);
                        }
                        this.InstanceList.Add(currentInstance);
                    }

                    this.Result = StepResult.OK;
                }
                else
                {
                    this.AppendResultDescription(1, "No matching service instance found", EventLogEntryType.Error);
                    this.Result = StepResult.Error;
                }
            }

            BTSTestContext.AddParam(this.TargetContextProperty, this.InstanceList);

            return(this.Result == StepResult.OK);
        }
Example #6
0
 private void addInstanceInContext(OrchestrationInstance instance)
 {
     lock (BTSTestContext.Params)
         ((List <OrchestrationInstance>)BTSTestContext.GetParam(this.TargetContextProperty)).Add(instance);
 }
Example #7
0
        //public override object GetData()
        //{ return null; }

        public override bool ExecuteStep()
        {
            BTSTestContext.AddParam(this.TargetContextProperty, new List <OrchestrationInstance>());

            this.AppendResultDescription(0, "Executing step [{0}] ({1}):", this.StepName, this.StepType);
            this.AppendResultDescription(1, "Context Properties :");
            foreach (ControlProperty prop in this.ContextProps)
            {
                this.AppendResultDescription(2, "{0}/{1} : {2}", prop.Namespace, prop.Property, prop.Value);
                if (!String.IsNullOrEmpty(prop.TargetContextProperty))
                {
                    this.AppendResultDescription(3, "(overridden by context prop '{0}')", prop.TargetContextProperty);
                }
            }
            this.AppendResultDescription(1, "XPath Values :");
            foreach (ControlField field in this.XPathProps)
            {
                this.AppendResultDescription(2, "{0} : {1}", field.XPath, field.Value);
            }
            this.AppendResultDescription(1, "PollingInterval : {0}", this.PollingInterval);
            this.AppendResultDescription(1, "PollingCount : {0}", this.PollingCount);

            TrackingDatabase dta = new TrackingDatabase(BTSTestContext.BizTalkDbServer,
                                                        BTSTestContext.BizTalkDTADb);
            BizTalkOperations operations = new BizTalkOperations(BTSTestContext.BizTalkDbServer, BTSTestContext.BizTalkMgmtDb);
            //bool result = true;



            int loopIterator = 0;

            while (((IList)BTSTestContext.GetParam(this.TargetContextProperty)).Count == 0 && loopIterator < this.PollingCount)
            {
                loopIterator++;

                //IEnumerable services = operations.GetServiceInstances();
                IEnumerator servicesEnum = operations.GetServiceInstances().GetEnumerator();

                while (servicesEnum.MoveNext())
                {
                    if (servicesEnum.Current.GetType() == typeof(Microsoft.BizTalk.Operations.OrchestrationInstance))
                    {
                        OrchestrationInstance tempInstance = (OrchestrationInstance)servicesEnum.Current;

                        Analyzer analyser = new Analyzer(tempInstance);
                        this.onProcess         += analyser.ProcessInstance;
                        analyser.ProcessStopped = this.ProcessStopped;
                        analyser.AddToContext   = this.addInstanceInContext;
                    }
                }
                if (this.onProcess != null)
                {
                    this.onProcess(operations, this.ContextProps, this.XPathProps, this.ProcessName, this.AppendResultDescription);
                }



                if (((IList)BTSTestContext.GetParam(this.TargetContextProperty)).Count == 0)
                {
                    this.AppendResultDescription(1, "[{0}] No matching service instance found, retrying in {1} milliseconds.", EventLogEntryType.Warning, this.PollingInterval);
                    System.Threading.Thread.Sleep(this.PollingInterval);
                }
                else
                {
                    this.Result = StepResult.OK;
                }
            }


            if (this.Result != StepResult.OK)
            {
                this.AppendResultDescription(1, "[{0}] No matching service instance found!!", EventLogEntryType.Error);
                this.Result = StepResult.Error;
            }

            return(this.Result == StepResult.OK);
        }
Example #8
0
        public void Call2WayMock()
        {
            using (Init2WayMockMessagingService twoWayTarget = new Init2WayMockMessagingService
            {
                StepName = "Init 2-Way mock service",
                ServiceURI = "http://*****:*****@"BizWTF.Testing.Sample.Messages.Mock-Demo-2WayMockService-Response.xml",
                                                                                    System.Reflection.Assembly.GetExecutingAssembly());
                twoWayTarget.ResolutionSettings.Clear();
                twoWayTarget.ResolutionSettings.Add(setting);
                // Add as many resolution setting as needed

                /// OPTIONAL : if you need to fire some custom code when a message is received
                //MockServiceEventHub.ResetMessageReceivedEventHandler(); // Optional, if you need to flush all event handlers
                MockServiceEventHub.OnMessageReceived += (string uri, MultipartMessageDefinition message) =>
                {
                    if (uri == twoWayTarget.ServiceURI)
                    {
                        // Do something
                    }
                };

                /// OPTIONAL : if you need to fire some custom code when a message is resolved
                //MockServiceEventHub.ResetMessageResolvedEventHandler(); // Optional, if you need to flush all event handlers
                MockServiceEventHub.OnMessageResolved += (string uri, MultipartMessageDefinition message) =>
                {
                    if (uri == twoWayTarget.ServiceURI)
                    {
                        // Do something
                    }
                };

                /// Following code must complete (this is were we start the mock service)
                /// In case of any error, the user that runs the test may need som additional right to reserve the URL.
                /// If so, consider using the following command : netsh http add urlacl url=... user=...
                if (!twoWayTarget.ExecuteStep())
                {
                    Assert.Fail(twoWayTarget.ResultDescription);
                }
                #endregion



                /// Add the rest of your test here
                // Do something
                SubmitMockMessage2WayStep send2WayMsgStep = new SubmitMockMessage2WayStep("Submit 2Way Message");
                send2WayMsgStep.DestURI                = "http://*****:*****@"BizWTF.Testing.Sample.Messages.Mock-Demo-1WayMockService.xml";
                send2WayMsgStep.SourceResourceAssembly = System.Reflection.Assembly.GetExecutingAssembly().FullName; // In this case, the resource is embedded in the current assembly
                send2WayMsgStep.TestID = Guid.NewGuid().ToString();                                                  // NOTE : you can provide a test ID, wich will be attached as a message property. This facilitates instance tracking.
                send2WayMsgStep.TargetContextProperty = "send2WayMsgStep_Response";

                /// NOTE : the folowwing code actually sends the message.
                /// Nevertheless, it is recommended to first initialize all the steps of the test before executing any of them.
                if (!send2WayMsgStep.ExecuteStep())
                {
                    Assert.Fail(send2WayMsgStep.ResultDescription);
                }

                /// Once the step has executed successfully, do whatever test you need to do.
                /// The following code : BTSTestContext.GetParam(send2WayMsgStep.TargetContextProperty)
                /// retrieves the response received.
                Assert.IsNotNull(BTSTestContext.GetParam(send2WayMsgStep.TargetContextProperty));
            }
        }