Brand new to MOno/db4o and C#.
Simple db program and I get an outer stack error "Type Initialization Exception" and the inner stack error states the file name is unknown. I have the db4o.dll file in my references, I know it is something silly but I can't seem to locate an answer anywhere, thanks for the help, project is due on Monday!
using System;
using Db4objects.Db4o;
public class Test {
static string _file = "store.yap";
public static void Main (string [] args){
IObjectContainer db = Db4oFactory.OpenFile (_file);
db.Close();
}
Related
How do I solve this missing dependency? Googling around for this problem, it seems rare. I see similar ones like The type or namespace name 'Windows' does not exist in the namespace 'System' but nowhere do I see someone explain this particular message.
Log files naturally recorded by windows at locations such as C:\Windows\System32\WDI\LogFiles\BootPerfDiagLogger.etl record useful forensic security info, such as every process that ran persistently at boot.
My goal is to parse these files into some intermediary structure like XML or JSON so I can import the data to Python.
I wanted to parse Windows ETL files in Python for forensic / security data science. I thought this would be easy since there's a Python library for it but upon running that library, it doesn't work and is probably no longer maintained.
Luckily I found a Microsoft dev blog on parsing ETL files with the same classes Windows exposes to allow Windows Performance Analyzer to do it.
The example code shown was like:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Windows.EventTracing;
using Microsoft.Windows.EventTracing.Disk;
using Microsoft.Windows.EventTracing.Processes;
class FileOperation
{
public IProcess IssuingProcess;
public string Operation;
public string Path;
public long Size;
public decimal Duration;
}
class Program
{
public static void Main(string[] args)
{
var etlFileName = args[0];
var diskTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-disk.csv";
var fileTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-file.csv";
using (ITraceProcessor trace = TraceProcessor.Create(etlFileName))
{
var pendingDisk = trace.UseDiskIOData();
var pendingFile = trace.UseFileIOData();
trace.Process();
ProcessDisk(pendingDisk.Result, diskTrace);
ProcessFile(pendingFile.Result, fileTrace);
}
}
I won't include the ProcessDisk and ProcessFile classes here because those seem to be geared toward whatever debugging purpose the writer had. Rather, I'm interested in trace. Based on the methods I see called: UseDiskIOData, UseFileIOData, presumably there is a longer list of methods like that I could use to access all available data for each trace.
My immediate goal with this question is just to view what methods exist on the trace object.
So I did some research on how you look at all properties on an object in C#, and there are plenty of answers, that's probably not a problem:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Windows.EventTracing;
using Microsoft.Windows.EventTracing.Disk;
using Microsoft.Windows.EventTracing.Processes;
class Program
{
public static void Main(string[] args)
{
var etlFileName = args[0];
#var diskTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-disk.csv";
#var fileTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-file.csv";
using (ITraceProcessor trace = TraceProcessor.Create(etlFileName))
{
Type myType = trace.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(trace, null);
// Do something with propValue
Console.WriteLine(propValue);
}
#var pendingDisk = trace.UseDiskIOData();
#var pendingFile = trace.UseFileIOData();
#trace.Process();
#ProcessDisk(pendingDisk.Result, diskTrace);
#ProcessFile(pendingFile.Result, fileTrace);
}
}
But what I did have a problem with is this:
The type or namespace Windows does not exist in namespace Microsoft
As I said, I looked around for solutions to this and found nothing.
I’m trying to use the File class to work with a text file in a console and winforms desktop app and getting the following exception:
The type initializer for '_Library.Logging' threw an exception
From what I’ve read here this error is typically caused by a problem in App.config for Winfoms apps but the Exception details seem to point elsewhere:
System.ArgumentNullException: Value cannot be null. Parameter name: path
at System.IO.File.AppendAllText(String path, String contents)
The MSDN examples for file manipulation all hard code the path parameter without any reference to using an App.confiig file so my presumption was it is possible to do this without involving ConfigurationManager.
This is the code I'm trying to use
// in calling method
class Program_Console
{
private static StringBuilder SB4log = new StringBuilder();
public static void Main(string[] tsArgs)
{
// Conditionals dealing with argumentts from Task Scheduler
Save2Log("Calling _UI.exe via \"Process.Start()\"", true);
// try-catch-finally for Process.Start
}
private static void Save2Log(string msgTxt, bool noTS)
{
SB4log.AppendLine($"{msgTxt}");
if (noTS) Logging.SaveLog(SB4log);
else Logging.SaveLog_TimeStamp(SB4log);
SB4log.Clear();
}
}
// saving app progression messages to a single log txt file
public static class Logging
{
private static String filePath = Connections.LogPath();
private static StringBuilder SB4log = new StringBuilder();
public static void SaveLog(StringBuilder logTxt)
{
File.AppendAllText(filePath, logTxt.ToString());
logTxt.Clear();
}
}
// class for DB connection and file paths
public static class Connections
{
private static StringBuilder SB4log = new StringBuilder();
public static string AppPath()
{
string appRoot;
try
{
string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
SaveLog($"->App Path: {appDir}", true); // culprit
int loc = appDir.IndexOf("BURS");
appRoot = appDir.Substring(0, loc + 5);
}
catch (Exception ex)
{
// Exception response and MessageBox
}
return appRoot;
}
public static string ConsolePath() {}
public static string UIPath() {}
public static string LogPath()
{
string appRoot = AppPath();
string wrkDir = #"_Library\Data\BURS_Log.Txt";
string fullDir = $"{appRoot}{wrkDir}";
SaveLog($"->Log Path: {fullDir}\n", true); // culprit
return fullDir;
}
}
In stepping through the code the code the variable containing the path -- filePath -- has the expected value: "D:\BURS_Library\Data\BURS_Log.Txt" (quotes used to show there re no unintended spaces needing to be trimmed). Acordinng to MSDN if it's a malformed path an exception will be thrown but the path looks valid to me.
Why isn’t the Path variable utilized?
Any help will be appreciated.
Edit: expanded code to show start-to-finish flow since the original abridged version seemed to be confusing. Have added the text "//culprit" to the two lines which caused the error as pointed out by the responders.
It's not clear what Connections is, but given Connections.LogPath(); it seems that you're calling LogPath(); to set the value for filePath which is a problem because that calls AppPath which has the following statement SaveLog($"->App Path: {appDir}", true);.
You haven't included a version of SaveLog that has 2 parameters, but assuming it's similar to the one you've posted, you're attempting to use filePath when the value hasn't been set yet - which causes an issue.
As the title says, Visual Studio is throwing an exception when I execute my program.
The exact error:
An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
As I'm rather new to using Visual Studio, and C# for that matter, I was unable to discern what the issue was. I did Google, but none of the information I found assisted the recovery of my excepted program.
Program code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Game {
public struct entity {
int XP,
HP,
mana,
luck,
strength,
defense;
float modStrength,
modDefense;
string stance;
}
public class Game {
private entity enemy;
private static Dictionary<string, int> playerData =
new Dictionary<string, int>();
public static string[] entityPool =
new StreamReader(Properties.Resources.Entities).ToString().Split('?');
static void Main (string[] args) {
instancePlayer();
Console.ReadKey();
}
private static void instancePlayer () {
string[] playerDataDummy = entityPool[0].Trim().Split(';');
foreach (string s in playerDataDummy) {
string[] indivArr = s.Split(' ');
playerData.Add(indivArr[0], Convert.ToInt16(indivArr[1]));
}
foreach (KeyValuePair<string, int> s in playerData) {
Console.WriteLine("[{0}] {1}", s.Key, s.Value);
}
}
private void instanceEnemy () {
}
}
}
I have been able to narrow the issue down to this line, though...
public static string[] entityPool = new StreamReader(Properties.Resources.Entities).ToString().Split('?');
That's about as much as I've been found out; removing the initialization of that, and all it's reference, nullifies the issue. But alas, I do need it there.
Take a look at the streamreader class on MSDN. There are several constructors for it and a simple example for reading from a text file. I'm not sure what you have in Properties.Resources.Entities (a file path I assume). Assuming this is a valid file path or stream and the constructor isn't throwing the error, you are creating the streamreader then calling .ToString() which gives you a string representation of the StreamReader object, not the contents of the file or stream. This is probably not what you are expecting. The sample on the MSDN page should help you with using the StreamReader class.
This line is wrong.
public static string[] entityPool = new StreamReader(Properties.Resources.Entities).ToString().Split('?');
What you probably meant was to read all the contents of the stream. Something like this.
StreamReader sr = new StreamReader(Properties.Resources.Entities);
string[] entityPool = sr.ReadToEnd().Split('?');
Better to put this code in the constructor with a try-catch rather than in an initialiser.
It appears that a StreamReader was not necessary to access the contents of the file.
string[] entityPool = Properties.Resources.Entities.split('?'); works as I previously intended.
I appreciate the responses, All.
I am looking for an OFX file parser library in C#. I have search the web but there seems to be none. Does anyone know of any good quality C# OFX file parser. I need to process some bank statements files which are in OFX format.
Update
I have managed to find a C# library for parsing OFX parser.
Here is the link ofx sharp. This codebase seems to be the best case to startup my solution.
I tried to use the ofx sharp library, but realised it doesn't work is the file is not valid XML ... it seems to parse but has empty values ...
I made a change in the OFXDocumentParser.cs where I first fix the file to become valid XML and then let the parser continue. Not sure if you experienced the same issue?
Inside of the method:
private string SGMLToXML(string file)
I added a few lines first to take file to newfile and then let the SqmlReader process that after the following code:
string newfile = ParseHeader(file);
newfile = SGMLToXMLFixer.Fix_SONRS(newfile);
newfile = SGMLToXMLFixer.Fix_STMTTRNRS(newfile);
newfile = SGMLToXMLFixer.Fix_CCSTMTTRNRS(newfile);
//reader.InputStream = new StringReader(ParseHeader(file));
reader.InputStream = new StringReader(newfile);
SGMLToXMLFixer is new class I added into the OFXSharp library. It basically scans all the tags that open and verifies it has a closing tag too.
namespace OFXSharp
{
public static class SGMLToXMLFixer
{
public static string Fix_SONRS(string original)
{ .... }
public static string Fix_STMTTRNRS(string original)
{ .... }
public static string Fix_CCSTMTTRNRS(string original)
{ .... }
private static string Fix_Transactions(string file, string transactionTag, int lastIdx, out int lastIdx_new)
{ .... }
private static string Fix_Transactions_Recursive(string file_modified, int lastIdx, out int lastIdx_new)
{ .... }
}
}
Try http://www.codeproject.com/KB/aspnet/Ofx_to_DataSet.aspx. The code uses Framework 3.5 and transforms an ofx into a dataset, this may help with what you're trying to do.
I'm getting some serious weirdness using FileVersionInfo.GetVersionInfo() and was hoping somebody might be able to help.
The basics of the issue is that I am iterating through all the files in a folder calling GetVersionInfo() on each. There are about 300 files. This works ok for all but 2 of the files. For these DLLs I am getting comepletely incorrect info back from GetVersionInfo().
In order to eliminate all other variables, I extracted this call into a simple test app and it still got the same problem. However, if I built the test app as a Windows Application (it was a Console Application initially) then the data came back correct.
Just to clarify, the incorrect data coming back when running as a Console App is not simply null info like you would get if the file didn't contain version data. It contained reasonable data, but just the wrong data. It's as if it's reading it from a different file. I've looked for a file that contains matching version data, but can't find one.
Why is this simple call functioning differently if built as a Console Application rather than a Windows Application?
If anyone can help with this I would be very grateful.
Rgds,
Andy
-- Code Added
using System;
using System.Diagnostics;
namespace test
{
class Program
{
static void Main(string[] args)
{
string file = "C:\\ProblemFile.dll";
FileVersionInfo version = FileVersionInfo.GetVersionInfo(file);
string fileName = version.FileName;
string fileVersion = version.FileVersion;
Console.WriteLine(string.Format("{0} : {1}", fileName, fileVersion));
}
}
}
This behaviour seems weird indeed. Could it be that the Console application does not load the DLL from the same place as the WinForms application does? This would mean that GetVersionInfo uses some other API than just Win32 CreateFile (maybe going through some DLL resolver mechanism, side-by-side or whatever); remember that under the covers, version.dll will be executing your request, not the CLR itself.
Looking at FileVersionInfo through Reflector points in another direction yet:
public static unsafe FileVersionInfo GetVersionInfo(string fileName)
{
// ...
int fileVersionInfoSize = UnsafeNativeMethods.GetFileVersionInfoSize(fileName, out num);
FileVersionInfo info = new FileVersionInfo(fileName);
if (fileVersionInfoSize != 0)
{
byte[] buffer = new byte[fileVersionInfoSize];
fixed (byte* numRef = buffer)
{
IntPtr handle = new IntPtr((void*) numRef);
if (!UnsafeNativeMethods.GetFileVersionInfo(fileName, 0, fileVersionInfoSize, new HandleRef(null, handle)))
{
return info;
}
int varEntry = GetVarEntry(handle);
if (!info.GetVersionInfoForCodePage(handle, ConvertTo8DigitHex(varEntry)))
{
int[] numArray = new int[] { 0x40904b0, 0x40904e4, 0x4090000 };
foreach (int num4 in numArray)
{
if ((num4 != varEntry) && info.GetVersionInfoForCodePage(handle, ConvertTo8DigitHex(num4)))
{
return info;
}
}
}
}
}
return info;
}
As you can see there, some interesting dance is going on with code pages. What if the DLLs you inspected had several version information resources attached to them? Depending on the culture of the program calling into GetVersionInfo, I guess that the code page related calls could return other results?
Take the time to check the resources of the DLLs and make sure that there is only one language/code page for the version information. It might point you at the solution, I hope.
Sure the "files" you're seeing aren't . and .. ? If you iterate through all files, you'll always see entries for . (current dir) and .. (up dir). GetVersion Info might well return anything for these. You'd have to filter these entries out manually by name.
File and Assembly versions are 2 different things.
Are you sure you are not expecting the other?
Update: Tried this. Didn't work.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace test
{
class Program
{
[DllImport("COMCTL32")]
private static extern int InitCommonControls(int nExitCode);
static void Main(string[] args)
{
InitCommonControls(0);
string file = "C:\\ProblemFile.dll";
FileVersionInfo version = FileVersionInfo.GetVersionInfo(file);
string fileName = version.FileName;
string fileVersion = version.FileVersion;
Console.WriteLine(string.Format("{0} : {1}", fileName, fileVersion));
}
}
}