XamlReader.Load is throwing System.Windows.Markup.XamlParseException - c#

What could be wrong with the following:
<Run FontWeight=\"Bold\" Foreground=\"#FF0000FF\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\"><Run.TextDecorations><TextDecoration Location=\"Underline\" /></Run.TextDecorations>046/98 5802007513 \r</Run>
While similar others are loaded fine by the XamlReader.Load, this throws following exception:
"A first chance exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll
Additional information: Invalid character in the given encoding. Line
1, position 233."
Code to replicate the issue:
using System;
using System.IO;
using System.Text;
using System.Windows.Markup;
namespace XamlTesting
{
class Program
{
static void Main(string[] args)
{
String str = "<Run FontWeight=\"Bold\" Foreground=\"#FF0000FF\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\"><Run.TextDecorations><TextDecoration Location=\"Underline\" /></Run.TextDecorations>046/98 5802007513 \r</Run>";
Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(str));
try
{
var temp = XamlReader.Load(s);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}

Calling XamlReader.Parse instead of XamlReader.Load doesn't throw exception "XamlParseException" with the same input, however I don't know what's the difference and how it is working.
static void Main(string[] args)
{
String str = "<Run FontWeight=\"Bold\" Foreground=\"#FF0000FF\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\"><Run.TextDecorations><TextDecoration Location=\"Underline\" /></Run.TextDecorations>046/98 5802007513 \r</Run>";
try
{
var temp = XamlReader.Parse(str);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

use " (Double quote) instead of \ as show below
String str = #"http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xml:space=""preserve"">046/98 5802007513 \r";

Related

How to get exact stack trace line number in Exception Handling

I am trying to understand Exception handling in C#. I have a sample program.
class Program
{
static void Main(string[] args)
{
Program p = new Program();
try
{
p.Method2();
}
catch (Exception ex)
{
Console.WriteLine("Enter into Main()");
Console.WriteLine("The original Stack Trace Line No 47 is missing in current Stack Trace.");
Console.WriteLine("------------------------------------------------------------------------");
Console.Write(ex.StackTrace.ToString());
Console.ReadKey();
}
}
private void Method2()
{
try
{
Method1();
}
catch (Exception ex)
{
//throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
throw;
}
}
private void Method1()
{
try
{
throw new Exception("Inside Method1");
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex);
throw;
}
}
}
I would like to see the original stack trace line number in the main method(which I can see in the catch block of the Method1). Is this possible?
I'm on .NET Core, but I think it works the same for .NET Framework. I copied your code, and just added line number as comments in the interesting lines:
private void Method1()
{
try
{
throw new Exception("Inside Method1"); // line 42
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex);
throw; // line 47
}
}
The code above print the following:
at Main.Program.Method1() in C:...\Main.cs:line 42
in both Console.WriteLine in Method1 and Main.
If I replace throw by throw ex in the catch block, then it prints:
at Main.Program.Method1() in C:...\Main.cs:line 42
in Console.WriteLine in Method1, and
at Main.Program.Method1() in C:...\Main.cs:line 47
in Console.WriteLine in Main, because the exception is rethrown, so the line number change.
All of that to say that your code works as you expect; so the code you are executing is maybe not the one you compile :-)
You can make use of the StackTrace class to get more information like ClassName , LineNumber etc. Eg below
catch (Exception ex)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
}
Edit
An even better way to do is, create a concrete place like this where you can just pass the Exception to get all the information you need.
public static AdditionalInformation GetStackTrace(Exception exception)
{
var trace = new StackTrace(exception, true);
var reflectedType = trace.GetFrame(0).GetMethod().ReflectedType;
var additionalInformation = new AdditionalInformation();
if (reflectedType != null)
{
additionalInformation = new AdditionalInformation()
{
Column = trace.GetFrame(0).GetFileColumnNumber(),
Line = trace.GetFrame(0).GetFileLineNumber(),
MethodName = reflectedType.FullName,
File = trace.GetFrame(0).GetFileName()
};
}
return additionalInformation;
}

system io file not found exception/ error handling

