I am using the Schematron.net nuget package and I want to know if it's possible to get the output of a call to Validate to give the results in a structured format that I can then process. My existing solution relies on a try catch block and the assertion failures are all returned as the message within the exception as the error message. Is there a way to get this information as XML? I have seen this post which asks a similar question, but the answers don't refer to the Schematron.net implementation.
My code looks like this:
try
{
var bookValidator = new Validator();
bookValidator.AddSchema("book.xsd");
bookValidator.Validate("book.xml");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
It's pretty simple actually. I just realised that passing a suitable enumeration of OutputFormatting to the Validator constructor allows me to control the format of the message in the exception, like so:
try
{
//OutputFormatting is a public enum from the Schematron library. Valid values include boolean, default, Log, simple and XML.
OutputFormatting format = OutputFormatting.XML;
var bookValidator = new Validator(format);
bookValidator.AddSchema("book.xsd");
bookValidator.Validate("book.xml");
}
catch (Exception ex)
{
//ex.Message will now be in XML format and can be processed however I want!
Console.WriteLine(ex.Message);
}
And there's your structured results. I hope that helps someone as it wasn't obvious to me.
Related
I think this is a rather straightforward issue, but I don't have much information to go on. I have this code to try and read a DWG file into memory, so that I can read and manipulate the data. I am getting an error that the parameter "Value" cannot be null.
While that does let me know something is wrong, how do I proceed in figuring out what exactly this value is so that I can fix it?
string basePath = Path.Combine($"{Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)}", "temp");
string fileName = Path.Combine(basePath, "ATemplateV0.2.dwg");
if(File.Exists(fileName))
{
DwgReader dwgReader = new(fileName);
try
{
DxfModel dxfModel = dwgReader.Read();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
WW CadLib needs a license to run, if you don't have one that may be causing the error.
The code example in the answer from #b166er is referring to an Open Source library called ACadSharp to read dwg/dxf files from one of my repositories.
Right now you can use a pre-release version of it in Nuget
You can pass a onNotification event into the DwgReader constructor that might give you more information. Examples here: https://github.com/DomCR/ACadSharp/blob/master/ACadSharp.Examples/Program.cs
Blank project repo with problematic code
I have the following code for querying all the supported Audio codec following this article using CodecQuery.FindAllAsync
try
{
var query = new CodecQuery();
var queryResult = await query.FindAllAsync(CodecKind.Audio, CodecCategory.Encoder, "");
var subTypes = queryResult
.SelectMany(q => q.Subtypes)
.ToHashSet();
// Other codes
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw;
}
As the documentation mentioned,
To specify that all codecs of the specified kind and category should be returned, regardless of what media subtypes are supported, specify an empty string ("") or null for this parameter.
For empty string "", it works for CodecKind.Video but not for Audio (for both CodecCategory of Encoder or Decoder). If I specify a subtype, then it does not crash, for example:
var queryResult = await query.FindAllAsync(CodecKind.Audio, CodecCategory.Encoder, CodecSubtypes.AudioFormatMP3);
What is strange about that is that even though I have a try/catch with generic Exception, the app just crashes through that one and show this instead:
I have tried restarting Windows, uninstall the UWP app and make a clean build. What is happening? How do I query all available audio codecs?
Update: after changing Debug setting, I could trace the error message:
Unhandled exception at 0x00007FFDCE5FD759 (KernelBase.dll) in ******.exe: 0xC0000002: The requested operation is not implemented.
After my testing, the content of this document is correct. When I set “” for the third parameter to find all audio codecs, the code works well. So there is not an error in this document.
You could choose the Debug options, and change Debugger type from Managed Only to Mixed. It won't fix your exception, but you can trace it with the debugger. You could refer to this reply to get more information.
I have an text file which has some settings parameters for my project. My desktop layer reads this file. Therewithal , web layer's project read from from Server's MapPath.
FileStream has no operator to bypass an exception.I have tried to Exists control. But , i just need to bypass FileNotFoundException.
Place the code in a try catch.
try
{
//read
}
catch(FileNotFoundException ex)
{
//do logging for this silent catch
Console.WriteLine(ex);
}
How about this,
if (File.Exists(path)
{
// read file,
}
Another way,
if (File.Exists(path)
{
try
{
// read file,
}
catch (Some other exception related to file, read access violation, etc.)
{
handle exception,
}
}
How about checking the file exists or not?
if so, you can prevent throwing FileNotFoundException.
[Can not provide complete solution/feedback as we aren't sure about your actual implementation]
If(!File.Exists(<path_to_file>)
return;
// continue doing the rest only if file exists
Hope this helps. let us know if require more clarifications. It Would be nice if you could post your method implementation or at least a pseudo code for us to understand the actual problem you trying to solve.
Cheers,
I'm having some trouble understanding and getting the search contract to work in my Store app. I have been unable to find any sort of documentation or guide that explains the structure of using the contract. (I've looked at the quickstarts on MSDN, the Search Contract sample and the build video, but that only really deals with javascript)
So far I've been able to run a query and get a list (of Custom Objects) into my search contract page, and from there I try to assign that to defaultviewmodel.results, but no matter what query I type nothing shows up I on the page. Is there something else I need to set?
What I have so far is as follows (excerpts):
App.xaml.cs
protected override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
{
SearchCharmResultsPage.Activate(args.QueryText, args.PreviousExecutionState);
SearchCharmResultsPage.ProcessSearchQuery(args.QueryText);
}
public async static void ProcessSearchQuery(string queryString)
{
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("recipeCustomObject Debug.WriteLine("Database exists, connecting");
SQLiteAsyncConnection connection = new SQLiteAsyncConnection("CustomObject_db");
List<CustomObject> resultsList = new List<CustomObject>();
string query = "SELECT * FROM CustomObjectDB";
resultsList = await connection.QueryAsync<RecipeRecord>(query);
}
catch (FileNotFoundException fnfExc)
{
Debug.WriteLine("FNFEXC: " + fnfExc.ToString());
}
}
I think it is possible that here lies the problem, though I'm not sure if it is, or how to change it.
the resultsList list is created here, but because the method it asynchronous, I can't return from the method. Because of this I'm guess that when I try to assign this.DefaultViewModel[Results] = resultsList; in the LoadStateMethod, the object doesn't exist (thought the program throws no error). When I try to add the same line in the ProcessSearchQuery method, i'm told that this is not valid in a static method, but I think I need the method to be static? My problem might just be a fundamental logic error?
Finally got it! found the solution here: http://jeffblankenburg.com/2012/11/06/31-days-of-windows-8-day-6-search-contract
For those looking for an answer in the future, the key is to make sure you have your search logic within the Filter_SelectionChanged method, which was something I wasn't doing. Look at the guide within the above link to get an idea of the structure.
Have you looked at the Search contract sample on the developer center? There's a C#/XAML version there as well.
My open source Win8 RSS Reader framework implements Search (and Share) have a look at the source and if you still got questions, I'll be happy to help http://win8rssreader.codeplex.com/
How do I get the Exception Handling Application Block (EHAB) to write the values from the Exception.Data property in the log?
try
{
// ...
}
catch (Exception ex)
{
ex.Data.Add("Hello", "World");
throw ex;
}
The exception is logged correctly, but I can’t find the added data anywhere in the log entry created by EHAB.
As far as I understand, it’s a recommended practice to add additional relevant information to the exception itself like in the above example. That’s why I’m a little surprised that EHAB doesn’t include this by default.
Can I fix this by modifying the template with the EntLib Text Formatter Template Editor (screen shot below)? I can't find any info on the various "tokens" provided, but I assume the answer is hidden somewhere with them.
Text Formatter Template Editor http://img195.imageshack.us/img195/6614/capturegmg.png
Or do I really need to implement my own custom Text Formatter to accomplish this?
EDIT/UPDATE:
I do this in my Global.asax.cs in order to avoid having to add the HandleException method call everywhere in my code:
using EntLib = Microsoft.Practices.EnterpriseLibrary;
using System;
namespace MyApp
{
public class Global : System.Web.HttpApplication
{
protected void Application_Error(object sender, EventArgs e)
{
// I have an "All Exceptions" policy in place...
EntLib.ExceptionHandling.ExceptionPolicy.HandleException(Server.GetLastError(), "All Exceptions");
// I believe it's the GetLastError that's somehow returning a "lessor" exception
}
}
}
It turns out this is not the same as this (which works fine, and essentially solves my problem):
try
{
// ...
}
catch (Exception ex)
{
ex.Data.Add("Hello", "World");
bool rethrow = ExceptionPolicy.HandleException(ex, "Log Only Policy");
throw ex;
}
Going through all the code and adding try-catch's with a HandleException call just seems ... well, stupid.
I guess my problem really is how to use EHAB correctly, not configuration.
Any suggestion on how I can properly log all exceptions on a "global level" in an ASP.NET web application??
You shouldn't have to create your own formatter.
Each item in the Data IDictionary on the Exception object is added to the ExtendedProperties Dictionary of the LogEntry object and is logged (if specified by the formatter).
The Extended Properties:{dictionary({key} - {value})} config snippet should log all key/value pairs in the extended properties dictionary. If you want to log just one item from the collection you can use "keyvalue". In your example it would be something along the lines of:
Hello Key: {keyvalue(Hello)}
I modified the ExceptionHandlingWithLoggingQuickStart to add Data.Add("Hello", "World") and I see "Extended Properties: Hello - World" at the end of the Event Log entry. So it is working.
If you aren't seeing that behavior, you need to ensure:
That your exception with the Data items added is passed in to ExceptionPolicy.HandleException
That the policy specified in the HandleException method is configured for logging with a LoggingExceptionHandler in the configuration
That the formatter that is specified in the LoggingConfiguration is configured to support ExtendedProperties
If you can't see what the problem is try comparing what you have with what is in the QuickStart. If it's still not working, post your code and your config.
UPDATE:
If you are going to handle Application_Error in the global.asax then you will be receiving an HttpUnhandledException since the page did not handle the error. You can retrieve the Exception you are interested in by using the InnerException Property; the InnerException will contain the original Exception (unless it is in that exception's InnerException :) ). Alternately, you can use Server.GetLastError().GetBaseException() to retrieve the exception which is the root cause.