Why does ConfigurationManager not contain a definition for OpenExeConfiguration? C# - c#

I am sort of new to config files. I am aware that I can add key value pairs and that it's possible to access them and change them on the fly. I am attempting to implement the ChangeConfiguration method on https://blogs.msdn.microsoft.com/youssefm/2010/01/21/how-to-change-net-configuration-files-at-runtime-including-for-wcf/
However, I am getting:
"'ConfigurationManager' does not contain a definition for 'OpenExeConfiguration'"
...and I get the same for trying to use ConfigurationManager.RefreshSection()
I am aware that the instructions date back to 2010 so by the looks of it, these instructions seem to no longer be the correct procedure to do this...?
Context
Web UI tests using Specflow, Selenium WebDriver, NUnit
Class Library targeting .NET Framework 4.6.1
Trying to add key value pairs at runtime in App.config
using System.Configuration;
using System.Reflection;
namespace CoreSeleniumFramework.Managers
{
public class ConfigurationManager
{
static void ChangeConfiguration()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
appSettings.Settings.Clear();
appSettings.Settings.Add("name", "bar");
config.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
}

Answered by #Nastaran Hakimi
Ok so this is a thing... need to use...
System.Configuration.ConfigurationManager.OpenExeConfiguration
...when it seems I should just need...
using System.Configuration;
Edit: if you get "object reference not set to an instance of an object" (or in other words, GetEntryAssembly() returns null), use GetCallingAssembly()

Related

My System.CommandLine app won't build! It can't find a CommandHandler. Do I need to write it?

I am using VS 2022, .Net 6.0, and trying to build my first app using System.CommandLine.
Problem: when I build it, I get an error
The name 'CommandHandler' does not exist in the current context
The code I'm trying to build is the sample app from the GitHub site: https://github.com/dotnet/command-line-api/blob/main/docs/Your-first-app-with-System-CommandLine.md , without alteration (I think).
It looks like this:
using System;
using System.CommandLine;
using System.IO;
static int Main(string[] args)
{
// Create a root command with some options
var rootCommand = new RootCommand
{
new Option<int>(
"--int-option",
getDefaultValue: () => 42,
description: "An option whose argument is parsed as an int"),
new Option<bool>(
"--bool-option",
"An option whose argument is parsed as a bool"),
new Option<FileInfo>(
"--file-option",
"An option whose argument is parsed as a FileInfo")
};
rootCommand.Description = "My sample app";
// Note that the parameters of the handler method are matched according to the names of the options
rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
{
Console.WriteLine($"The value for --int-option is: {intOption}");
Console.WriteLine($"The value for --bool-option is: {boolOption}");
Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
});
// Parse the incoming args and invoke the handler
return rootCommand.InvokeAsync(args).Result;
}
I have installed the latest version of System.Commandline: 2.0.0-beta2.21617.1
SURELY I am just being a big fat idiot in some respect. But I don't see it.
Any insight would be welcomed.
This issue is caused by updating the CommandLine 2.0 Beta 2 package. Add the reference System.CommandLine.NamingConventionBinder to the references to fix the problem. Follow the announcements on command-line-api's GitHub account:
In your project, add a reference to System.CommandLine.NamingConventionBinder.
In your code, change references to the System.CommandLine.Invocation namespace to
use System.CommandLine.NamingConventionBinder, where the CommandHandler.Create
methods are now found. (There’s no longer a CommandHandler type in
System.CommandLine, so after you update you’ll get compilation errors until you
reference System.CommandLine.NamingConventionBinder.)
If you want to continue with the old habits, try using older versions of the System.CommandLine package.
References
Announcing System.CommandLine 2.0 Beta 2 and the road to GA
Think you are missing a using line:
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
I can't swear that's it, but it looks like CommandHandler is defined in a namespace not referenced by a using (in your current code), so System.CommandLine.Invocation may be the key!

System.Linq: The call is ambiguous between the following methods or properties

There is a old Asp.Net WebSite Project, opened in VS 2015 which targeting a 4.0 FrameWork Version, when I am trying to build it it gives me below error:
The call is ambiguous between the following methods or properties:
System.Linq.Enumerable.Contains<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource) and System.Linq.Enumerable.Contains<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource)
which both method signature looks exactly identical.
Here it code from the class:
using System;
using System.Collections.Generic; // Gray out
using System.Linq;
using System.Web; // Gray out
using System.Web.Routing;
using System.Web.UI; // Gray out
public class UrlRoute
{
public static string RegisterRoutes(string routes)
{
string MainUrl = routes;
string result = "";
if (MainUrl.Contains('\\')==true)
{
result = "CMS"
}
return result;
}
}
Project Properties:
Framework Details:
I tried solution from SO but none of them worked [delete bin folder, check unresolved references], don't understand the reason behind the error!
EDIT:
Same is happening for Last() and all that extension method from System.Linq:
Error CS0121 The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.Last(System.Collections.Generic.IEnumerable)' and 'System.Linq.Enumerable.Last(System.Collections.Generic.IEnumerable)'
Will love to share any other configuration/code if required.
You are most likely referencing two versions of System.Linq.dll. Project should use version from GAC, not local copy from BIN.
Try to find and remove explicit reference to System.Linq.dll in your C# project.
P.S. And if you have multiple projects in the solution, make sure they all target same version of .NET Framework.

Retrieve <Version> tag written in csproj file from dll [duplicate]

