TypeInitializationException with EPPlus script - c#

I am trying to run a script to read values from an Excel sheet using EPPlus and load them into a list of tuples.
However when I run the script I am getting two errors, the first is:
An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
I have seen in other posts that I need to check for the inner exception, however none is offered by Visual Studio 15.
This is all the exception details that are available.
System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
Additional information: The type initializer for 'CGCompare2.Program' threw an exception.
Then when I close the VS15 exception window I get a pop up dialogue:
Cannot access a disposed object.
Object name: 'HwndSourceAdapter'
I am unsure what the issue is, if this is caused by my code or not. Any help, much appreciated.
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using OfficeOpenXml;
namespace CGComparer
{
class Program
{
private static List<Tuple<string, string>> _listTop;
private static List<Tuple<string, string>> _listGNED;
private static Base _baseCell;
private static ExcelPackage _package = new ExcelPackage(new FileInfo(_excelFile));
private static string _excelFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"Compare GNED and TOP V1.0.xlsx");
static void Main(string[] args)
{
_baseCell = new Base(1, 2);
_listTop = ColumnsToList(_baseCell.Column(),_baseCell.Row());
_baseCell = new Base(3, 2);
_listGNED = ColumnsToList(_baseCell.Column(),_baseCell.Row());
}
public static List<Tuple<string, string>> ColumnsToList(int column, int row)
{
var list = new List<Tuple<string, string>>();
var ws = _package.Workbook.Worksheets[1];
var ListIsValid = true;
do
{
var userEmail = (string)ws.Cells[column, row].Value;
var customerGroup = (string)ws.Cells[column + 1, row].Value;
if (!string.IsNullOrEmpty(userEmail))
{
list.Add(new Tuple<string, string>(userEmail, customerGroup));
row = row++;
}
else
{
ListIsValid = false;
}
} while (ListIsValid);
return list;
}
}
}
Base.cs
namespace CGComparer
{
public class Base
{
private static int _column;
private static int _row;
public Base(int column, int row)
{
_column = column;
_row = row;
}
public int Column()
{
return _column;
}
public int Row()
{
return _row;
}
}
}

So, turns out the issue was staring me in the face, I went through below steps provided by, Hans Passant in the issue comments:
"The debugger in VS2015 is a crappy bag 'o bugs, it won't let you look
at the InnerException. Use Tools > Options > Debugging > General >
tick "Use Managed Compatibility Mode" and now you can see it. Careful
with those statics, their initializer can byte you in the rear end
badly."
It was a null reference exception caused by me declaring the excel file with a path argument that had yet to be declared itself.
private static ExcelPackage _package = new ExcelPackage(new FileInfo(_excelFile));
private static string _excelFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"Compare GNED and TOP V1.0.xlsx");

Related

Error "Missing closing curly bracket" while all curly brackets are closed?

I am trying to code a card game, and I'm making a shuffling system using a function, however it's telling me I need a closing bracket while all my brackets are closed. It's also asking me for an end-of-file or namespace definition. I'm using an online editor (dotnetfiddle.net) to edit this code, if that changes anything.
Here's my current code-
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
List<string> shuffle(List<string> l) { //ERROR 1: } expected
int count = l.Count-1;
List<string> ret = new List<string>();
int ind = 0;
Random rng = new Random();
string card = null;
while (count > -1) {
ind = rng.Next(0, count);
card = l[ind];
l.RemoveAt(ind);
ret.Add(card);
card = null;
count--;
}
return ret;
}
List<List<string>> playerHands = new List<List<string>>();
//💧🔥🌀🌱 (copypaste symbols)
List<string> deck = new List<string> {"1💧", "2💧", "3💧", "4💧", "5💧", "6💧", "7💧", "8💧", "9💧", "1🔥", "2🔥", "3🔥", "4🔥", "5🔥", "6🔥", "7🔥", "8🔥", "9🔥", "1🌀", "2🌀", "3🌀", "4🌀", "5🌀", "6🌀", "7🌀", "8🌀", "9🌀", "🌱1", "🌱2", "🌱3", "🌱4", "🌱5", "🌱6", "🌱7", "🌱8", "🌱9"};
List<string> sDeck = new List<string> {"R🔄", "S❌", "D🔳", "X⛈", "+✨", "A🌕", "A🌑"};
List<string> vDeck = new List<string> {"V◆", "V◇", "V◈"};
}
}//ERROR 2: Namespace, type, or end-of-file expected
Maybe it is related to the C# version you used.
Local functions are only allowed when using C# 7.
When I pasted your code in VS 2019, the compilation succeeded.
The only warning I have, is related to the function shuffle() that is declared but never used.
Also, always put your class in a namespace.

