本文整理汇总了C#中Context.LogException方法的典型用法代码示例。如果您正苦于以下问题:C# Context.LogException方法的具体用法?C# Context.LogException怎么用?C# Context.LogException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Context
的用法示例。
在下文中一共展示了Context.LogException方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendRequestData
/// <summary>
/// Helper method to execute an HTTP request-response
/// </summary>
///
/// <param name="url">The HTTP Url</param>
/// <param name="payload">Byte array conatining the request data</param>
/// <param name="requestTimeout">The request timeout value</param>
/// <param name="context">The BizUnit context object which holds state and is passed between test steps</param>
/// <returns>response MemoryStream</returns>
public static MemoryStream SendRequestData(String url, byte[] payload, int requestTimeout, Context context)
{
WebResponse result = null;
var response = new MemoryStream();
Stream responseStream = null;
Stream requestStream = null;
try
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.Timeout = requestTimeout;
req.ContentType = "text/xml; charset=\"utf-8\"";
req.ContentLength = payload.Length;
requestStream = req.GetRequestStream();
requestStream.Write( payload, 0, payload.Length );
result = req.GetResponse();
responseStream = result.GetResponseStream();
const int bufferSize = 4096;
var buffer = new byte[bufferSize];
int count = responseStream.Read( buffer, 0, bufferSize );
while (count > 0)
{
response.Write(buffer, 0, count);
count = responseStream.Read(buffer, 0, bufferSize );
}
response.Seek(0, SeekOrigin.Begin);
}
catch(Exception e)
{
context.LogException( e );
throw;
}
finally
{
if ( null != result )
{
result.Close();
}
if ( null != responseStream )
{
responseStream.Close();
}
if ( null != requestStream )
{
requestStream.Close();
}
}
return response;
}
示例2: Execute
//.........这里部分代码省略.........
}
case "DataConnectionFact":
{
var fact = currentFact as DataConnectionFact;
var conn = new SqlConnection(fact.ConnectionString);
conn.Open();
var dc = new DataConnection(fact.Dataset, fact.TableName, conn);
facts[i] = dc;
break;
}
case "dataTable":
case "dataRow":
{
var fact = currentFact as DataTableFact;
var dAdapt = new SqlDataAdapter();
dAdapt.TableMappings.Add("Table", fact.TableName);
var conn = new SqlConnection(fact.ConnectionString);
conn.Open();
var myCommand = new SqlCommand(fact.Command, conn) {CommandType = CommandType.Text};
dAdapt.SelectCommand = myCommand;
var ds = new DataSet(fact.Dataset);
dAdapt.Fill(ds);
var tdt = new TypedDataTable(ds.Tables[fact.TableName]);
if (fact.Type == "dataRow")
{
var tdr = new TypedDataRow(ds.Tables[fact.TableName].Rows[0], tdt);
facts[i] = tdr;
}
else
{
facts[i] = tdt;
}
break;
}
}
i++;
}
// Execute Policy Tester
try
{
policyTester.Execute(facts, dti);
}
catch (Exception e)
{
context.LogException(e);
throw;
}
finally
{
dti.CloseTraceFile();
}
// write out all document instances passed in
foreach (object fact in facts)
{
switch (fact.GetType().Name)
{
case "TypedXmlDocument":
{
var txd = (TypedXmlDocument)fact;
context.LogData("TypedXmlDocument result: ", txd.Document.OuterXml);
Stream data = StreamHelper.LoadMemoryStream(txd.Document.OuterXml);
// Validate if configured...
// HACK: We need to prevent ExecuteValidator for /each/ TypedXmlDocument
if (txd.DocumentType == "UBS.CLAS.PoC.Schemas.INSERTS")
{
foreach (var subStep in SubSteps)
{
data = subStep.Execute(data, context);
}
}
break;
}
case "DataConnection":
{
var dc = (DataConnection)fact;
dc.Update(); // persist any changes
break;
}
case "TypedDataTable":
{
var tdt = (TypedDataTable)fact;
tdt.DataTable.AcceptChanges();
break;
}
case "TypedDataRow":
{
var tdr = (TypedDataRow)fact;
tdr.DataRow.AcceptChanges();
break;
}
}
}
}
示例3: ValidateXmlInstance
private XmlDocument ValidateXmlInstance(Stream data, Context context)
{
try
{
var settings = new XmlReaderSettings();
foreach (var xmlSchema in _xmlSchemas)
{
settings.Schemas.Add(xmlSchema.XmlSchemaNameSpace, xmlSchema.XmlSchemaPath);
}
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(data, settings);
var document = new XmlDocument();
document.Load(reader);
var eventHandler = new ValidationEventHandler(ValidationEventHandler);
document.Validate(eventHandler);
return document;
}
catch (Exception ex)
{
context.LogException(ex);
throw new ValidationStepExecutionException("Failed to validate document instance", ex, context.TestName);
}
}
示例4: ExecuteValidation
public void ExecuteValidation(Stream data, Context context)
{
MemoryStream dataToValidateAgainst = null;
try
{
try
{
dataToValidateAgainst = StreamHelper.LoadFileToStream(_comparisonDataPath);
}
catch (Exception e)
{
context.LogError("BinaryValidationStep failed, exception caugh trying to open comparison file: {0}", _comparisonDataPath);
context.LogException(e);
throw;
}
try
{
data.Seek(0, SeekOrigin.Begin);
dataToValidateAgainst.Seek(0, SeekOrigin.Begin);
if (_compareAsUtf8)
{
// Compare the streams, make sure we are comparing like for like
StreamHelper.CompareStreams(StreamHelper.EncodeStream(data, System.Text.Encoding.UTF8), StreamHelper.EncodeStream(dataToValidateAgainst, System.Text.Encoding.UTF8));
}
else
{
StreamHelper.CompareStreams(data, dataToValidateAgainst);
}
}
catch (Exception e)
{
context.LogError("Binary validation failed while comparing the two data streams with the following exception: {0}", e.ToString());
// Dump out streams for validation...
data.Seek(0, SeekOrigin.Begin);
dataToValidateAgainst.Seek(0, SeekOrigin.Begin);
context.LogData("Stream 1:", data);
context.LogData("Stream 2:", dataToValidateAgainst);
throw;
}
}
finally
{
if (null != dataToValidateAgainst)
{
dataToValidateAgainst.Close();
}
}
}
示例5: ExecuteContextLoader
public void ExecuteContextLoader(Stream data, Context context)
{
var doc = new XmlDocument();
doc.Load(data);
foreach (var xPathExpression in _xPathExpressions)
{
var contextKey = (string)xPathExpression.First;
var xpathExp = (string)xPathExpression.Second;
string val;
context.LogInfo("XmlContextLoader loading key:{0} with value:\"{1}\"", contextKey, xpathExp);
try
{
val = doc.SelectSingleNode(xpathExp).InnerText;
}
catch (Exception ex)
{
context.LogError("The XPath expression: {0}, could not be evaluated", xpathExp);
context.LogException(ex);
throw;
}
context.Add(contextKey, val);
}
}
示例6: Execute
/// <summary>
/// ITestStep.Execute() implementation
/// </summary>
/// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
public void Execute(XmlNode testConfig, Context context)
{
const string soapproxynamespace = "BizUnit.Proxy";
Stream request = null;
Stream response = null;
// Turn on shadow copying of asseblies for the current appdomain.
AppDomain.CurrentDomain.SetShadowCopyFiles();
try
{
string wsdlFile = context.ReadConfigAsString(testConfig, "WebServiceWSDLURL");
string soapMessagePath = context.ReadConfigAsString(testConfig, "MessagePayload", true);
string inputMessageTypeName = context.ReadConfigAsString(testConfig, "InputMessageTypeName", true);
string webMethod = context.ReadConfigAsString(testConfig, "WebMethod");
string serviceName = context.ReadConfigAsString(testConfig, "ServiceName");
Assembly proxyAssembly = GetProxyAssembly(wsdlFile, soapproxynamespace);
object objInputMessage = null;
if(null != inputMessageTypeName && null != soapMessagePath)
{
objInputMessage =
LoadMessage(proxyAssembly, soapproxynamespace + "." + inputMessageTypeName, soapMessagePath);
if (null != objInputMessage)
{
request = GetOutputStream(objInputMessage);
context.LogData("SOAPHTTPRequestResponseStep request data", request);
}
}
object proxy = Activator.CreateInstance(proxyAssembly.GetType(soapproxynamespace + "." + serviceName));
MethodInfo mi = proxy.GetType().GetMethod(webMethod);
context.LogInfo("SOAPHTTPRequestResponseStep about to post data from File: {0} to the Service: {1} defined in WSDL: {2}", soapMessagePath, serviceName, wsdlFile);
object outputMessage;
if (null != inputMessageTypeName && null != soapMessagePath)
{
outputMessage = mi.Invoke(proxy, new[] { objInputMessage });
}
else
{
outputMessage = mi.Invoke(proxy, null);
}
if (null != outputMessage)
{
response = GetOutputStream(outputMessage);
context.LogData("SOAPHTTPRequestResponseStep response data", response);
}
// Execute ctx loader step if present...
if (null != response)
{
context.ExecuteContextLoader(response, testConfig.SelectSingleNode("ContextLoaderStep"), true);
}
// Validate the response...
try
{
context.ExecuteValidator(response, testConfig.SelectSingleNode("ValidationStep"), true);
}
catch (Exception e)
{
throw new ApplicationException("SOAPHTTPRequestResponseStep response stream was not correct!", e);
}
}
catch(Exception ex)
{
context.LogError("SOAPHTTPRequestResponseStep Failed");
context.LogException(ex);
throw;
}
finally
{
if (null != response)
{
response.Close();
}
if (null != request)
{
request.Close();
}
}
}
示例7: Execute
/// <summary>
/// ITestStep.Execute() implementation
/// </summary>
/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
public override void Execute(Context context)
{
try
{
if (Action == OrchestrationAction.Start)
{
Start(AssemblyName, OrchestrationName, context);
}
else
{
Stop(AssemblyName, OrchestrationName, context);
}
// Delay if necessary to allow the orchestration to start/stop
if (DelayForCompletion > 0)
{
context.LogInfo("Waiting for {0} seconds before recommencing testing.", DelayForCompletion);
System.Threading.Thread.Sleep(DelayForCompletion * 1000);
}
}
catch (System.Runtime.InteropServices.COMException e)
{
context.LogException(e);
throw;
}
}
示例8: Execute
/// <summary>
/// TestStepBase.Execute() implementation
/// </summary>
/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
public override void Execute(Context context)
{
var endTime = DateTime.Now.AddMilliseconds(Timeout);
bool found = false;
string[] filelist;
int timesLogged = 0;
context.LogInfo("Searching directory: {0}, search pattern: {1}", DirectoryPath, SearchPattern);
do
{
Thread.Sleep(100);
// Get the list of files in the directory
filelist = Directory.GetFiles(DirectoryPath, SearchPattern);
if ( filelist.Length == ExpectedNumberOfFiles)
break;
} while (endTime > DateTime.Now);
context.LogInfo("Number of files found: {0}", filelist.Length);
if (filelist.Length == 0)
{
// Expecting more than one file
throw new ApplicationException(String.Format("Directory contains no files matching the pattern!"));
}
if (0 < ExpectedNumberOfFiles && filelist.Length != ExpectedNumberOfFiles)
{
// Expecting a specified number of files
throw new ApplicationException(String.Format("Directory contained: {0} files, but the step expected: {1} files", filelist.Length, ExpectedNumberOfFiles));
}
// For each file in the file list
foreach (string filePath in filelist)
{
context.LogInfo("FileReadMultipleStep validating file: {0}", filePath);
Stream fileData = StreamHelper.LoadFileToStream(filePath, Timeout);
context.LogData("File: " + filePath, fileData);
fileData.Seek(0, SeekOrigin.Begin);
// Check it against the validate steps to see if it matches one of them
foreach(var subStep in SubSteps)
{
try
{
// Try the validation and catch the exception
fileData = subStep.Execute(fileData, context);
}
catch (Exception ex)
{
context.LogException(ex);
throw;
}
}
if(DeleteFiles)
{
System.IO.File.Delete(filePath);
}
}
}
示例9: Execute
/// <summary>
/// ITestStep.Execute() implementation
/// </summary>
/// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
public void Execute(XmlNode testConfig, Context context)
{
var destinationPath = context.ReadConfigAsString(testConfig, "DestinationPath");
var rawListOfServers = context.ReadConfigAsString(testConfig, "Server");
var listOfServers = new List<string>();
listOfServers.AddRange(rawListOfServers.Split(','));
foreach (var server in listOfServers)
{
context.LogInfo("About to save the event on server: {0} to the following directory: {1}", server,
destinationPath);
ManagementScope scope;
if ((server.ToUpper() != Environment.MachineName.ToUpper()))
{
var options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true
};
scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", server), options);
}
else
{
var options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true
};
scope = new ManagementScope(@"root\cimv2", options);
}
var query = new SelectQuery("Select * from Win32_NTEventLogFile");
var searcher = new ManagementObjectSearcher(scope, query);
foreach (var logFileObject in searcher.Get())
{
var methodArgs = new object[] { destinationPath + @"\" + server + ".evt" };
try
{
((ManagementObject)logFileObject).InvokeMethod("BackupEventLog", methodArgs);
}
catch (Exception e1)
{
//access denied on method call if scope path referes to the same
context.LogException(e1);
throw;
}
}
}
}
示例10: CallWebMethod
private Stream CallWebMethod(
Stream requestData,
string serviceUrl,
string action,
string username,
string password,
Context ctx )
{
try
{
Stream responseData;
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.UseDefaultWebProxy = true;
var epa = new EndpointAddress(new Uri(serviceUrl));
ChannelFactory<genericContract> cf = null;
genericContract channel;
Message request;
Message response;
string responseString;
try
{
cf = new ChannelFactory<genericContract>(binding, epa);
cf.Credentials.UserName.UserName = username;
cf.Credentials.UserName.Password = password;
cf.Open();
channel = cf.CreateChannel();
using (new OperationContextScope((IContextChannel)channel))
{
XmlReader r = new XmlTextReader(requestData);
request = Message.CreateMessage(MessageVersion.Soap11, action, r);
foreach (var header in _soapHeaders)
{
MessageHeader messageHeader = MessageHeader.CreateHeader(header.HeaderName, header.HeaderNameSpace, header.HeaderInstance);
OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
}
response = channel.Invoke(request);
string responseStr = response.GetReaderAtBodyContents().ReadOuterXml();
ctx.LogXmlData("Response", responseStr);
responseData = StreamHelper.LoadMemoryStream(responseStr);
}
request.Close();
response.Close();
cf.Close();
}
catch (CommunicationException ce)
{
ctx.LogException(ce);
if (cf != null)
{
cf.Abort();
}
throw;
}
catch (TimeoutException te)
{
ctx.LogException(te);
if (cf != null)
{
cf.Abort();
}
throw;
}
catch (Exception e)
{
ctx.LogException(e);
if (cf != null)
{
cf.Abort();
}
throw;
}
return responseData;
}
catch (Exception ex)
{
ctx.LogException(ex);
throw;
}
}