C# TypeInitiializationException - c#

I have a C# program running under Visual Studio 15 .NET Framework 4.5.2. It uses AutoMapper 4.1.1. It's been running fine for years. (I inherited it from someone else.) Just lately, it started erroring out at the line "AutoMappings.AutoMappings.CreateMaps();" Here's the relevant code:
using System;
using System.Windows.Forms;
using IVGOffice.UserInterface;
using System.Net;
using System.Net.Security;
namespace IVGOffice
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Assign certification callback to allow for self-signed certs on the services
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IVG.Common.Certificate.ValidateRemoteCertificate);
AutoMappings.AutoMappings.CreateMaps(); // <----- Errors out here
It throws a System.TypeInitiializationException with inner error "Configuration system failed to initialize". It never actually enters into the AutoMappings class, so I don't think the problem is related to the class, but here's the beginning of it anyway:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IVG.Common;
using IVG;
namespace IVGOffice.AutoMappings
{
public static class AutoMappings
{
private static bool mapsCreated = false;
private static Utilities2.Services services = new Utilities2.Services();
public static void CreateMaps()
{
// AutoMapper CreateMap should only be called once in an application domain. If we call this twice, check and just leave the second time
if (mapsCreated)
return;
// For every IAutomappedObject
System.Reflection.Assembly assm = System.Reflection.Assembly.GetCallingAssembly();
var interfaceTypes = assm.GetTypes();
var automappedTypes = interfaceTypes.Where(type => typeof(IAutomappedObject).IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);
foreach (var type in automappedTypes)
...
My coworker tried running the same code on his laptop and it worked fine, so there must be something going on with my copy of Visual Studio or my computer settings. I've tried running different versions of the program, rebooting, restoring the program from backup, etc. to no avail.
Anybody have any ideas? Thanks.

I hit this today because I stupidly placed appSettings before the configSections in my app.config file.
The error possibly indicates that your config file contains illegal syntax/layout. I'd start your investigation there.

The problem was in the configuration, but not in app.config. I had added code to save and restore the window status, location, and size. These settings were saved into a new user.config file. The problem was that I had added this code to a new git repo. My boss had to approve the changes before merging them into the master repo. In the meantime, I had gone back to the master to start a new project. The master didn't have the new code, but the new user.config file was still there. For some reason, that seems to have confused the program. When my boss finally merged the new code and I updated my copy of the master, the problem went away. Thanks for your feedback.

Related

How can I add a static 'Main' method suitable for an entry point?

I am getting an error on my code that says "Error CS5001
Program does not contain a static 'Main' method suitable for an entry point"
I am coding in C# using Microsoft Visual Studio and .NET. This is my code.
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;
class projectsummer
{
[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
string strFileName = "C:\\DRAFT.dwg";
DocumentCollection acDocMgr = Application.DocumentManager;
if (File.Exists(strFileName))
{
acDocMgr.Open(strFileName, false);
}
else
{
acDocMgr.MdiActiveDocument.Editor.WriteMessage("File " + strFileName +
" does not exist.");
}
}
}
I am not sure how to go about this error. Thank you!
Looking at this post and your previous question, let's try and break down what's going on.
You created a new Console application in Visual Studio. You did not tick "Do not use top level statements". This gave you a Program.cs file that was essentially empty (there was no "Main" method visible).
You erased the Hello World code given to you, and went to make a static method - the code from your previous question.
Damien_The_Unbeliever commented that based on the error, you put your method inside a "top level statement" file, and to put your method inside a class.
You wrap your method (which is still inside Program.cs) in a class, and now suddenly you get a Can't Find Entry Point error.
User Ryan Pattillo posted a great explanation of the original issue - where your method was "by itself" in the Program.cs file. You should follow their advice, but you should also ensure that this class is in its own file.
You should end up with this:
Program.cs
// this is the entire contents of the file
using ConsoleApp1;
ProjectSummer.OpenDrawing();
ProjectSummer.cs
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;
namespace ConsoleApp1
{
public class ProjectSummer
{
[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
// ...
}
}
}
Change ConsoleApp1 to the name of your project.
The entry point of your application, which right now is the only file that has "top level statements", remains Program.cs, thus you fix the Can't Find Entry Point error.
Another adjustment you can make, which seeing you're new to C# might be useful, is to not use top level statements at all. Modify your Program.cs to this:
namespace ConsoleApp1
{
internal static class Program
{
// this is your program's entry point
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
ProjectSummer.OpenDrawing();
}
}
}
Change ConsoleApp1 to the name of your project.
You cannot use the AutoCAD .NET API out of process. To be able to use the AutoCAD .NET libraries, you have to build a "class library" project (DLL) and NETLOAD this DLL from a running AutoCAD process. See this topic about in-process vs out-of-process and you can start from this other one to see how to create an AutoCAD .NET project.

IComponentConnector.Connect(int, object)' is explicitly implemented more than once. WPF

I am working on a WPF project and I just came across a weird error, I have code that runs perfectly fine but has 16 errors in the form of 2:
IComponentConnector.Connect(int, object)' is explicitly implemented more than once
(In the same document at the same space I might add) and 14 ambiguity errors due to this. All of this happened after I added a button, but removing it does nothing.
As I said before the project runs perfectly fine, but it seems to think as if there are duplicates of the code?
Completely recreating the window does nothing either and the "errorscribbles" don't even show up. I seem to be only one suffering from this as I could not find anything online cept This which is a similar but not equal problem.
Could it be the version I am running? I have .NET 5.0, but changing this does nothing. I am really out of ideas and in the worst case scenario il just live with the errors.
The code that is getting the error:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Eu4MissionDesigner
{
/// <summary>
/// Interaction logic for DirSelectWindow.xaml
/// </summary>
public partial class DirSelectWindow : Window
{
public DirSelectWindow(FileDirs FileDirectories)
{
InitializeComponent();
FileDirs fdDW = FileDirectories;
if (fdDW != null)
{
if (fdDW.LocDir == null) { LocDirBlock.Text = "No Directory"; } else { LocDirBlock.Text = fdDW.LocDir; }
if (fdDW.ImgDir == null) { ImgDirBlock.Text = "No Directory"; } else { ImgDirBlock.Text = fdDW.ImgDir; }
if (fdDW.MisDir == null) { MisDirBlock.Text = "No Directory"; } else { MisDirBlock.Text = fdDW.MisDir; }
}
}
private void LocButtClick(object sender, RoutedEventArgs e)
{
}
}
}
It is really simple code and I don't see what could be wrong. It keeps referring to:
public DirSelectWindow(FileDirs FileDirectories)
as if it is something wrong (no errors in other documents, could post entire project if necessary).
Sorry for my English, I am using the last of my mental capacity left to write this
With my issue, After Copying a View, or some of another's code, I'd have to go into the new view's .cs file and manually change the Partial Class and the public class because they also duplicated from the copied view.
I restarted my computer and it fixed itself. Mind you, restarting the program itself did nothing. This must have been something to do with my windows, maybe an update?
In my case this seems to have been caused by a project directory which contained other projects inside it. That seems to work fine in .NET Framework, but .NET Core showed the inside projects as folders of code in the top project causing duplicate code that VS is complaining about.
Solution - make each project a separate directory in the solution.

Kusto Connection with cluster using C# {kusto.data}

I'm trying to establish connection to Azure DataExplorer cluster using C# ..
I referenced the C# in https://learn.microsoft.com/en-us/azure/kusto/api/netfx/about-kusto-data
and installed nuget package kusto.data in visual studio and copied the code and did dotnet run in cmd prompt, but it didn't work.
Below is my code-
using Microsoft.Azure.Management.Kusto;
using System;
namespace LensDashboradOptimization
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//var clusterUrl = "https://masvaas.kusto.windows.net";
//var kcsb = new Kusto.Data.KustoConnectionStringBuilder(clusterUrl);
//Console.WriteLine(kcsb);
// Read the first row from reader -- it's 0'th column is the count of records in MyTable
// Don't forget to dispose of reader when done.
var client = Kusto.Data.Net.Client.KustoClientFactory.CreateCslQueryProvider("https://masvaas.windows.net/Samples;Fed=true");
var reader = client.ExecuteQuery("MyTable | count");
Console.WriteLine(reader);
}
}
}
I tried both fed=true and WithAadUserPromptAuthentication(); both didn't work. Am I missing something?
Hello and welcome to Stack Overflow!
I tried and faced a similar error when I was checking this out. But the issue turned out to be with the version of .Net Framework that I was running. The Kusto.Data package requires .Net Framework 4.6.2 as a dependency. When I had that installed, I was able to install and import the package, and also subsequently connect to the intended Kusto cluster and read data. This is the snippet that worked for me:
using System;
using Kusto.Data;
namespace hello_world
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var client = Kusto.Data.Net.Client.KustoClientFactory.CreateCslQueryProvider("https://help.kusto.windows.net/Samples;Fed=true");
var reader = client.ExecuteQuery("StormEvents | sort by StartTime desc | take 10");
}
}
}
Please double check on the dependencies and let me know if you still run into issues. Hope this helps!
using Kusto.Data;
using Kusto.Data.Common;
using Kusto.Data.Net.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Only these using statement do the job that you are trying to. For that all you need to install SDK from nuget gallery .
Also, only install Microsoft.Azure.Kusto.Data and Microsoft.Azure.Management.Kusto from above. That is sufficient.
Hope this help.
Few more things you can look on as: 1) Static IP 2)VS 2019 community edition with Azure dev packages installed
WithAadUserPromptAuthentication, this method is not supported now as kusto database first need authentication for the user. and the console application is not able to open a prompt window. I recommend to use a web application.

