C# ini-parser issues - c#

I found that C# didn't directly support ini files, so I went on the prowl and found the following library called ini-parser. The usage shows an extremely simple example, but for some reason I can't get Visual studio 2010 to like it. If I copy the following exactly from the wiki on their web page:
IniParser.FileIniDataParser parser = new FileIniDataParser();
IniData parsedData = parser.LoadFile("TestIniFile.ini");
I get the following error, with the parser part of parser.LoadFile() underlined and the following error:
Error 1 A field initializer cannot reference the non-static field,
method, or property
'WindowsFormsApplication1.Form1.parser' C:\Users\Support\Documents\Visual
Studio
2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 28 30 WindowsFormsApplication1
I'm not sure what to make of what it's saying, or how to fix it. Can someone else offer up a suggestion/solution?

You're trying to do this in a field initializer. You're not allowed to refer to this within an instance field initalizer. Do it in the constructor instead:
private readonly IniData configuration;
public Form1()
{
InitializeComponent();
IniParser.FileIniDataParser parser = new FileIniDataParser();
configuration = parser.LoadFile("TestIniFile.ini");
}
Or just do it inline without a separate variable for the parser at all:
private readonly IniData configuration =
new FileIniDataParser().LoadFile("TestIniFile.ini");
(I'm assuming you don't actually need the parser for anything else, so it's pointless using a field for it.)

The error message is basically saying that you can't use parser (another field) within a field initializer of the class (the initializer for parsedData).
You have to put this logic in the constructor:
FileIniDataParser parser = new FileIniDataParser();
IniData parsedData;
public Form1()
{
InitializeComponent();
parsedData = parser.LoadFile("TestIniFile.ini");
}

Related

Kafka Producer Error: ' Value serializer not specified and there is no default serializer defined for type ...'

I just started using Kafka and hit the following rookie error:
'Value cannot be null.
Parameter name: Value serializer not specified and there is no default serializer defined for type ActMessage.'
It happens when trying to send a class object, ActMessage object, rather then the a simple string that comes with the example. The line of code that raises the erros is:
using (var p = new ProducerBuilder<Null, ActMessage>(config ).Build()
I am using the .net client.
My understanding is that i need to use one of the default serializes in the first type parameter, one that come with Kafka client, as explained here, but can't find them on this .net package.
I guess i could build one but that would be a waste of time.
Here a reproducible example:
public class ActMessage {
public int SomeId {get;set;}
public string SomeContent {get;set;}
}
class Tester {
void send(){
var config = new ProducerConfig { BootstrapServers = "localhost:9092" };
using (var p = new ProducerBuilder<Null, ActMessage>(config).Build()) //throws error here
{
var dr = p.ProduceAsync("news", new Message<Null, ActMessage>
{
Value = new ActMessage { SomeId = 1, SomeContent="hi" },
}
).Result;
}
}
}
I suggest checking out the working examples/ dir in that repo to see working code that you can copy into your own projects.
If you have your own class, you need to implement the ISerializer and IDeserializer interfaces.
Or you can use the built-in ones
However, an alternative is to use Avro
This requires writing an Avro schema file, then using avrogen to create your class, not manually write it. E.g.
dotnet tool install --global Apache.Avro.Tools
avrogen -s User.avsc .
Then you must always add some ValueSerializer in Kafka clients in order to send data

Why can't I see my XML documentation when decompiling using ICSharpCode.Decompiler?

I've been looking into decompiling .dlls using ICSharpCode.Decompiler and found some sample code and fingers in the right direction on this thread:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/00e59445-9f85-4ec5-a04f-9796a72a00a2/library-to-decompile-assembly-to-c
I've copied the code and added set the variable ShowXmlDocumentation = true in the DecompilerSettings, however I'm still unable to see my documentation.
My source code looks like this:
var settings = new DecompilerSettings
{
FullyQualifyAmbiguousTypeNames = true,
ShowXmlDocumentation = true
};
const string assemblyName = "Experiments.Decompilation.dll";
var assembly1 = AssemblyDefinition.ReadAssembly(assemblyName);
var decompilerContext = new DecompilerContext(assembly1.MainModule) {Settings = settings};
var decompiler = new AstBuilder(decompilerContext);
decompiler.AddAssembly(assembly1);
var output = new StringWriter();
decompiler.GenerateCode(new PlainTextOutput(output));
var byteArray = Encoding.ASCII.GetBytes(output.ToString());
TextReader codeReader = new StreamReader(new MemoryStream(byteArray));
var line = codeReader.ReadToEnd();
Yet the variable line never has any of the expected XML documentation in it.
I get the full trace of what's in the .dll, for example
namespace Experiments.Decompilation
{
public interface ITest
{
long Method();
}
}
But I was expecting the interface method to have the XML docs I defined, a la
namespace Experiments.Decompilation
{
///<summary>
///This is some test documentation
///</summary>
public interface ITest
{
long Method();
}
}
But no cookie for me.
Am I missing anything? Do I need to change any other configuration?
If anyone has any ideas on this I'd really appreciate it. I've been wracking my brains and haven't found a solution myself, so here you are SO, please help!
Because that property doesn't actually do anything within the ICSharpCode.Decompiler library. It's just there to support projects (like ILSpy) that want to consume the decompiler.
ILSpy, for example, will check to see if the decompiler has the option set; if so, it will look up the appropriate XML file on-disk and parse the XMLDoc strings, and embed them in the final output.
Also, note that the actual .NET assembly doesn't have the XMLDoc in it. Visual Studio generates a separate file with that stuff, and if you don't have that, ILSpy won't be able to include XMLDoc even if you ask.

Can't find suitable Main method

I'm trying to create a Windows Form Application, that can create another Windows Form Application. But the error i'm getting when i'm trying to compile with CodeDom in the c# code, is a weird one.
'kjpUnityGameLauncherTemplate.RunLauncher' does not have a suitable static Main method
This kinda confuses me, since the class "RunLauncher" DOES have a main method, with the default setup described at the (http://msdn.microsoft.com/) site.
RunLauncher class: http://pastebin.com/NU3VYwpv (which have the main method)
The code i'm using to actually compile this via. CodeDom is this:
if (codeProvider.Supports(GeneratorSupport.EntryPointMethod))
{
parameters.MainClass = "kjpUnityGameLauncherTemplate.RunLauncher";
}
CodeCompileUnit compileUnits = new CodeCompileUnit();
CodeNamespace nsp = new CodeNamespace("kjpUnityGameLauncherTemplate");
parameters.CompilerOptions = "/main:kjpUnityGameLauncherTemplate.RunLauncher";
CodeTypeDeclaration class1 = new CodeTypeDeclaration("RunLauncher");
nsp.Types.Add(class1);
CodeTypeDeclaration class2 = new CodeTypeDeclaration("kjpUnityGameLauncher");
nsp.Types.Add(class2);
CodeTypeDeclaration class3 = new CodeTypeDeclaration("Launcher");
nsp.Types.Add(class3);
nsp.Imports.Add(new CodeNamespaceImport("kjpUnityGameLauncherTemplate"));
compileUnits.Namespaces.Add(nsp);
CompilerResults results = icc.CompileAssemblyFromDom(parameters, compileUnits);
Theres some other stuff like declaration of the variables "codeProvider" etc. but those aren't the problem in this case, which is why I didn't include them.
To Create an Executable Your code must have an Entry Point Method declared and set properly to run in CodeDom. I do not see one declared in your example above. Below I have an example from MSDN located at
http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx
CodeEntryPointMethod start = new CodeEntryPointMethod();
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression("System.Console"),
"WriteLine", new CodePrimitiveExpression("Hello World!"));
start.Statements.Add(cs1);

"is a field and used like a type" error

I am trying to use StringBuilder in a C# Class Library project. I have added the using statement and all. I am not getting intellisense and I am getting a compile error.
Eg:
StringBuilder sb= new StringBuilder();
sb.Append("");
I am seeing an error on the variable sb, that
sb is a field and used like a type.
Any help is appreciated.
Without looking at your complete code I can only guess that you are writing your code directly in the class, Following line should be inside a method
sb.Append("");
For the class it should be like:
using System.Text; //make sure this is included.
public class MyClass
{
StringBuilder sb = new StringBuilder();
public MyClass() //Constructor
{
sb.Append(""); //this statement should be inside a method
}
}
Currently it would be like:
In order to use the StringBuilder class you need to reference it's library properly.
Add using System.Text; to the top of your class

Using application's *.resx from a generic DLL

I'm creating a generic DLL that creates documents from models and can be used either for winForms or for webForms. It's composed of a main class that I instantiate with certain parameters.
I'd like my DLL to be able to lookup in the resource files without being tied down to 1 technology.
So to say, I know how to access my resource files (*.resx) in a WebForm :
HttpContext.GetGlobalResourceObject("Global", "myLabel")
I have a few restrictions :
I don't want to transfer the HttpContext to the DLL as it will tie it to the application
I don't want to rename the resource files from *.resx to *.resource because they are used in the application
I don't want to pass all the labels over to the DLL because then my models won't be modifiable as I need
I'd like to place a marker in my document models that is like this <%resource(Global,myLabel)%>
I've been looking at passing the class a resource object using ResourceManager but it never gets hold of my *.resx files.
Does anyone know how to acheive the final goal? Either passing a resource object to the class either picking up the resource object from inside the class.
Ok, I found how to do this.
In my DLL, I overloaded the constructor allowing to give it a ResourceManagerobject. So here is what I have :
For the model file :
\paragraph
[
Style = "Normal"
]
{
<%resource(lblMontant)%> : <%montant%>
}
For the DLL using the ResourceManager :
public Reporter(String inputModel, String outputPdf, Dictionary<String, IParameter> parameters, ResourceManager resman)
{
// Assigne parameters to globals
_sourceFile = inputModel;
_destinationFile = outputPdf;
_parameters = parameters;
_rm = resman;
Worker();
}
private String parseResource(String val)
{
MatchCollection _matches = _resourceMatcher.Matches(val);
foreach (Match _match in _matches)
{
String _item = _match.Groups["item"].Value;
val = val.Replace(_match.Groups[0].Value, String.Format("{0}", _rm.GetObject(_item)));
}
return val;
}
For the caller, we use Resources.global that is considered a class :
ResourceManager _rm = new ResourceManager(typeof(Resources.global));
Reporter _cl = new Reporter(modelFilePath, outputFilePath, _params, _rm);
If this is useful to others and some need more details, don't hesitate to ask ;)

Categories