public static void TerminateUncompletedBizTalkServiceInstances() { // https://blogs.msdn.microsoft.com/biztalknotes/2015/05/19/biztalk-2013-r2-issues-while-terminating-and-resuming-instance-using-c-code/ // http://stackoverflow.com/questions/27454762/biztalk-operations-terminateinstance-sql-error // From BizTalk 2010 onwards, it was decided to acquire a lock only on Update statement and not on Select // statements. Therefore the workaround is to create 2 BizTalkOperations objects. One for the Select operation // methods and other for Update Operations methods. using (var bizTalkOperations = new BizTalkOperations()) { GetRunningOrSuspendedServiceInstances() .Select(i => new { ServiceInstance = i, CompletionStatus = bizTalkOperations.TerminateInstance(i.ID) }) .Where(sd => sd.CompletionStatus != CompletionStatus.Succeeded) .ForEach( (idx, sd) => { Trace.TraceWarning("Could not terminate the BizTalk service instance with ID {0}", sd.ServiceInstance.ID); _logger.Warn( $"[{idx,2}] Could not terminate the BizTalk service instance class: {sd.ServiceInstance.Class}\r\n" + $" ServiceType: {sd.ServiceInstance.ServiceType}\r\n" + $" Creation Time: {sd.ServiceInstance.CreationTime}\r\n" + $" Status: {sd.ServiceInstance.InstanceStatus}\r\n" + $" Error: {sd.ServiceInstance.ErrorDescription}\r\n"); } ); } }
/// <summary> /// This function will check to see if there are any service instances for the given /// BizTalk application. If so, it will throw an exception. /// </summary> public override bool Execute() { this.Log.LogMessage("Checking for existing service instances associated with application '{0}'...", _applicationName); using (BizTalkOperations _operations = new BizTalkOperations()) { // Get all service instances in the message box. foreach (Instance instance in _operations.GetServiceInstances()) { // We will only deal with instances that we can determine // which application it belongs to. MessageBoxServiceInstance mbsi = instance as MessageBoxServiceInstance; if (mbsi != null) { if (mbsi.Application == Application) { this.Log.LogError( "There is at least one service instance associated with the '{0}' application [Instance Status = {1}]. An application be removed only when there are no associated service instances.", _applicationName, Enum.GetName(typeof(InstanceStatus), mbsi.InstanceStatus)); return(false); } } } } this.Log.LogMessage("Done checking for existing service instances associated with application '{0}'.", _applicationName); return(true); }
public static MessageBoxServiceInstance[] GetRunningOrSuspendedServiceInstances() { using (var bizTalkOperations = new BizTalkOperations()) { return(bizTalkOperations .GetServiceInstances().OfType <MessageBoxServiceInstance>() .Where(i => (i.InstanceStatus & (InstanceStatus.RunningAll | InstanceStatus.SuspendedAll)) != InstanceStatus.None) .ToArray()); } }
private void SaveHelper(string outputFolder, BizTalkOperations biztalkOps, InstanceStatus statusToFind) { int i = 0; foreach (Instance instance in biztalkOps.GetServiceInstances()) { if (instance is OrchestrationInstance) { OrchestrationInstance orchInstance = instance as OrchestrationInstance; if (orchInstance.InstanceStatus == statusToFind) { i = i + 1; if (orchInstance.CreationTime >= DateTime.Parse(textStartDate.Text) && orchInstance.CreationTime <= DateTime.Parse(textEndDate.Text)) { Trace(string.Format( "Found orch ({0}) in date range. Creation date:{1}", i, orchInstance.CreationTime)); bool msgFound = false; foreach (IBaseMessage msg in orchInstance.Messages) { IBaseMessagePart part = msg.BodyPart; if (part == null) { Trace("Found null message attached to service instance."); } else { using (StreamWriter sw = new StreamWriter(Path.Combine(outputFolder, msg.MessageID.ToString()))) { Trace("Saving message attached to service instance with msgid:" + msg.MessageID.ToString()); using (StreamReader partReader = new StreamReader(part.Data)) { sw.Write(partReader.ReadToEnd()); } sw.Close(); msgFound = true; } } } if (!msgFound) { Trace(string.Format("No messages found for instance: " + instance.ID.ToString())); } CompletionStatus status = biztalkOps.TerminateInstance(instance.ID); Trace(string.Format("Terminating instance: {0} yielded {1}", instance.ID.ToString(), status)); } } } } }
//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); }
/// <summary> /// retrieve message body by message ID and store it in the dictionary /// </summary> /// <param name="messageId"></param> /// <returns>the message content</returns> public String GetMessageBodyByMessageId(Guid messageId, Guid instanceId) { using (BizTalkOperations operations = new BizTalkOperations()) { IBaseMessage message = operations.GetMessage(messageId, instanceId); String body = String.Empty; using (StreamReader streamReader = new StreamReader(message.BodyPart.Data)) { body = streamReader.ReadToEnd(); } //add the new message to the dictionnary return(body); } }
private void SaveMessages( string mgmtDbServer, string mgmtDbName, string outputFolder) { AppSettingsReader appSet = new System.Configuration.AppSettingsReader(); InstanceStatus statusToFind = (InstanceStatus)Enum.Parse(typeof(InstanceStatus), (string)appSet.GetValue("State", typeof(string))); BizTalkOperations biztalkOps = new BizTalkOperations(mgmtDbServer, mgmtDbName); int retryCount = 0; bool retryLoop = true; while (retryLoop) { try { SaveHelper(outputFolder, biztalkOps, statusToFind); retryLoop = false; } catch (System.Exception ex) { // For large numbers of messages, the connection occasionally breaks off... if (ex.Message.IndexOf("Failed to connect") > -1) { bool connectSuccess = false; while (!connectSuccess) { try { retryCount++; Trace(string.Format("Connection failure {0} - trying again.", retryCount)); this.Refresh(); System.Threading.Thread.Sleep(500); biztalkOps = new BizTalkOperations(mgmtDbServer, mgmtDbName); connectSuccess = true; } catch { } } } } } Trace("Done."); }
private void btnGenerate_Click(object sender, EventArgs e) { //string targetDirectory = new FileInfo(this._project.FullName).DirectoryName; BizTalkOperations operations = new BizTalkOperations(this.txtDTAServerName.Text, this.txtMgmtDBName.Text); TrackingDatabase dta = new TrackingDatabase(this.txtDTAServerName.Text, this.txtDTADBName.Text); if (this.dgMessages.SelectedRows.Count > 0) { foreach (DataGridViewRow row in this.dgMessages.SelectedRows) { IBaseMessage btsMessage = operations.GetTrackedMessage((Guid)row.Cells["InstanceID"].Value, dta); MultipartMessageDefinition tempMsg = MultipartMessageManager.GenerateFromMessage(btsMessage); string destPath = System.IO.Path.Combine(this._targetFolder, String.Format("{0}-{1}-{2}.xml", row.Cells["EventType"].Value, row.Cells["PortName"].Value, row.Cells["InstanceID"].Value)); MultipartMessageSerializer.Serialize(tempMsg).Save(destPath); if (this._project != null) { EnvDTE.ProjectItem item = this._project.ProjectItems.AddFromFile(destPath); EnvDTE.Property prop = item.Properties.Item("BuildAction"); prop.Value = 2; } } this.Close(); } else { MessageBox.Show("Please select one or more messages to generate.", "No message selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public string GetBiztalkMessage(string messageId) { string messageBody = string.Empty; // Converts the Collection for Connection String // NameValueCollection collection = ConvertStringToNameValueCollection(ConfigurationManager.AppSettings["BCC.BIZTALK_CONNECTION"]); BizTalkOperations operations = new BizTalkOperations(); IEnumerable messages = operations.GetMessages(); try { foreach (BizTalkMessage message in messages) { if (messageId.Equals(message.MessageID.ToString())) { using (StreamReader streamReader = new StreamReader(message.BodyPart.Data)) { messageBody = streamReader.ReadToEnd(); } } } } catch (Exception e) { throw e; } if (messageBody != null && messageBody.Length > 0) { return messageBody; } else { return "No message found for " + messageId; } }
//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); }
public static MessageFlow GetMessageFlow(string instanceID) { BizTalkOperations bizOps = new BizTalkOperations(GlobalProperties.MgmtDBServer, GlobalProperties.MgmtDBName); return(bizOps.GetMessageFlow(new Guid(instanceID))); }
public void ResumeMessage(string instanceID) { BizTalkOperations btOperations = new BizTalkOperations(); btOperations.ResumeInstance(new Guid(instanceID)); }
public override bool Execute() { if (string.IsNullOrEmpty(_applicationName)) { base.Log.LogError("Application property must be set"); return(false); } int resumedServiceCount = 0; bool success = true; bool resumeAll = (_applicationName.Trim() == "*"); base.Log.LogMessage( MessageImportance.Normal, "Attempting to resume all service instances for BizTalk app '{0}'...", resumeAll ? "[ALL APPS]" : _applicationName); using (BizTalkOperations operations = new BizTalkOperations()) { // Get all service instances in the message box. // This is terribly inefficient -- BizTalkOperations has a way to directly query and filter by app, but the classes are Internal. // Could use reflection to call it anyway, but risks compatibility across BizTalk releases. foreach (Instance instance in operations.GetServiceInstances()) { MessageBoxServiceInstance mbsi = instance as MessageBoxServiceInstance; if (mbsi != null) { // Only resume if the application matches the one we are interested in. "*" will match all apps. bool resumeThisInstance = (resumeAll || (string.Compare(mbsi.Application, _applicationName, true) == 0)); bool suspended = ((mbsi.InstanceStatus & InstanceStatus.SuspendedAll) != InstanceStatus.None); if (resumeThisInstance && suspended) { CompletionStatus status = operations.ResumeInstance(mbsi.ID); if (status != CompletionStatus.Succeeded) { this.Log.LogWarning("Could not resume instance {0}. Status is {1}.", mbsi.ID, status.ToString()); success = false; } else { resumedServiceCount++; } if (resumedServiceCount % 5000 == 0) { base.Log.LogMessage( MessageImportance.Normal, "Resumed {0} service instances for BizTalk app '{1}'.", resumedServiceCount, resumeAll ? "[ALL APPS]" : _applicationName); } } } } } base.Log.LogMessage( MessageImportance.Normal, "Finished resuming {0} service instances for BizTalk app '{1}'.", resumedServiceCount, resumeAll ? "[ALL APPS]" : _applicationName); return(success); }
public static bool PerformMessageLookup(Guid messageInstanceID, List <ControlProperty> contextProps, List <ControlField> xpathProps, TrackingDatabase dta, BizTalkOperations operations) { bool result = true; try { /// NOTE : /// Following instruction will throw an exception if the corresponding message was not found in the DTA Db IBaseMessage message = operations.GetTrackedMessage(messageInstanceID, dta); Logger.CurrentLogger.Write(2, "Testing message {0}", System.Diagnostics.EventLogEntryType.Information, messageInstanceID); //BizTalkMessage btsMsg = (BizTalkMessage)rawMessage; foreach (ControlProperty prop in contextProps) { string expectedValue = prop.Value; string foundValue = (string)message.Context.Read( prop.Property, prop.Namespace); if (expectedValue != foundValue) { Logger.CurrentLogger.Write(3, "[KO] Prop '{0}/{1}' : mismatch - Expected {2}, found {3}.", System.Diagnostics.EventLogEntryType.Information, prop.Namespace, prop.Property, expectedValue, foundValue); result = false; } else { Logger.CurrentLogger.Write(3, "[OK] Prop '{0}/{1}' : match - Expected {2}, found {3}.", System.Diagnostics.EventLogEntryType.Information, prop.Namespace, prop.Property, expectedValue, foundValue); } } if (xpathProps.Count > 0) { List <ControlField> tmpXpathProps = xpathProps.ToList <ControlField>(); for (int i = 0; i < message.PartCount; i++) { string body = string.Empty; string partName = string.Empty; using (StreamReader streamReader = new StreamReader(message.GetPartByIndex(i, out partName).Data)) { Logger.CurrentLogger.Write(3, "Testing part {0}", System.Diagnostics.EventLogEntryType.Information, partName); Logger.CurrentLogger.Write(3, "Retrieving body...", System.Diagnostics.EventLogEntryType.Information); body = streamReader.ReadToEnd(); Logger.CurrentLogger.Write(3, "Body retrieved successfully : Length={0}", System.Diagnostics.EventLogEntryType.Information, body.Length); XmlDocument testedMsg = new XmlDocument(); testedMsg.LoadXml(body); foreach (ControlField field in xpathProps) { string expectedValue = field.Value; XmlNode tmpNode = testedMsg.SelectSingleNode(field.XPath); if (tmpNode != null) { string foundValue = tmpNode.InnerText; if (expectedValue != foundValue) { Logger.CurrentLogger.Write(3, "[KO] XPath '{0}' : mismatch - Expected {1}, found {2}.", System.Diagnostics.EventLogEntryType.Information, field.XPath, expectedValue, foundValue); } else { Logger.CurrentLogger.Write(3, "[OK] XPath '{0}' : match - Expected {1}, found {2}.", System.Diagnostics.EventLogEntryType.Information, field.XPath, expectedValue, foundValue); tmpXpathProps.Remove(tmpXpathProps.Find(tmpField => tmpField.XPath == field.XPath && tmpField.Value == field.Value)); } } } if (tmpXpathProps.Count == 0) { break; } } } if (tmpXpathProps.Count == 0) { result = true; } else { result = false; } } return(result); } catch (Exception ex) { Logger.CurrentLogger.Write(2, "Error when retrieving message {0} from DTA Db : {1}", System.Diagnostics.EventLogEntryType.Error, messageInstanceID, ex.Message); return(false); } }
//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); } TrackingDatabase dta = new TrackingDatabase(BTSTestContext.BizTalkDbServer, BTSTestContext.BizTalkDTADb); BizTalkOperations operations = new BizTalkOperations(BTSTestContext.BizTalkDbServer, BTSTestContext.BizTalkMgmtDb); IEnumerable services = operations.GetServiceInstances(); IEnumerator servicesEnum = services.GetEnumerator(); while (servicesEnum.MoveNext()) { if (servicesEnum.Current.GetType() == typeof(Microsoft.BizTalk.Operations.OrchestrationInstance)) { OrchestrationInstance tempInstance = (OrchestrationInstance)servicesEnum.Current; this.AppendResultDescription(1, "Analysing instance of '{0}'", tempInstance.ServiceType); this.AppendResultDescription(1, "Service status : {0}", tempInstance.InstanceStatus); if (tempInstance.ServiceType.StartsWith(this.ProcessName)) { this.AppendResultDescription(2, "[OK] Service Type match : {0}", this.ProcessName); foreach (var rawMessage in tempInstance.Messages) { if (rawMessage.GetType() == typeof(BizTalkMessage)) { bool currentMatch = true; BizTalkMessage btsMsg = (BizTalkMessage)rawMessage; string body = string.Empty; using (StreamReader streamReader = new StreamReader(btsMsg.BodyPart.Data)) { body = streamReader.ReadToEnd(); } foreach (ControlProperty prop in this.ContextProps) { string expectedValue = prop.Value; string foundValue = (string)btsMsg.Context.Read( prop.Property, prop.Namespace); if (expectedValue != foundValue) { this.AppendResultDescription(3, "[KO] Prop '{0}/{1}' : mismatch - Expected {2}, found {3}.", prop.Namespace, prop.Property, expectedValue, foundValue); currentMatch = false; break; } else { this.AppendResultDescription(3, "[OK] Prop '{0}/{1}' : match - Expected {2}, found {3}.", prop.Namespace, prop.Property, expectedValue, foundValue); } } if (this.XPathProps.Count > 0 && currentMatch) { XmlDocument testedMsg = new XmlDocument(); testedMsg.LoadXml(body); foreach (ControlField field in this.XPathProps) { string expectedValue = field.Value; string foundValue = testedMsg.SelectSingleNode(field.XPath).InnerText; if (expectedValue != foundValue) { this.AppendResultDescription(3, "[KO] XPath '{0}' : mismatch - Expected {1}, found {2}.", field.XPath, expectedValue, foundValue); currentMatch = false; break; } else { this.AppendResultDescription(3, "[OK] XPath '{0}' : match - Expected {1}, found {2}.", field.XPath, expectedValue, foundValue); } } } if (currentMatch) { // Implement copy here this.AppendResultDescription(2, "Matching message found : instance {0}, message {1}", tempInstance.ID, btsMsg.MessageID); foreach (IBaseMessage processMessage in tempInstance.Messages) { MultipartMessageDefinition tempMessage = MultipartMessageManager.GenerateFromMessage(processMessage); tempMessage.Description = "Message from instance:" + tempInstance.ID.ToString(); this.FoundMessages.Add(tempMessage); } this.Result = StepResult.OK; } } } } } } if (this.FoundMessages.Count == 0) { this.AppendResultDescription(1, "No matching instance found!"); this.Result = StepResult.Error; } return(this.Result == StepResult.OK); }
public Samples() { _operations = new BizTalkOperations(); }
public void ProcessInstance(BizTalkOperations operations, List <ControlProperty> contextProps, List <ControlField> xpathProps, string processName, AppendResultDescriptionHandler writeLog) { OrchestrationInstance instance = null; StringWriter log = new StringWriter(); log.WriteLine(" Analysing instance of '{0}'", tempInstance.ServiceType); if (tempInstance.ServiceType.StartsWith(processName)) { log.WriteLine(" [OK] Service Type match : {0}", processName); foreach (var rawMessage in tempInstance.Messages) { if (rawMessage.GetType() == typeof(BizTalkMessage)) { bool currentMatch = true; BizTalkMessage btsMsg = (BizTalkMessage)rawMessage; #region Test context and XPath foreach (ControlProperty prop in contextProps) { string expectedValue = prop.Value; string foundValue = (string)btsMsg.Context.Read( prop.Property, prop.Namespace); if (expectedValue != foundValue) { log.WriteLine(" [KO] Prop '{0}/{1}' : mismatch - Expected {2}, found {3}.", prop.Namespace, prop.Property, expectedValue, foundValue); currentMatch = false; break; } else { log.WriteLine(" [OK] Prop '{0}/{1}' : match - Expected {2}, found {3}.", prop.Namespace, prop.Property, expectedValue, foundValue); } } if (xpathProps.Count > 0 && currentMatch) { string body = string.Empty; using (StreamReader streamReader = new StreamReader(btsMsg.BodyPart.Data)) { body = streamReader.ReadToEnd(); } XmlDocument testedMsg = new XmlDocument(); testedMsg.LoadXml(body); foreach (ControlField field in xpathProps) { string expectedValue = field.Value; XmlNode foundValueNode = testedMsg.SelectSingleNode(field.XPath); if (foundValueNode != null) { string foundValue = testedMsg.SelectSingleNode(field.XPath).InnerText; if (expectedValue != foundValue) { log.WriteLine(" [KO] XPath '{0}' : mismatch - Expected {1}, found {2}.", field.XPath, expectedValue, foundValue); currentMatch = false; break; } else { log.WriteLine(" [OK] XPath '{0}' : match - Expected {1}, found {2}.", field.XPath, expectedValue, foundValue); } } else { log.WriteLine(" [KO] XPath '{0}' : returned no value.", field.XPath); currentMatch = false; break; } } } #endregion if (currentMatch) { instance = tempInstance; log.WriteLine(" Matching service instance found : {0}", instance.ID); this.AddToContext(instance); try { log.WriteLine(" Waiting for instance to finish..."); bool loop = true; OrchestrationInstance waitInstance = null; while (loop) { while (instance.InstanceStatus != InstanceStatus.Completed && instance.InstanceStatus != InstanceStatus.Dehydrated && instance.InstanceStatus != InstanceStatus.Suspended && instance.InstanceStatus != InstanceStatus.SuspendedAll && instance.InstanceStatus != InstanceStatus.SuspendedNotResumable && instance.InstanceStatus != InstanceStatus.Terminated) { System.Threading.Thread.Sleep(5000); waitInstance = (OrchestrationInstance)operations.GetServiceInstance(instance.ID); instance = waitInstance; } loop = this.ProcessStopped(instance); if (loop) { System.Threading.Thread.Sleep(2000); waitInstance = (OrchestrationInstance)operations.GetServiceInstance(instance.ID); instance = waitInstance; } } } catch { } writeLog(0, log.ToString()); break; } else { writeLog(0, log.ToString()); } } } } }
//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); }
public override bool Execute() { if (string.IsNullOrEmpty(_applicationName)) { base.Log.LogError("Application property must be set"); return(false); } const int MaxRetries = 3; bool success = true; int terminatedServiceCount = 0; bool removeAll = (_applicationName.Trim() == "*"); base.Log.LogMessage( MessageImportance.Normal, "Attempting to terminate all service instances for BizTalk app '{0}'...", removeAll ? "[ALL APPS]" : _applicationName); for (int retryCount = 0; retryCount < MaxRetries; retryCount++) { success = true; // Create a new BizTalkOperations instance each time to avoid potential caching issues using (BizTalkOperations operations = new BizTalkOperations()) { // Get all service instances in the message box. // This is terribly inefficient -- BizTalkOperations has a way to directly query and filter by app, but the classes are Internal. // Could use reflection to call it anyway, but risks compatibility across BizTalk releases. foreach (Instance instance in operations.GetServiceInstances()) { MessageBoxServiceInstance mbsi = instance as MessageBoxServiceInstance; if (mbsi == null) { continue; } // Only terminate if the application matches the one we are interested in. "*" will match all apps. bool removeThisInstance = (removeAll || (string.Compare(mbsi.Application, _applicationName, true) == 0)); bool running = ((mbsi.InstanceStatus & InstanceStatus.RunningAll) != InstanceStatus.None); bool suspended = ((mbsi.InstanceStatus & InstanceStatus.SuspendedAll) != InstanceStatus.None); if (removeThisInstance && (running || suspended)) { CompletionStatus status = operations.TerminateInstance(mbsi.ID); if (status != CompletionStatus.Succeeded) { if (instance.Class == ServiceClass.RoutingFailure) { this.Log.LogMessage(MessageImportance.Low, "Could not terminate routing failure {0}. It was probably terminated by a linked instance.", mbsi.ID); } else { if (retryCount == MaxRetries - 1) { this.Log.LogError("Could not terminate instance {0}. Status is {1}.", mbsi.ID, status.ToString()); } success = false; } } else { terminatedServiceCount++; } } } } if (success) { break; } } base.Log.LogMessage( MessageImportance.Normal, "Terminated {0} service instances for BizTalk app '{1}'.", terminatedServiceCount, removeAll ? "[ALL APPS]" : _applicationName); return(success); }
public DataTable RetrieveAllMessages(string messageStatus, StringCollection applicationList, int maxLimit) { DataTable dt = new DataTable(); BizTalkOperations btOperations = new BizTalkOperations(); int messageCounter = 0; //// define the table's schema dt.Columns.Add(new DataColumn("MessageID", typeof(string))); dt.Columns.Add(new DataColumn("Status", typeof(string))); dt.Columns.Add(new DataColumn("InstanceID", typeof(string))); dt.Columns.Add(new DataColumn("CreationTime", typeof(DateTime))); dt.Columns.Add(new DataColumn("Application", typeof(string))); dt.Columns.Add(new DataColumn("HostName", typeof(string))); if (btOperations != null) { // Loop and get the service instances foreach (MessageBoxServiceInstance serviceInstance in btOperations.GetServiceInstances()) { if (serviceInstance.Application != null && (applicationList.Contains(serviceInstance.Application))) { foreach (BizTalkMessage msg in serviceInstance.Messages) { if (messageCounter < maxLimit) { DataRow dr = dt.NewRow(); dr[0] = msg.MessageID; dr[1] = msg.InstanceStatus; dr[2] = msg.InstanceID.ToString(); dr[3] = msg.CreationTime.ToString(); dr[4] = serviceInstance.Application; dr[5] = msg.HostName; dt.Rows.Add(dr); messageCounter++; } else { break; } } } } } return dt; }
public BizTalkObject(string serverName) { this._BizTalkOperations = new BizTalkOperations(mgmtDbServer: serverName, mgmtDbName: MANAGEMENTDBNAME); this._TrackingDatabase = new TrackingDatabase(dbServer: serverName, dbName: TRACKINGDBNAME); }
public Extractor(Settings settings) { this._settings = settings; this._btsOps = new BizTalkOperations(settings.BizTalkMgmtHost, settings.BizTalkMgmtDb); this._trackingDatabase = new TrackingDatabase(settings.BizTalkDTAHost, settings.BizTalkDTADb); }
public BizTalkMessage RetrieveBiztalkMessage(string messageId) { // Converts the Collection for Connection String // NameValueCollection collection = ConvertStringToNameValueCollection(ConfigurationManager.AppSettings["BCC.BIZTALK_CONNECTION"]); BizTalkOperations operations = new BizTalkOperations(); IEnumerable messages = operations.GetMessages(); try { foreach (BizTalkMessage message in messages) { if (messageId.Equals(message.MessageID.ToString())) { return message; } } } catch (Exception e) { throw e; } return null; }
private void btnSearch_Click(object sender, EventArgs e) { this.dgMessages.Rows.Clear(); List <ControlProperty> contextProps = new List <ControlProperty>(); List <string> serviceNames = new List <string>(); foreach (DataGridViewRow dr in this.dgProps.Rows) { if (dr.Cells[0].Value != null) { //ControlProperty cp = new ControlProperty(); //cp.Namespace = (string)dr.Cells[1].Value; //cp.Property = (string)dr.Cells[0].Value; //cp.Value = (string)dr.Cells[2].Value; //contextProps.Add(cp); serviceNames.Add((string)dr.Cells[0].Value); } } string entityConnectionStr = String.Empty; this.testConnection(out entityConnectionStr, false); using (BizTalkDTADbEntities btsDTA = new BizTalkDTADbEntities(entityConnectionStr)) { TrackingDatabase dta = new TrackingDatabase(this.txtDTAServerName.Text, this.txtDTADBName.Text); BizTalkOperations operations = new BizTalkOperations(this.txtDTAServerName.Text, this.txtMgmtDBName.Text); var msgIds = from mioe in btsDTA.dta_MessageInOutEvents join si in btsDTA.dta_ServiceInstances on mioe.uidServiceInstanceId equals si.uidServiceInstanceId join s in btsDTA.dta_Services on si.uidServiceId equals s.uidServiceId join pn in btsDTA.dta_PortName on mioe.nPortId equals pn.nPortId join sn in btsDTA.dta_SchemaName on mioe.nSchemaId equals sn.nSchemaId where mioe.dtTimestamp > this.dtFrom.Value && mioe.dtTimestamp < this.dtTo.Value && serviceNames.Contains(s.strServiceName) orderby mioe.dtInsertionTimeStamp descending select new tempMsgInfo { strServiceName = s.strServiceName , uidMessageInstanceId = mioe.uidMessageInstanceId , strPortName = pn.strPortName , dtTimestamp = mioe.dtTimestamp , nStatus = mioe.nStatus , strSchemaName = sn.strSchemaName }; ControlProperty tempCP = contextProps.Find(cp => cp.Namespace == BizWTF.Core.Entities.BTSProperties.messageType.Name.Namespace && cp.Property == BizWTF.Core.Entities.BTSProperties.messageType.Name.Name); if (tempCP != null) { msgIds = msgIds.Where(rec => rec.strSchemaName == tempCP.Value); } /// Looping through all the messages in order to identify the one we are looking for foreach (var msg in msgIds.Take(Int32.Parse(this.txtMaxRecord.Text))) { bool match = MatchingPartInfo.PerformMessageLookup(msg.uidMessageInstanceId, contextProps, new List <ControlField>(), dta, operations); if (match) { string status = String.Empty; switch (msg.nStatus) { case 0: status = "Receive"; break; case 1: status = "Send"; break; case 5: status = "Transmission Failure"; break; default: status = "?"; break; } this.dgMessages.Rows.Add(status, msg.strServiceName, msg.strPortName, msg.strSchemaName, msg.dtTimestamp, msg.uidMessageInstanceId); } } } }
public DataTable EnumerateAllArtifacts() { DataTable dt = new DataTable(); DataRow dr = null; bceExplorer = new BtsCatalogExplorer(); //Edit the following connection string to point to the correct database and server bceExplorer.ConnectionString = bizTalkMgmtDbConnectionString; BtsAssemblyCollection btsAssemblyCollection = bceExplorer.Assemblies; BizTalkOperations btOperations = new BizTalkOperations(); // define the table's schema dt.Columns.Add(new DataColumn("Name", typeof(string))); dt.Columns.Add(new DataColumn("Status", typeof(string))); dt.Columns.Add(new DataColumn("Data", typeof(string))); try { // Enumerate all orchestrations foreach (BtsAssembly btsAssembly in btsAssemblyCollection) { dr = dt.NewRow(); dr["Name"] = btsAssembly.Name; dr["Status"] = ""; dr["Data"] = "Assembly:" + btsAssembly.DisplayName + ":" + btsAssembly.Version + ":" + btsAssembly.PublicKeyToken; dt.Rows.Add(dr); foreach (BtsOrchestration btsOrchestration in btsAssembly.Orchestrations) { // create the rows dr = dt.NewRow(); dr["Name"] = btsOrchestration.FullName; dr["Status"] = btsOrchestration.Status.ToString(); dr["Data"] = "Orchestration:" + btsOrchestration.BtsAssembly.Name + ":v" + btsOrchestration.BtsAssembly.Version + ":" + btsOrchestration.BtsAssembly.PublicKeyToken; dt.Rows.Add(dr); // Enumerate ports and operations foreach (OrchestrationPort port in btsOrchestration.Ports) { dr = dt.NewRow(); dr["Name"] = port.Name; dr["Status"] = ""; dr["Data"] = "Port Type:" + port.PortType.FullName + ":" + port.PortType.AssemblyQualifiedName; dt.Rows.Add(dr); foreach (PortTypeOperation operation in port.PortType.Operations) { dr = dt.NewRow(); dr["Name"] = operation.Name; dr["Status"] = ""; dr["Data"] = "PortTypeOperation:" + operation.Type; dt.Rows.Add(dr); } } // Enumerate used roles foreach (Role role in btsOrchestration.UsedRoles) { dr = dt.NewRow(); dr["Name"] = role.Name; dr["Status"] = ""; dr["Data"] = "ServiceLinkType:" + role.ServiceLinkType; dt.Rows.Add(dr); foreach (EnlistedParty enlistedparty in role.EnlistedParties) { dr = dt.NewRow(); dr["Name"] = enlistedparty.Party.Name; dr["Status"] = ""; dr["Data"] = "Data:" + enlistedparty.Party.CustomData; dt.Rows.Add(dr); } } } } foreach (SendPort sp in bceExplorer.SendPorts) { dr = dt.NewRow(); dr["Name"] = sp.Name; dr["Status"] = sp.Status.ToString(); if (sp.PrimaryTransport != null) { dr["Data"] = "Send Port:" + sp.PrimaryTransport.Address + ":" + sp.PrimaryTransport.TransportType.Name; } dt.Rows.Add(dr); } foreach (ReceivePort rp in bceExplorer.ReceivePorts) { foreach (ReceiveLocation rl in rp.ReceiveLocations) { // create the rows dr = dt.NewRow(); dr["Name"] = rp.Name; dr["Status"] = (rl.Enable ? "Enabled" : "Disabled"); dr["Data"] = "Receive Location:" + rl.Name; dt.Rows.Add(dr); } } // Host instances ManagementClass objHostSettingClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostInstance", null); foreach (ManagementObject objShare in objHostSettingClass.GetInstances()) { dr = dt.NewRow(); dr["Name"] = objShare.Properties["RunningServer"].Value.ToString(); string status = objShare.Properties["ServiceState"].Value.ToString(); dr["Status"] = ("4".Equals(status) ? "Running" : "Stopped"); dr["Data"] = "Host:" + objShare.Properties["HostName"].Value.ToString(); dt.Rows.Add(dr); } if (btOperations != null) { // Loop and get the service instances foreach (MessageBoxServiceInstance serviceInstance in btOperations.GetServiceInstances()) { if (serviceInstance.Application != null ) { foreach (BizTalkMessage msg in serviceInstance.Messages) { dr = dt.NewRow(); dr["Name"] = serviceInstance.Application.ToUpper(); dr["Status"] = msg.InstanceStatus; dr["Data"] = "Message:" + msg.MessageID + ":" + msg.InstanceID.ToString() + ":" + msg.CreationTime.ToString(); dt.Rows.Add(dr); } } } } foreach (Transform transform in bceExplorer.Transforms) { dr = dt.NewRow(); dr["Name"] = transform.FullName; dr["Status"] = ""; dr["Data"] = "Map:" + transform.SourceSchema.FullName + ":" + transform.TargetSchema.FullName; dt.Rows.Add(dr); } } catch (Exception exception) { throw exception; } return dt; }
public static List <MatchingPartInfo> GetMatchingPartInfo(BizTalkDTADbEntities btsDTA, TrackingDatabase dta, BizTalkOperations operations, List <ControlProperty> contextProps, List <ControlField> xpathProps, string processName, string sourceContextProperty) { DateTime startDate = DateTime.Now.Subtract(new TimeSpan(BTSTestContext.MaxHistory, 0, 0, 0)); List <MatchingPartInfo> info = new List <MatchingPartInfo>(); if (!String.IsNullOrEmpty(sourceContextProperty)) { Logger.CurrentLogger.Write(1, "Getting service instance info according to cached property '{0}'", System.Diagnostics.EventLogEntryType.Information, sourceContextProperty); //Guid serviceInstanceID = (Guid)BTSTestContext.Params[sourceContextProperty]; //List<Guid> serviceInstanceIDs = (List<Guid>)BTSTestContext.Params[sourceContextProperty]; List <OrchestrationInstance> serviceInstanceIDs = (List <OrchestrationInstance>)BTSTestContext.Params[sourceContextProperty]; foreach (OrchestrationInstance serviceInstance in serviceInstanceIDs) { Logger.CurrentLogger.Write(2, "(Value = '{0}')", System.Diagnostics.EventLogEntryType.Information, serviceInstanceIDs[0]); /// Query the DTA Db to retrieve all messages related to /// the type of process we are looking for. var msgIds = from s in btsDTA.dta_Services join si in btsDTA.dta_ServiceInstances on s.uidServiceId equals si.uidServiceId //join ss in btsDTA.dta_ServiceState on si.nServiceStateId equals ss.nServiceStateId join me in btsDTA.dta_MessageInOutEvents on si.uidServiceInstanceId equals me.uidServiceInstanceId where s.strServiceName == processName && si.uidServiceInstanceId == serviceInstance.ID orderby me.dtInsertionTimeStamp descending select new MatchingPartInfo { ServiceId = s.uidServiceId, txtSymbol = s.txtSymbol, ServiceInstanceId = si.uidServiceInstanceId, MessageInstanceId = me.uidMessageInstanceId, Status = (ServiceStatus)si.nServiceStateId }; if (msgIds.Count() == 0) { info = GetMatchingPartInfo(btsDTA, dta, operations, contextProps, xpathProps, processName, null); } else { info.AddRange(msgIds.ToList <MatchingPartInfo>()); } } } else { Logger.CurrentLogger.Write(1, "Looking for service instance into DTA Db", System.Diagnostics.EventLogEntryType.Information); /// Query the DTA Db to retrieve all messages related to /// the type of process we are looking for. var msgIds = from s in btsDTA.dta_Services join si in btsDTA.dta_ServiceInstances on s.uidServiceId equals si.uidServiceId join me in btsDTA.dta_MessageInOutEvents on si.uidServiceInstanceId equals me.uidServiceInstanceId where s.strServiceName == processName && si.dtStartTime > startDate orderby me.dtInsertionTimeStamp descending select new MatchingPartInfo { ServiceId = s.uidServiceId, ServiceName = s.strServiceName, txtSymbol = s.txtSymbol, ServiceInstanceId = si.uidServiceInstanceId, MessageInstanceId = me.uidMessageInstanceId, Status = (ServiceStatus)si.nServiceStateId }; /// Looping through all the messages in order to identify the one we are looking for Logger.CurrentLogger.Write(2, "Retrieved {0} messages", System.Diagnostics.EventLogEntryType.Information, msgIds.Count()); foreach (MatchingPartInfo part in msgIds) { bool match = PerformMessageLookup(part.MessageInstanceId, contextProps, xpathProps, dta, operations); if (match) { Logger.CurrentLogger.Write(2, "[OK] Message match", System.Diagnostics.EventLogEntryType.Information); info.Add(part); //break; } } } return(info); }
public static CompletionStatus Terminate(string instanceID) { BizTalkOperations bizOps = new BizTalkOperations(GlobalProperties.MgmtDBServer, GlobalProperties.MgmtDBName); return(bizOps.TerminateInstance(new Guid(instanceID))); }
public void TerminateMessage(string instanceID) { BizTalkOperations btOperations = new BizTalkOperations(); btOperations.TerminateInstance(new Guid(instanceID)); }
public BtsOrchestration GetOrchestrationByName(string orchestrationName, string applicationName) { bceExplorer = new BtsCatalogExplorer(); //Edit the following connection string to point to the correct database and server bceExplorer.ConnectionString = bizTalkMgmtDbConnectionString; BtsAssemblyCollection btsAssemblyCollection = bceExplorer.Assemblies; BizTalkOperations btOperations = new BizTalkOperations(); try { foreach (BtsAssembly btsAssembly in btsAssemblyCollection) { foreach (BtsOrchestration btsOrchestration in btsAssembly.Orchestrations) { // Show only HUB related orchestrations. if ((applicationName.ToUpper()).Equals(btsOrchestration.BtsAssembly.Application.Name.ToUpper()) && orchestrationName.Equals(btsOrchestration.FullName)) { return btsOrchestration; } } } } catch (Exception e) { throw e; } return null; }