C# - How do I build/debug this code in VS2015?

I was given some code for a simple text file parser that I would like to build on and modify. It was built in VS and I've installed VS2015 Community so that I can work with it, but for the life of me I can't figure out how to set it up in VS2015.
A snippet of the very beginning of the code is below. Do I build it as a class, or a console application, or something else? How can I modify it to read a local file line by line?
Any help would be tremendously appreciated!
using System;
using System.Collections.Generic;
using System.IO;
public static class Cawk
{
public static IEnumerable<Dictionary<string, object>> Execute(StreamReader input)
{
Dictionary<string, object> row = new Dictionary<string, object>();
string line;
//string[] lines = File.ReadAllLines(path);
//read all rows
while ((line = input.ReadLine()) != null)
{
The snippet you posted is a class file definition.
You will need a class called Cawk.cs with that code inside.
To run it, you will need something to invoke it, either a console app or a unit test will do.
For a console app:
create a new console application project.
add a new class named Cawk.cs with your code inside.
in the 'program.cs' class (created when you create the console project), inside the Main method, call your Execute method.
To debug it, put a breakpoint on a line and press F5.
Considering you've never build an application in visual studio, the easiest way are:
Start VS
Create new project: File -> New -> Project
Select Templates -> Visual C# -> "Console application"
Choose a folder to save the project, click OK.
That will give you a basic console application with one file Program.cs that has static method Main() inside. Now let's add the new class.
Right click the solution tree, choose Add -> New item
Choose "Class", enter name "Cawk", click OK.
You will create a new file "Cawk.cs" for Cawk class. Let's fill it up.
Copy-paste your snippet in Cawk.cs, overwriting it's contents.
Correct the namespace - it should be the same as in the Program.cs
So it will become something like:
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
public static class Cawk
{
...
Now you can call Cawk.Execute() static method from the Main() method.
The method Execute() accepts a StreamReader object. This object reads data from a byte stream - a flow of data coming from some kind of source - user input, file, another application, etc.
In order to parse a file through Cawk you need to instantiate StreamReader first with a proper constructor, and dispose it afterwards (see "using" statement in C#).
Let me provide you an example of code:
using (var sr = new StreamReader("C:\temp\file.txt"))
{
var results = Cawk.Execute(sr);
foreach (item in results)
{
// do something with item which is Dictionary<string, object>
}
}

How to use LAME (lame_enc.dll) in my C# web site

I am trying to use the lame_enc.dll in my C# .NET website and I am stuck.
I am working with: .NET Framework 3.5 / Visual Web Developer 2008 Express Edition / (Anything else you'd need to know?)
The first thing I did was get the code from C# MP3 Compressor on The Code Project. One thing I noted is that this project/post is from January 2004 (so, it's old)
I put the folders "yeti.mmedia" and "yeti.mp3" in my "App_Code" directory and deleted the "Bin" and "obj" directories within each. Then I tried to build the project. When I got errors I ended up excluding from the project the following files:
yeti.mmedia/AssemblyInfo.cs
yeti.mmedia/EditWaveWriter.cs
yeti.mmedia/EditWaveWriter.resx
yeti.mmedia/InFormatEdit.cs
yeti.mmedia/InFormatEdit.resx
yeti.mmedia/NumericTextBox.cs
yeti.mmedia/NumericTextBox.resx
yeti.mmedia/Win32Functions.cs
yeti.mp3/AssemblyInfo.cs
yeti.mp3/EditMp3Writer.cs
yeti.mp3/EditMp3Writer.resx
These seem to me to be the code files related to the Windows UI (which I don't need sonce I'm doing this on the web).
I also put the file "lame_enc.dll" in the Bin directory.
I created a test page based on the example on the page linked above:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using WaveLib;
using Yeti.MMedia;
using Yeti.MMedia.Mp3;
public partial class Documents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WaveStream InStr = new WaveStream(Server.MapPath(#"Temp/SomeFile.wav"));
try {
Mp3Writer writer = new Mp3Writer(new FileStream(Server.MapPath(#"Temp/SomeFile.mp3"), FileMode.Create), InStr.Format);
try {
byte[] buff = new byte[writer.OptimalBufferSize];
int read = 0;
while ((read = InStr.Read(buff, 0, buff.Length)) > 0) {
writer.Write(buff, 0, read);
}
}
finally {
writer.Close();
}
}
finally {
InStr.Close();
}
}
}
So, then I load this page and the error I get is:
Unable to load DLL 'Lame_enc.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
(I can't add the DLL as a reference in my project because it says "...This is not a COM component.") I have also tried getting the latest and greatest (lame3.98.4) dll and had the same problems. So, I assume there is something different about using this code in a website rather than another type of project. What it is I don't know though.
My guess, having not used LAME, is you have to install in on the box in question. After that, you should be able to use the code project code successfully. If that does not work, it appears Lame_Enc.dll is a native component and you will have to PInvoke methods.

Categories