I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:
"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"
Please someone help me to do the error handling.
Thank you in advance.
using System;
using System.IO;
class Test
{
static void Main(string[] args)
{
Console.WriteLine("Please :");
string hely = Console.ReadLine();
string[] __file = Directory.GetFiles(hely);
string[] __dir = Directory.GetDirectories(hely);
foreach (string i in __file)
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
foreach (string i in __dir)
{
DirectoryInfo _file = new DirectoryInfo(i);
Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
}
Console.ReadKey();
}
}
You should check existence of a path with
System.IO.Directory.Exists(directory)
and of a file with
System.IO.File.Exists(filePath)
Then, you need to take the try-catch block inside the for-loop, to catch any possible exceptions that occur because of insufficient rights/permissions.
e.g.
foreach (string i in __file)
{
try
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
throw;
}
}
You could also create two try-catch blocks - depends on what you want to do.
try
{
foreach (string i in __file)
{
try
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
throw;
}
}
}
catch (System.Exception exLoop)
{
System.Console.WriteLine(exLoop.Message);
throw;
}
Note that in your example, you should first check if the directory "hely" exists:
if (!System.IO.Directory.Exists(hely))
{
System.Console.Error.WriteLine("Directory \"{0}\" does not exist.", hely);
System.Environment.Exit(1);
// or: return;
}
Since exception handling is usually very slow, I would however recommend that you check for the existence of the file/directory explicitly. It would also be a good idea to do so for the file/directory-listing & read-access rights for the respective user. But even if you do so, keep the try-catch, because there might be cases where your program suddenly fails - e.g. when a removable storage is forcefully removed.
Use try catch
using System;
using System.IO;
class Test
{
static void Main(string[] args)
{
Console.WriteLine("Please :");
string hely = Console.ReadLine();
try
{
string[] __file = Directory.GetFiles(hely);
string[] __dir = Directory.GetDirectories(hely);
foreach (string i in __file)
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
foreach (string i in __dir)
{
DirectoryInfo _file = new DirectoryInfo(i);
Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
}
}
catch(System.IO.DirectoryNotFoundException ex)
{
Console.WriteLine("Directory not found");
}
Console.ReadKey();
}
}
You can check if the file exists
foreach (string i in __file)
{
if (File.Exists(i))
{
FileInfo fajl = new FileInfo(i);
Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
}
}
RTFM?
Read Directory.GetFiles method
It says that you will get the DirectoryNotfound exception if the specified path is not found. Obviously folder 'C:\Temp\first_project\first_project\bin\Debug\12345' does not exist.
Proper code would be:
string hely = ...
try
{
string[] files = Directory.GetFiles(hely);
ProcessFiles(files);
}
catch (DirectoryNotFoundException exc)
{
Console.WriteLine(exc.Message);
}
If you don't know how to react on exceptions read MSDN about exception handling

C# open variable file with error message

I can't figure out how to have the console error check the user input then open the file that is requested. Can someone show me what I'm doing wrong?
Here's my current program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine(">Enter File to open.");//Prompt user for file name
try
{
if (!File.Exists(Console.ReadLine()))
throw new FileNotFoundException();//Check for errors
}
catch (FileNotFoundException)
{
Console.WriteLine("You stuffed up!"); //Display error message
}
}
System.Diagnostics.Process.Start(#Console.ReadLine()); //set valid reply response
Console.ReadLine();
}
}
}
You have a semicolon in this line
if (!File.Exists(Console.ReadLine())) ;
You don't put semicolons on if statements, if you only have a single line after your if statement the following is fine
if (!File.Exists(Console.ReadLine()))
throw new FileNotFoundException();//Check for errors
else
if (!File.Exists(Console.ReadLine())){
throw new FileNotFoundException();//Check for errors
//some more code
}
EDIT:
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine(">Enter File to open.");//Prompt user for file name
string s = Console.ReadLine();
try
{
if (!File.Exists(s))
throw new FileNotFoundException();//Check for errors
else
System.Diagnostics.Process.Start(s); //set valid reply response
Console.ReadLine();
}
catch (FileNotFoundException)
{
Console.WriteLine("You stuffed up!"); //Display error message
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ABCD
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine(">Enter File to open.");//Prompt user for file name
string fileName = Console.ReadLine();
try
{
if (!File.Exists(fileName))
throw new FileNotFoundException();//Check for errors
else
System.Diagnostics.Process.Start(fileName); //set valid reply response
Console.ReadLine();
}
catch (FileNotFoundException)
{
Console.WriteLine("You stuffed up!"); //Display error message
}
}
}
}
}
just make sure that you make an input of filename i.e. executable file with ".exe" extension, and make sure that you provide full path.
i.e. make an input like "C:\Program Files\Internet Explorer\iexplore.exe", to open Internet Explorer

Format Exception Unhandled while debugging