How to use CommandLineParser in a WinForms Project? How to build a custom Help MessageBox?

I'm trying to use the CommandLineParser Library in Version 2.5.0 in a WinForms application.
It works great except for a help screen (MessageBox in that case).
I already figured out that I need to create a own parser and set at least the HelpWriter property to null to create a custom Help Screen.
But when the application is called with --help argument my "Error handler" just get one error instance with a Tag of type CommandLine.ErrorType and a Value of HelpRequestedError
Now how to build the custom Help Screen?
https://github.com/commandlineparser/commandline/wiki/Generating-Help-and-Usage-information
This site suggests to use the Types in CommandLine.Text Namespace but how? There are zero examples how to do it.
Anyone here did something like this?
I have the following code:
namespace myWorkspace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using CommandLine;
using DevExpress.XtraEditors;
using Options;
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
internal static int Main(string[] args)
{
AppDomain.CurrentDomain.SetupInformation.PrivateBinPath = "bin";
WindowsFormsSettings.EnableFormSkins();
WindowsFormsSettings.EnableMdiFormSkins();
WindowsFormsSettings.ForceDirectXPaint();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var parser = new Parser(config =>
{
config.AutoHelp = true;
config.AutoVersion = true;
config.CaseInsensitiveEnumValues = false;
config.CaseSensitive = false;
config.EnableDashDash = true;
config.HelpWriter = null;
config.IgnoreUnknownArguments = true;
//config.MaximumDisplayWidth
config.ParsingCulture = CultureInfo.InvariantCulture;
});
return Parser.Default.ParseArguments<RunOptions>(args)
.MapResult(
RunRunAndReturnExitCode,
RunParsingFailedAndReturnExitCode);
}
private static int RunRunAndReturnExitCode(RunOptions opts)
{
try
{
Application.Run(new MainForm());
}
catch
{
return -1;
}
return 0;
}
private static int RunParsingFailedAndReturnExitCode(IEnumerable<Error> errs)
{
foreach (var err in errs)
{
var locErr = err;
}
return 1;
}
}
}
And on Line var locErr = err; i don't know what to do to get a help screen message i can show in a MessageBox or the like.
CommandLineParser seems to support console output out-of-the-box for help or --help but I have no console app here.
Ok i now figured out a way to do it. Does not seem to be the best way but it works.
I create a StringBuilder instance and put it into a StringWriter instance
private static StringBuilder helpTextBuilder = new StringBuilder();
private static StringWriter helpTextWriter = new StringWriter(helpTextBuilder);
Then I create a new Parser with (at least this) Option(s):
var parser = new Parser(config =>
{
config.HelpWriter = helpTextWriter;
});
In the case of error I can now use what is written into the helpTextBuilder to show a message box.
private static int RunParsingFailedAndReturnExitCode(IEnumerable<Error> errs)
{
MessageBox.Show(helpTextBuilder.ToString());
return 1;
}
So this is now working for me.

Xbim Geometry error