I am trying to get the executing assembly version in C# 3.0 using the following code:
var assemblyFullName = Assembly.GetExecutingAssembly().FullName;
var version = assemblyFullName .Split(',')[1].Split('=')[1];
Is there another proper way of doing so?
Two options... regardless of application type you can always invoke:
Assembly.GetExecutingAssembly().GetName().Version
If a Windows Forms application, you can always access via application if looking specifically for product version.
Application.ProductVersion
Using GetExecutingAssembly for an assembly reference is not always an option. As such, I personally find it useful to create a static helper class in projects where I may need to reference the underlying assembly or assembly version:
// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
public static readonly Version Version = Reference.GetName().Version;
}
Then I can cleanly reference CoreAssembly.Version in my code as required.
In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly property of a type found in the assembly.
The following example illustrates:
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Console.WriteLine("The version of the currently executing assembly is: {0}",
typeof(Example).Assembly.GetName().Version);
}
}
/* This example produces output similar to the following:
The version of the currently executing assembly is: 1.1.0.0
Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.
using System.Reflection;
{
string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}
Remarks from MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx:
The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.
Product Version may be preferred if you're using versioning via GitVersion or other versioning software.
To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:
using System.Diagnostics;
using System.Reflection;
//...
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.
Sourced from a combination of places:
https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

Get value of version out of project.json

In a DNX application, which uses a "project.json" file, is there a way to read the value of the "version" property out of the "project.json" file?
I'm writing a library that writes something to the current HTTP response and I would like to show the version of the application in there.
Any help on how this can be done is highly appreciated.
If you set the version attribute during build (or in any other way) you can do this like that:
using System;
using System.Reflection;
[assembly:AssemblyVersionAttribute("1.2.3")]
namespace Test
{
class Program
{
public static void Main()
{
var assembly = typeof(Program).GetTypeInfo().Assembly;
var name = assembly.GetName();
Console.WriteLine($"{name.Name}: {name.Version}");
}
}
}
I did it using the new dotnet cli which is replacing dnx but it should work with dnx dnxcore50 as well.
Are you writing a Class Library or an ASP.NET application?
If a class Library, you could copy the version string to a resource file that you read in during run-time to grab the version. It's kind hard to do this sort of thing with class libraries since you don't get the beauty of a Startup and IoC.
If ASP.NET, then just add a version into your appsettings.json configuration (or a custom json file to store settings) and read it in at startup: http://docs.asp.net/en/latest/fundamentals/configuration.html
Multipe ways of doing this if you are running in a the web application, not a class library.
First way custom attributes data (should check if attribute is available):
this.GetType().Assembly.GetCustomAttributesData()
.First(x => x.AttributeType.FullName == "System.Reflection.AssemblyInformationalVersionAttribute")
.ConstructorArguments[0];
Second way
var name = this.GetType().AssemblyQualifiedName;
name = name.Substring(name.IndexOf("Version=") + 8);
var verion = name.Substring(0, name.IndexOf(", "));

C#.NET Namespace name does not exist in namespace error - only when using is outside local namespace directive - why?

Using .NET 2.0, C#, Windows Forms development, Enterprise Library 3.1.
We have a project namespace (call it Project). We also have several sub-namespaces inside of that project, for example Project.Namespace1, Project.Namespace2, etc.
In one class, we define enums and such to be used with the Enterprise Library Logging block, like this:
namespace Project.Logging
{
public static class Logging
{
public enum LogPriority
{
// enum values here
}
}
}
In another class, I use the enum values so I need to declare a using statement. Same project, so there is no assembly to reference, right?
If I declare the using inside of the local namespace, like this, it works fine:
namespace Project.SomeName
{
using Project.Logging;
// code referencing the Logging enum
}
However, if I put the using statement outside of the local namespace declaration, I get the "type or namespace name 'LogPriority' does not exist in the namespace 'Project.Logging'... Like this:
using Project.Logging;
namespace Project.SomeName
{
// code referencing the Logging.LogPriority.whatever
}
Why is this? Has anyone run across this before?
I have run into similar (though not exactly the same) problems before when using a class that has the same name as its namespace.
Oddly enough it seemed to compile ok on some developers pc's but not on others. In the end we made sure that no namespace contained a class of the same name.
namespace Project.Logging
{
public static class Logging // this is what caused the probems for me
{
}
}
I also had a wired error. I cannot find any namespace which is coming from different assemblies, but begins with executing assembly name.
Finally, I found out that I have set the target framework to .NET framework client profile.
Yes, most likely you have an unusual value set for the "Default Namespace" in your project properties. I would validate the project configuration.
We ran into this issue before and it all went down to ambiguous naming of the namespace and the class name.
When we tried to have our namespace as Services.Web.xxx and also add in a service reference as Services.Web.xxxx and ALSO add a references to an assembly that was named Services.Web.xxx you can only imagine the problems we ran into.
In the end to fix it we simply did a rename to make sure that there was only one instance of the Services prefix
Also you could do the following and create an alias to LogPriority to LogEnum:
using LogEnum= Project.Logging.Logging.LogPriority;
namespace Project.SomeName
{
internal class MyClass
{
public MyClass()
{
LogEnum enum1 = LogEnum.None;
}
}
}
namespace Project.Logging
{
public static class Logging
{
public enum LogPriority
{
None,
Default
}
}
}
It definitely can make a difference if you have usings inside or outside the namespace. There is a good discussion here, and it is likely to be related to your default namespace settings.

Categories

Resources