When debugging the code, Visual Studio gives me a "format exception was unhandled" while highlighting this line of code: 'CustObj.d_CustDiscount = Convert.ToDecimal(gs_InPutBuffer.Substring(000, 004));'
I have been googling correct formats and have not come up with any fixes. So my main question is, how do I rewrite this code in order for it to work?
Thanks for any help!
Below is the full program if you need to reference it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CustFile_DLL;
namespace FileConvertorPA03
{
class Program
{
//add these to handle I/O
//instatiate streamreader
private static StreamReader TextfileIn = new StreamReader("customers.txt");
//instantiate the dll
private static CustFileClass CustObj = new CustFileClass();
//a few vars
private static string gs_InPutBuffer = "";
private static Int32 gi_TotalRec = 0, gi_FirstRecNo = 0;
private static bool gb_FirstRec = true;
static void Main(string[] args)
{
while ((gs_InPutBuffer = TextfileIn.ReadLine()) != null)
{
ParsetoAttributes();
CustObj.AddObject();
}//end while
PopMessageBox();
TextfileIn.Close();
}//end main
//method to parse input buffer to class attributes
private static void ParsetoAttributes()
{
CustObj.s_CustName = gs_InPutBuffer.Substring(000, 033).Trim();
CustObj.s_CustAddress = gs_InPutBuffer.Substring(033, 032).Trim();
CustObj.s_CustZip = gs_InPutBuffer.Substring(065, 005);
CustObj.s_CustPhone = gs_InPutBuffer.Substring(070, 010);
CustObj.d_CustDiscount = Convert.ToDecimal(gs_InPutBuffer.Substring(000, 004));
}//end parse attributes
//method to count records added
static void CountRecs()
{
if (gb_FirstRec == true)
{
gi_FirstRecNo = CustObj.i_CustNumber;
gb_FirstRec = false;
}//end if
gi_TotalRec++;
}//end count recs
public static void PopMessageBox()
{
MessageBox.Show(String.Format("Message: \n\tRecords Added \t{0,6}n\tFirst Rec Added\t {1,6}\n\tLast Rec Added\t{2,6}",
gi_TotalRec, gi_FirstRecNo, CustObj.i_CustNumber),"File Conversion Message:",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}//end class
}
}//end namespace
Replace the ToDecimal call with the following to find out what the issue is:
try
{
CustObj.d_CustDiscount = Convert.ToDecimal(gs_InPutBuffer.Substring(0, 4));
}
catch (FormatException e)
{
Console.WriteLine(gs_InPutBuffer.Substring(0, 4));
Console.WriteLine(e.Message);
}
If this isn't a console application, you can change the code in the catch block to write out to a MessageBox. You can also leave out the leading zeros in the arguments to the calls to Substring.

C# SVN Pre Commit Hook, SharpSvn error

I have a C# console application that I use as an SVN Pre Commit Hook. The console app is started perfectly. However, as soon as I try to do a Write using SharpSvn, I get this error:
Commit failed (details follow):
Commit blocked by pre-commit hook (exit code -1066598274) with output:
Unhandled Exception: System.Runtime.InteropServices.SEHException: External
component has thrown an exception.
at svn_client_cat2(svn_stream_t* , SByte* , svn_opt_revision_t* ,
svn_opt_revision_t* , svn_client_ctx_t* , apr_pool_t* )
at SharpSvn.SvnClient.Write(SvnTarget target, Stream output, SvnWriteArgs args)
at SharpSvn.SvnClient.Write(SvnTarget target, Stream output)
at SvnPreCommitHook.Program.Main(String[] args)
I have tried to do the svn.Write command from my own machine, pointing to svn://svn-server instead of localhost - and that works fine. I guess it is something on the server. TortoiseSVN is installed, although I don't see any context menus...
My code looks like this:
private static EventLog _serviceEventLog;
static void Main(string[] args)
{
_serviceEventLog = new EventLog();
if (!System.Diagnostics.EventLog.SourceExists("Svn Hooks"))
{
System.Diagnostics.EventLog.CreateEventSource("Svn Hooks", "Svn Hooks");
}
_serviceEventLog.Source = "Svn Hooks";
_serviceEventLog.Log = "Svn Hooks";
SvnHookArguments ha;
if (!SvnHookArguments.ParseHookArguments(args, SvnHookType.PreCommit, false, out ha))
{
/*Console.Error.WriteLine("Invalid arguments");
Environment.Exit(1);*/
}
using (SvnLookClient cl = new SvnLookClient())
{
SvnChangeInfoEventArgs ci;
cl.GetChangeInfo(ha.LookOrigin, out ci);
if (!ci.LogMessage.Equals("Svn Hook Test"))
{
AllowCommit();
return;
}
var checkoutDir = #"C:\SvnTemp\" + DateTime.Now.Ticks.ToString();
foreach (SvnChangeItem i in ci.ChangedPaths)
{
var checkoutFilepath = checkoutDir + "\\" + Path.GetFileName(i.Path);
if (!Directory.Exists(checkoutDir))
{
Directory.CreateDirectory(checkoutDir);
}
using (SvnClient svn = new SvnClient())
{
using (StreamWriter sw = new StreamWriter(checkoutFilepath))
{
svn.Write(SvnTarget.FromString("svn://localhost/" + i.RepositoryPath), sw.BaseStream);
}
}
var fileContents = File.ReadAllText(checkoutFilepath);
if (fileContents.Contains("Martin Normark"))
{
RemoveTempDirectory(checkoutDir);
PreventCommit("Name is not allowed!");
}
}
RemoveTempDirectory(checkoutDir);
}
AllowCommit();
}
Maybe one of the following:
64bit vs 32 bit
vcredist missing on the server
Maybe you should first catch the thrown exception by using the HandleProcessCorruptedStateExceptionsAttribute:
[HandleProcessCorruptedStateExceptions]
static void Main() // main entry point
{
try
{
}
catch (Exception ex)
{
// Handle Exception here ...
}
}

Categories