I am using the following C# code to access geometry data from an ifc4 file. The file contains only a wall created using Revit 2016. I am using Xbim library. This is my code:
class Program
{
private static readonly ILog logger =
LogManager.GetLogger(typeof(Program));
static string _ifcFile = #"C:\Examples\OneWall.ifc";
static void Main(string[] args)
{
BasicConfigurator.Configure();
IfcStore model = IfcStore.Open(_ifcFile);
Xbim3DModelContext context = new Xbim3DModelContext(model);
context.CreateContext();
XbimMeshGeometry3D mesh = mesh = (XbimMeshGeometry3D)context.ShapeGeometryMeshOf(context.ShapeInstances().FirstOrDefault());
//The rest of my code
}
}
I get the following error. I am using visual studio 2015.
1226 [1] DEBUG Xbim.Geometry.Engine.Interop.XbimCustomAssemblyResolver (null) - Loading assembly from: C:\Examples\ifcWall\ifcWall\bin\Debug\x86\Xbim.Geometry.Engine32.dll
1404 [1] DEBUG Xbim.Geometry.Engine.Interop.XbimCustomAssemblyResolver (null) - Loading assembly from: C:\Examples\ifcWall\ifcWall\bin\Debug\x86\Xbim.Geometry.Engine32.dll
Unhandled Exception: System.Exception: Invalid Geometry Command
at Xbim.ModelGeometry.Scene.XbimMeshGeometry3D.Read(String data, Nullable1 trans) in c:\BuildAgent\work\860c3b913b6c647f\Xbim.ModelGeometry.Scene\XbimMeshGeometry3D.cs:line 219
at Xbim.ModelGeometry.Scene.XbimMeshGeometry3D.Add(String mesh, Int16 productTypeId, Int32 productLabel, Int32 geometryLabel, Nullable1 transform, Int16 modelId) in c:\BuildAgent\work\860c3b913b6c647f\Xbim.ModelGeometry.Scene\XbimMeshGeometry3D.cs:line 669
at Xbim.ModelGeometry.Scene.Xbim3DModelContext.ShapeGeometryMeshOf(XbimShapeInstance shapeInstance) in c:\BuildAgent\work\860c3b913b6c647f\Xbim.ModelGeometry.Scene\Xbim3DModelContext.cs:line 1525
at ifcWall.Program.Main(String[] args) in C:\Users\karshenas\Documents\Courses\CEEN6840\VS_Projects\ifcWall\ifcWall\Program.cs:line 26
Any help to fix the error is appreciated.
You run into an area where API has changed and this particular functions expects data in a different format. If what you need is a triangulation of the shape this code should work for you:
using System.IO;
using Xbim.Common.Geometry;
using Xbim.Ifc;
using Xbim.ModelGeometry.Scene;
using Xbim.Common.XbimExtensions;
namespace CreateWexBIM
{
class Program
{
static void Main(string[] args)
{
const string file = #"4walls1floorSite.ifc";
var model = IfcStore.Open(file);
var context = new Xbim3DModelContext(model);
context.CreateContext();
var instances = context.ShapeInstances();
foreach (var instance in instances)
{
var geometry = context.ShapeGeometry(instance);
var data = ((IXbimShapeGeometryData)geometry).ShapeData;
using (var stream = new MemoryStream(data))
{
using (var reader = new BinaryReader(stream))
{
var mesh = reader.ReadShapeTriangulation();
}
}
}
}
}
}
The best is to ask in xBIM GitHub Issues and to share the file. IFC geometry can get very complex so it is not possible to really answer your question just based on the exception.

unhandled exception c# dll

I tring to test a new dll that I've build for c#
private void button1_Click(object sender, EventArgs e)
{
String [] first = UserQuery.Get_All_Users();
//MessageBox.Show(first);
}
but I get the following error at String [] first = UserQuery.Get_All_Users();
An unhandled exception of type 'System.NullReferenceException' occurred in User_Query.dll
Additional information: Object reference not set to an instance of an object.
I been tring to figure this one out for hours but can't find any null varibles
I post my dll in case the dll is wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace User_Query
{
public class UserQuery
{
public static string[] Get_All_Users()
{
string[] names = new string[10];
var path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
byte i = 0;
foreach (var name in userNames)
{
Console.WriteLine(name);
names[i] = name;
i++;
}
return names;
}
}
}
}
There is a problem with your. path variable... since there should be \\ instead of //
The problem here turned out not to be the code but be VS2010 not loading the dll. This happen because I decided to change the program from using the dll from the debug to the release version but I did not clean the project after doing it and therefore the program was not correctly loading the dll. All that need to be done was clean the project

How to get error info from dynamic C# code compiling

I have a C# application which uses a C# script interface. That means that my application will compile C# code and run it.
I am using the System.CodeDom.Compiler class to do it with.
The problem is that if I run the code below it throws an InvalidCastException because it is trying to cast a string to an int in my dynamic code.
If I catch the exception I have no indication where in the 'dynamic code' that error occured. For instance 'InvalidCastException on line 8'.
I get a stack trace, but no line numbers.
Any ideas? I want to present to our users enough information to know where their error is.
public class NotDynamicClass
{
public object GetValue()
{
return "value";
}
}
class Program
{
public static void Main()
{
var provider = CSharpCodeProvider.CreateProvider("c#");
var options = new CompilerParameters();
options.ReferencedAssemblies.Add("DynamicCodingTest.exe");
var results = provider.CompileAssemblyFromSource(options, new[]
{
#"
using DynamicCodingTest;
public class DynamicClass
{
public static void Main()
{
NotDynamicClass #class = new NotDynamicClass();
int value = (int)#class.GetValue();
}
}"
});
var t = results.CompiledAssembly.GetType("DynamicClass");
t.GetMethod("Main").Invoke(null, null);
}
}
You need to set IncludDebugInformation to true on your CompilerParameters.
Update: At the bottom of the MSDN documentation there is a community remark:
For C#, if you set this property to true you need to also set GenerateInMemory to false and set the value of OutputAssembly to a valid file name. This will generate an assembly and a .pdb file on disk and give you file and line number information in any stacktraces thrown from your compiled code.

Categories

Resources