Usage of StreamWriter - c#

I'm using the following code to open a file and then trying to write something to it:
public partial class MainWindow : Window
{
StreamWriter file = null;
public MainWindow()
{
InitializeComponent();
using (file = new StreamWriter("../data/floorPlane.txt", true))
{
file.WriteLine("x \t y \t z \t w \n");
}
}
}
But it always gives the following error:
A first chance exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll
Additional information: 'The invocation of the constructor on type
'SkeletalViewer.MainWindow' that matches the specified binding
constraints threw an exception.
I'm totally new to c#. Maybe the question is kindof stupid.
Thanks,

First, check the inner exception to see what you are actually messing up. Then, if the answer is still not apparent, compare your code to the sample found at this MSDN article:
http://msdn.microsoft.com/en-us/library/vstudio/system.io.streamwriter

this exception is caught many times. You can press ctrl+alt+E to check all exception and than you can find real exception.

Related

Serializing/Deserializing a roundtrip with NetTopologySuite's IO Library for GeoJson reveals a potential bug

I'm having trouble using NetTopologySuite's GeoJsonReader to deserialize Feature objects. In particular, I'm receiving the following exception (which at first glance seems straightforward, so please read on):
An unhandled exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll. Additional information: Expected token '{' not found.
Just doing a simple round-trip results in this exception:
public static string DoIt( Feature feature )
{
GeoJsonWriter writer = new GeoJsonWriter();
var geoJson = writer.Write(feature);
GeoJsonReader reader = new GeoJsonReader();
var deserializedFeature = reader.Read<Feature>(geoJson );
}
in this case, geoJson is pretty straightforward:
"{\"type\":\"Feature\",\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-104.50348159865847,40.891762392617345],[-104.50348672999991,40.891415817000279],[-104.50355999200002,40.887782408000135],[-104.5036332529998,40.884149000000093],[-104.50845260799991,40.884357883000121],[-104.51307160051412,40.884558081989375],[-104.51307160051412,40.891762392617345],[-104.50348159865847,40.891762392617345]]]},\"properties\":null}"
Please let me know what I'm doing wrong. By the way, I'm using NetTopologySuite 1.14, NetTopologySuite.IO.GeoJSON 1.14, & Json.Net 9.0.1.
this is actually a bug.
code fixed, see #120

How to find out the XAML file that produces a XamlParseException

I get the following error at runtime from a C# WPF application:
A first chance exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll
Additional information: 'Set property
'System.Windows.Controls.ContentControl.Content' threw an exception.'
Line number '6' and line position '6'.
How can I find which file this is associated with? The Visual Studio solution contains two XAML files, app.xaml and MainWindow.xaml.
I am using VS 2010 on Windows 7. The application targets .NET 4.0.
UPDATE:
Following up on Kasper's helpful suggestion, I displayed the exception in detail, and this is what it showed:
Based on the information in there, I was able to gather that a certain DLL was missing. Supplying the DLL fixed this problem, but I still have other XAML parse errors coming up.
In the code-behind, the XAML code is parsed in the method InitializeComponent which is automatically generated. This method is called in the Window object's constructor. So to have more details about the exception, put the call to InitializeComponent in a try/catch block. This way, you have access to the useless XamlParseException, but also to its InnerExceptions and to the StackTrace.
UPDATE!
You can call the inner exception using a MessageDialog.
public partial class Window1 : System.Windows.Window
{
public Window1()
{
try
{
InitializeComponent();
}
catch ( Exception ex )
{
// Log error (including InnerExceptions!)
// Handle exception
MessageDialog dialog = new MessageDialog(ex.InnerException);
dialog.ShowAsync();
}
}
}
Hope that helps :)
There is also another trick to this:
Open the "Exceptions" window (Debug/Exceptions) in Visual Studio.
Click "add"
Add "System.Windows.Markup.XamlParseException"
Check the box to break on throw for this exception.
Hit F5!
You'll find that the XamlParseException you catch is much more descriptive, and will give the correct position in the xaml file.
Let me know if this was easier :)

Puma .NET exception 'System.Runtime.InteropServices.COMException'

Trying to recognise a set of images in a folder (using Puma .NET OCR library), the first image is recognised successfully, but after that I get an error:
An unhandled exception of type 'System.Runtime.InteropServices.COMException'
occurred in Puma.Net.dll
Additional information: <0x00000000>: ?????? ???.
I have a special class for recognition, and the error happens on this line:
Puma.Net.PumaPage inputFile = new Puma.Net.PumaPage(imagePath);
I found this link and this one, but they don't seem to help in my case.
Thank you
I found the answer by using 'using' statement
using(Puma.Net.PumaPage inputFile = new Puma.Net.PumaPage(imagePath))
{
}

The type initializer for 'MyClass' threw an exception

The following is my Windows service code. When I am debugging the code, I am getting the error/ exception:
The type initializer for 'CSMessageUtility.CSDetails' threw an exception.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using CSMessageUtility;
namespace CS_Data_Trasmmiting_Service
{
public partial class svcCSWinServ : ServiceBase
{
//private string sLogFormat;
//private string sErrorTime;
private Thread new_thread;
Logger logObject = new Logger();
private bool isenable = true;
public svcCSWinServ()
{
InitializeComponent();
logObject.append("Initialize Service " + DateTime.Now.ToString(), 70);
CheckForAlarms();
}
protected override void OnStart(string[] args)
{
try
{
new_thread = new Thread(new ThreadStart(CheckForAlarms));
new_thread.Start();
}
catch
{
}
logObject.append("Service Started successfully " + DateTime.Now.ToString(), 70);
}
protected override void OnStop()
{
try
{
isenable = false;
new_thread.Abort();
}
catch
{
}
logObject.append("Service Stopped successfully " + DateTime.Now.ToString(), 70);
}
void CheckForAlarms()
{
try
{
while (true)
{
//if((DateTime.Now.ToString("HH:mm") == "18:00"))
//{
logObject.append("Start Sending Data " +DateTime.Now.ToString(), 70);
try
{
//SendAllInfo();
string str = CSMessageUtility.CSDetails.createDHSMessageFormat();
Thread.Sleep(2000);
string str1 = CSMessageUtility.CSDetails.createEALMessageFormat();
Thread.Sleep(2000);
string str2 = CSMessageUtility.CSDetails.createProductStatusMessageForamt();
Thread.Sleep(2000);
string str3 = CSMessageUtility.CSDetails.createEODMessageFormat();
Thread.Sleep(2000);
string str4 = CSDetails.createProductReceiptEntryatBOSMessageFormat();
Thread.Sleep(2000);
string str5 = CSMessageUtility.CSDetails.createProductSaleMessageFormat();
Thread.Sleep(2000);
string str6 = CSMessageUtility.CSDetails.createTotalizerExceptionMessageFormat();
Thread.Sleep(2000);
//CSMessageUtility.CSDetails.createDailyCOtransferMessageFormat();
//Thread.Sleep(2000);
}
catch (Exception ee)
{
logObject.append(ee.Message, 70);
}
logObject.append("Finished Sending Data " +DateTime.Now.ToString(), 70);
Thread.Sleep(3000);
//}
//Thread.Sleep(20000);
}
}
catch (Exception ex)
{
logObject.append("Thread Exception: "+ ex.Message + " "+ DateTime.Now.ToString(), 70);
try
{
new_thread.Abort();
}
catch (Exception ex1)
{
logObject.append("Thread Exception: " +ex1.Message + " " + DateTime.Now.ToString(), 70);
}
if (isenable == true)
{
new_thread = new Thread(new ThreadStart(CheckForAlarms));
new_thread.Start();
}
}
}
}
}
Check the InnerException property of the TypeInitializationException; it is likely to contain information about the underlying problem, and exactly where it occurred.
This problem can be caused if a class tries to get value of a key in web.config or app.config which is not present there.
e.g.
The class has a static variable
private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();
But the web.config doesn't contain the GoogleCalendarApplicationClientID key
The error will be thrown on any static function call or any class instance creation
The type initializer for 'CSMessageUtility.CSDetails' threw an exception. means that the static constructor on that class threw an Exception - so you need to look either in the static constructor of the CSDetails class, or in the initialisation of any static members of that class.
I ran into the same problem, when I was using a static methods in a Util class, just like you had used CSMessageUtility.CSDetails.
The problem was that during the static initialization of the class (using the static constructor), the framework also initialize the the static variables (fields) in the class. I had a static variable that attempts to read values from app.config, and app.config was missing the respective settings, thus resulting in an un-handled exception. This resulted in getting the
"Object reference not set to an instance of an object."
as the inner exception.
One other thing to check when these initialize errors are thrown would be to check if the target .NET version is installed on the server. You can right click the project and see what .NET version the application is targeting.
Dictionary keys should be unique !
In my case, I was using a Dictionary, and I found two items in it have accidentally the same key.
Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
{"KEY1", "V1"},
{"KEY1", "V2" },
{"KEY3", "V3"},
};
This can happen if you have a dependency property that is registered to the wrong owner type (ownerType argument).
Notice SomeOtherControl should have been YourControl.
public partial class YourControl
{
public bool Enabled
{
get { return (bool)GetValue(EnabledProperty); }
set { SetValue(EnabledProperty, value); }
}
public static readonly DependencyProperty EnabledProperty =
DependencyProperty.Register(nameof(Enabled), typeof(bool), typeof(SomeOtherControl), new PropertyMetadata(false));
}
I've had the same problem caused by having two of the same configuration properties (which matches the app.config):
[ConfigurationProperty("TransferTimeValidity")]
Another scenario that might cause this is when you have a piece of your code that calls:
string sParam = **ConfigurationManager.AppSettings["SOME_PARAM"].ToString();
Keep in mind that you have to use the OWSTIMER.EXE.CONFIG file for configuration file settings. I had an App.config file that I was trying to read and I was getting this error because on instantiation of my job instance, I had a line in my code that was referring to Connfiguration.AppSettings & Configuration.ConnectionStrings. Just make sure that you go the path:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
and place your configuration settings in the OWSTIMER.EXE.CONFIG file.
If for whatever reason the power goes or the Visual Studio IDE crashes it can cause this problem inside your bin/debug bin/release...
Just delete the content and recompile (from personal experience when my toe hit the reset button!)
I had a different but still related configuration.
Could be a custom configuration section that hasn't been declared in configSections.
Just declare the section and the error should resolve itself.
I encountered this issue due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly
As the Error says the initialization of the Type/Class failed. This usually occurs when there is some exception in the constructor of the class. Most common reason is you assign some value in the constructor reading from a config file and the config file is missing those values.
Noteworthy: I had multiple projects in my solution and I forgot to add the references/Nuget libraries. When I ran a method in the static class, which used the given libraries, it threw the exception mentioned.
In my case I had this failing on Logger.Create inside a class library that was being used by my main (console) app. The problem was I had forgotten to add a reference to NLog.dll in my console app. Adding the reference with the correct .NET Framework library version fixed the problem.
Had a case like this in a WPF project. My issue was on a line that went like this:
DataTable myTable = FillTable(strMySqlQuery);
Where FillTable() returned a DataTable based on a SQL query string. If I did the "copy exception to clipboard" option, I think it was, and pasted into Notepad, I could see the message. For me, it was The input is not a valid Base-64 string as it contains a non-base 64 character.
My actual problem wasn't that the query string had something that shouldn't be there, like I was thinking, because string strMySqlQuery = "SELECT * FROM My_Table" was my string and thought it could be the * or _, but the actual problem was in FillTable(), where I had a call to another function, GetConnection() that returned an OracleConnection object, in order to open it and retrieve and return the DataTable. Inside GetConnection() I was getting the app.config parameters for my connection string, and I had one of them misnamed, so it was setting a null value for the service account's password and not making the DB connection. So it's not always where the error is exactly correct for all circumstances. Best to dive into the function where the error is and debug step-by-step and ensure all values are getting filled with what you expect.
I too faced this error in two situation
While performing redirection from BAL layer to DAL layer I faced this exception. Inner exception says that "Object Reference error".
Web.Config file key does not match.
Hope this useful to solve your problem.
Similar to what Muhammad Iqbal stated.. I was in a VB.NET (may also be C#) project where I did remove a key-value pair from the App.config which was referenced by a variable global to the Sub Main() of Module Main. Therefore, the exception (and break) occurs in Module Main before the Sub Main(). If only I had a break-point on the Dim, but we don't usually break on global variables. Perhaps a good reason not to declare globals referencing App.config? In other words, this...
An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module.
The type initializer for 'Namespace.Main' threw an exception.
Is caused by...
App.config
<connectionStrings>
<!--<add name="ConnectionString1" connectionString="..." />-->
Main module
Module Main
Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1") '<-- BREAK HERE (EXCEPTION)
Sub Main()
// main code
End Main
End Module
In my case, I had a helper class that was static. In that class was a method to initialize a SqlCommand dependent on variables. As this was being called in several places I moved it to the helper class and called as needed, so this method was also static. Now I had a global property that was the connection string in Global.asax pointing to the connection string in web.config. Intermittently I would get "The type initializer for 'Helper' threw an exception". If I moved the method from the Helper class to the class where it was being called from all was good. The inner exception complained of the object being null (Helper class). What I did was add Using Helper to Global.asax and even though it was not being used by Global.asax this solved the problem.
My Answer is also related to Config section. If you assign values from Config file at static class of C# or Module.VB of VB, you will get this error at run time.
add key="LogPath" value="~/Error_Log/"
Using Forward slash in Web.Config also leads to this error on Run time. I just resolved this issue by putting BackSlash
add key="LogPath" value="~\Error_Log\"
I wrapped my line that was crashing in a try-catch block, printed out the exception, and breaked immediately after it was printed. The exception information shown had a stack trace which pointed me to the file and line of code causing the fault to occur.
System.TypeInitializationException: The type initializer for 'Blah.blah.blah' threw an exception.
---> System.NullReferenceException: Object reference not set to an instance of an object.
at Some.Faulty.Software..cctor() in C:\Projects\My.Faulty.File.cs:line 56
--- End of inner exception stack trace ---
at Blah.blah.blah(Blah.blah.blah)
at TestApplication.Program.Main(String[] args)
in C:\Projects\Blah.blah.blah\Program.cs:line 29 Exception caught.
Somehow exiting Visual Studio and re-opening it solved this for me.

uncatchable exception from unreachable code

I run into a very strange problem in my C# 2.0 WinForms app and I'm not even sure if its worth asking SO, because the problem occurs in a strange setup and I don't think that you could reproduce it without my sources, but I'm totally out of ideas.
I have a Form with a TreeView on the left and an ListView on the right. The TreeView shows all available files and subfolders from a specific folder(which contains documents i need for my app). If a Folder is selected the ListView shows all files and subfolders from the selected folder. At startup I populate the TreeView form the folder and after that I select the first TreeNode by code(in my case it's an folder). After that the Content of the TreeView looks like this:
-folder
-file1
-file2
Selecting the folder triggers the AfterSelecedEvent of the TreeView. Because a folder was selected I populate the ListView using the following methode:
private void fillOverview(FAFolder folder)
{
lv_overview.Items.Clear();
ListViewItem item;
foreach (FAFile file in folder.sortedContent)
{
if (file is FAFolder)
{
item = new ListViewItem(file.Name, "Folder"); //exception got thrown here
}
else
{
item = new ListViewItem(file.Name, file.Name);
}
item.Tag = file;
lv_overview.Items.Add(item);
}
}
As you can see there is no subfolder, so the line item = new ListViewItem(file.Name, "Folder"); should never be touched in this setup, but every now and then a NullReferenceException got thrown. If I wrap this line with try/catch the exception got thrown inside the catch block. I tried checking everything if it's null or not, but ther were no nullreferences. Or if I add a MessageBox right before this line the exceptions got still thrown and no MessageBoxpops up. This brings me to the conclusion that the execption stacktrace is wrong and/or this exceptions comes from an other Thread or something like that.
I'm a very optimistic person and I know how clever the SO community can be, but I don't think that anybody can point out what the problem is. So what i'm actuallly looking for are hints and advices how i could find and debug the cause of this strange behavior.
EDIT:
internal abstract class FAFile
{
internal string Name;
internal readonly FAFolder Parent;
internal FAFile(FAFolder parent)
{
this.Parent = parent;
}
}
internal sealed class FAFolder : FAFile
{
internal readonly IDictionary<string, FAFile> Content = new Dictionary<string, FAFile>();
internal FAFolder(FAFolder parent, string name) : base(parent)
{
this.Name = name;
}
}
internal sealed class FADocument : FAFile
{
public readonly string Path;
public FADocument(FAFolder parent, string path): base(parent)
{
this.Path = path;
this.Name = System.IO.Path.GetFileNameWithoutExtension(path);
}
}
Have you tried an null check on folder.sortedContent ?
Usually ReSharper will prompt me that something like that should have a null check.
If you want to be sure, add the following line to your code, above the foreach loop:
if (folder.sortedContent == null) throw new Exception("It was null, dangit!");
On the line you mention:
item = new ListViewItem(file.Name, "Folder")
the only thing that can cause a NullReferenceException is if file is null (unless the exception is being thrown from within the ListViewItem constructor itself).
You don't provide the code for folder.sortedContent so I can't tell - but is it possible that one of the elements in this collection might be null under certain circumstances?
If the ListViewItem constructor is throwing the exception then you will need to use Reflector to look at the code, or download the reference source.
A co-worker of mine just found the answer(probably). I use a Thread to load the ImageList to the ListView from the HDD and this thread sometimes freezes and if i assign a ImageKey it fails. That's no answer why the exception is uncatchable or why it's thrown at this (unreachable) line. But i strongly belive that this is the cause of the problem.
That line is not unreachable. Because FAFolder derives from FAFile, it is possible that 'file is FAFolder' will return true.
However, that would imply that file is not null, unless it is being changed by another thread.
Edit: file can't be changed by another thread as it's a local reference. Can you provide a stack trace for the exception? This one has me intrigued now.
I just cannot help wondering is the FAFolder contain a '.' or a '..' for parent and subdirectory? and the sorting breaks as a result?
This answer will be edited accordingly if this turns out to be untrue?
Hope this helps,
Best regards,
Tom.
Is this exception reproducible on demand?
Can you show the the stack trace of the exception?
What other threads are running when the exception is thrown?
In general, there are two ways to debug this type of stuff. The first way is so-called "scientific" debugging:
Devise a theory to explain observed behaviour.
Devise an experiment to test the theory.
Run the experiment and observe the results.
The second way is by stripping-down the actual code piece by piece until the exception is no longer triggered. Then you have a significant clue for further investigation.
This brings me to the conclusion that the execption stacktrace is wrong....
It's usually easier to start by assuming that the problem is in your own code.

Categories