The name 'HttpUtility' does not exist in the current context (winform) - c#

Iget the following error:
The name 'HttpUtility' does not exist in the current context
I am building a winform app this my code using framework 4 client profile
and I can't find the System.Web reference:
string longurl = "https://test.com/currentaccount/Pages/current.aspx";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);//error
query["ltFrom"] = FromDate;
query["ltTo"] = ToDate;
query["ltFilterSelected"] = "none";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
What is the problem?

HttpUtility cannot be accepted with ClientProfile - change your .Net version to full.

The project is set on Target Framework to: .net 4 client profile.
That's the problem. HttpUtility doesn't exist in the client profile. Target the full profile instead (and make sure you have a reference to System.Web.dll).
Compare the "Version information" line from the above documentation:
.NET Framework
Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
with that of (say) System.String:
.
NET Framework
Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Portable Class Library
Supported in: Portable Class Library
.NET for Windows Store apps
Supported in: Windows 8
ref: Im getting error on visual studio 2010: The type or namespace name 'HttpUtility' does not exist

to use "HttpUtility" simply add reference in visual studio from option Project->Add Reference->click on system.web then ok.

HttpUtility is based in System.Web, the Client Profile for .NET 4 only allows access to a subset of the .NET framework and System.Web is not included in that.
If you can, change from Client Profile to Full unless you have a really good reason to stick with Client Profile in which case you will need to find a different approach.

Related

Why WindowsIdentity class is not visible in .NET Core

Having the code below in VisualStudio 2017 .NET Core 2.0 Console App
using System;
using System.Security.Principal;
namespace smallTests
{
class Program
{
static void Main(string[] args)
{
var identity = WindowsIdentity.GetCurrent();
}
}
}
Why am I getting the error:
The name 'WindowsIdentity' does not exist in the current context
If I can see this class in .NET Core 2.0 library in .Net Core docs ?
Same code works in .NET Console app.
[EDIT]
#Will #JohnnyL Commented that I do not refer, System.Security.Principal.Windows.dll, that is true.
But I am curious why it is not working, because
in .NET 4.6.1 project (where class WindowsIdentity is visible) I also do not refer this System.Security.Principal.Windows.dll specifically. However i refer System.dll.
I always thought that it works like namespace hierarchy. For instance, when I refer to
System.Security.Principal.dll
i can use class which is in
System.Security.Principal.Windows.dll.
Am I wrong?
I added System.Security.Principal.dll to .NetCore solution by hand but it still does not work.
[EDIT2]
#Will Thank you a lot for expaining the subject it helped me a lot.
I tried to figure out is WindowsIdentity compatible with Core and it seems that it is please see:
in this apisof.net in Declarations area i can see that WindowsIdentity is in .Net Core 2.0 System.Security.Principal.Windows, Version=4.1.1.0, PublicKeyToken=b03f5f7f11d50a3a
but i do not have System.Security.Principal.Windows.dll in references, should I add it? If yes from where?
in .NET Core api reference i see this class in the list (what is the purpose of that listing if it is not compatible with core?
I also find information about that class in that link
Am I looking in wrong places?
Microsoft announced Windows Compatibility Pack for .NET Core a few weeks ago,
https://blogs.msdn.microsoft.com/dotnet/2017/11/16/announcing-the-windows-compatibility-pack-for-net-core/
And by analyzing the source code of System.Security.Principal.Windows.csproj and the commit adding it,
https://github.com/dotnet/corefx/blob/master/src/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj
My conclusion is that this is also part of the Windows only compatibility libraries, so can only be used on Windows.
To add that to your project, open your csproj and add a PackageReference tag for System.Security.Principal.Windows manually (or use Visual Studio's NuGet Package Manager).

How to get target runtime info from a .NET assembly in a C# program? [duplicate]

From the command line (or by any means really), how can I determine which CLR version a .NET assembly requires?
I need to determine if an assembly requires 2.0 or 4.0 CLR version.
ildasm.exe will show it if you double-click on "MANIFEST" and look for "Metadata version". By default, it's the version that the image was compiled against.
One clarification...
The problem with all the mentioned methods is that they will return version 4.0 if assembly was compiled against .NET framework 4.0, 4.5 or 4.5.1.
The way to figure out this version programmatically at runtime is using the System.Runtime.Versioning.TargetFrameworkAttribute for the given assembly, for example
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
...
object[] list = Assembly.GetExecutingAssembly().GetCustomAttributes(true);
var attribute = list.OfType<TargetFrameworkAttribute>().First();
Console.WriteLine(attribute.FrameworkName);
Console.WriteLine(attribute.FrameworkDisplayName);
Will return
a.FrameworkName ".NETFramework,Version=v4.0" string
a.FrameworkDisplayName ".NET Framework 4" string
a.FrameworkName ".NETFramework,Version=v4.5" string
a.FrameworkDisplayName ".NET Framework 4.5" string
a.FrameworkName ".NETFramework,Version=v4.5.1" string
a.FrameworkDisplayName ".NET Framework 4.5.1" string
class Program {
static void Main(string[] args) {
System.Console.WriteLine(
System.Reflection.Assembly.LoadFrom(args[0]).ImageRuntimeVersion);
}
}
Compile and run the above application under the latest .NET Framework (as an older CLR may be unable to load assemblies requiring a newer CLR) and run it passing the path to the assembly you want to check as the command line argument.
Here's a PowerShell equivalent of the .NET code suggested in another answer. Using PowerShell means that you can skip a few steps like creating and compiling an assembly.
At a PowerShell prompt, run the following:
[System.Reflection.Assembly]::LoadFrom("C:\...\MyAssembly.dll").ImageRuntimeVersion
By default, PowerShell uses the .NET v2 runtime, so you'll get an exception for assemblies targetting v4. Stack Overflow question How can I run PowerShell with the .NET 4 runtime? details methods for changing that, if required.
Here is a powershell one liner that will display the Target framework version for assemblies targeting v4 and up.
Resolve-Path($args) | Select #{N='Assembly'; E={$_ }}, #{N='TargetFramework'; E={(([Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetCustomAttributesData() | Where-Object { $_.AttributeType -like "System.Runtime.Versioning.TargetFrameworkAttribute" })).NamedArguments.TypedValue}} | Format-Table
use:
C:\test\> show-targetfw.ps1 *.dll
Assembly TargetFramework
-------- --------
C:\test\a.dll ".NET Framework 4.6.1"
C:\test\b.dll ".NET Framework 4.5.2"
From command line
DUMPBIN your dll/exe /CLRHEADER
I'd suggest using ReflectionOnlyLoadFrom() insted of LoadFrom()
It has an advantage that it can load x64 and ia64 assemblies when running on x86 machine, while LoadFrom() will fail to do that.
Though it still won't load .Net 4.0 assemblies from a 2.0 powershell.
As #mistika suggested, it is better to use ReflectionOnlyLoadFrom() rather than LoadFrom(). The downside of this is that calling GetCustomAttributes() on an assembly loaded with ReflectionOnlyLoadFrom() throws an exception. You need to call GetCustomAttributesData() instead:
var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
var customAttributes = assembly.GetCustomAttributesData();
var targetFramework = customAttributes.FirstOrDefault(attr => attr.AttributeType.Equals(typeof(TargetFrameworkAttribute)));
var frameworkName = string.Empty;
var frameworkDisplayName = string.Empty;
if (null != targetFramework)
{
if(targetFramework.ConstructorArguments.Any())
{
// first argument is the name of the framework.
frameworkName = (string)targetFramework.ConstructorArguments[0].Value;
}
// search for a named argument called "FrameworkDisplayName"
var frameworkDisplayNameArg = targetFramework.NamedArguments.FirstOrDefault(arg => arg.MemberName.Equals("FrameworkDisplayName"));
if (null != frameworkDisplayNameArg)
{
frameworkDisplayName = (string)frameworkDisplayNameArg.TypedValue.Value;
}
}
Console.WriteLine("Framework Name: " + frameworkName);
Console.WriteLine("Framework Display Name: " + frameworkDisplayName);
I use ILSpy as a replacement for Reflector. If you open the assembly in ILSpy, you can see, for example:
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
A very nice tool is JustDecompile from Telerik. You can open assemblies and the tool is showing whether they are targeting 4.5, 4.5.1 or 4.6
If you want to include result in a script, I recommend using the text output of ildasm.exe, and then grep "Version String" from the output.
"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\ildasm.exe" /text D:\LocalAssemblies\Toolfactory.Core.BaseTypes.dll /noil /headers | find "' Version String"
Note I include a ' so the find command does not recognize "Version String Length"
Try this Assembly Information executable to get the assembly version, which tells you CLR version it requires, and as well other information
such as Compilation options, Target Processor and References:

Is GetFields supported in a PCL?

I am trying to implement an enumeration class found at https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Enumeration.cs.
In the following code, I am getting a compile error that GetFields cannot be resolved.
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
return fields.Select(info => info.GetValue(null)).OfType<T>();
}
According to http://msdn.microsoft.com/en-us/library/ch9714z3(v=vs.110).aspx, this method is supported in Portable Class Libraries.
My library is targeting .NET for Windows Store apps, .NET Framework 4.5 and Windows Phone 8.
Any idea of what is going on here?
Solution
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var type = typeof(T);
var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
return fields.Select(info => info.GetValue(null)).OfType<T>();
}
public static IEnumerable GetAll(Type type)
{
var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
return fields.Select(info => info.GetValue(null));
}
To add to Damien's answer, in .Net for Windows Store Apps, you can use the following extension method:
using System.Reflection;
var fields = type.GetRuntimeFields();
http://msdn.microsoft.com/en-us/library/system.reflection.runtimereflectionextensions.getruntimefields.aspx
This seems to be the equivalent of the GetFields method for the .Net Framework.
This method returns all fields that are defined on the specified type,
including inherited, non-public, instance, and static fields.
Just because a method says it's supported in Portable Class Libraries doesn't mean that it's supported for all possible targets. If you look at the help for the Type class, it lists each member and shows icons for each supported system.
In this case, you'll notice that there's no green shopping bag icon next to GetFields - it's not supported in Windows Store apps, and so as long as you include Windows Store in your set of supported targets for the PCL, it will not be available.
Another way to put it is - in the Version Information block for the methods, if they're supported for Windows Store, there'll be a specific section saying about it. Compare GetGenericTypeDefinition:
.NET Framework
Supported in: 4.5, 4, 3.5, 3.0, 2.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Portable Class Library
Supported in: Portable Class Library
.NET for Windows Store apps
Supported in: Windows 8
to GetFields
.NET Framework
Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
Portable Class Library
Supported in: Portable Class Library
For Windows Store apps, for reflection, you should switch to using the TypeInfo class - but note that it still doesn't, specifically, support the GetFields method.

c# get framework / runtime version from application with Assembly

I'm trying to check what framework version a other .NET application is working with through a assembly. I found two ways to get the version of the framework ( first through the ImageRunetimeVersion and with the FullName of the assembly ) but i'm getting two different values from it and i dont know which is the right one:
Assembly ass = Assembly.LoadFrom(autPath);
string imageRuntimeVersion = ass.ImageRuntimeVersion;
Console.WriteLine("ImageRunetimeVersion: " + imageRuntimeVersion);
Console.WriteLine("FullName: " + ass.FullName);
Console.WriteLine("");
Console.WriteLine("----");
Console.WriteLine("Referenced Assemblies: ");
Console.WriteLine("");
AssemblyName[] referencedAssemblies = ass.GetReferencedAssemblies();
foreach (AssemblyName a in referencedAssemblies)
{
Console.WriteLine(a.FullName);
}
if i'm going to test this with my application and of e.g paint.net the results are:
Like you can see i cant say which "version" is the right one. The biggest problem is that if i'm going to take a look to my project properties for my .net application the target platform is 3.5 and not 2.0 or 1.0-
I think I can clear some things up for you. First, the FullName property gives you the application version number. That is the number you set and has no relation to the .NET framework version. That means the version number in the FullName property can be ignored.
The imageRuntimeVersion is the CLR version. Unfortunately, 2.0 covers .NET 2.0, 3.0, and 3.5. Technically, your application is giving you the right information but it isn't really the information you want (I don't think).
Here is a SO article with more explanation:
Retrieve Target Framework Version and Target Framework Profile from a .Net Assembly
A couple of suggestions for you from that article include looking for a config file that would give you the targetted framework or looking at the versions of the libraries that are used. Neither is really foolproof but as far as I know, that is the best you can do.
TargetFramework not same CLR version.
For example,
CLR 4.0
TargetFramework: .NET 4.0 and .NET 4.5
A solution using TargetFrameworkAttribute http://www.lucbos.net/2011/08/get-targetframework-for-assembly.html
Note: TargetFrameworkAttribute is only available from .NET 4.0.
var targetFramework = "Unknown";
var targetFrameworkAttributes = assembly.GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), true);
if (targetFrameworkAttributes.Length > 0)
{
var targetFrameworkAttribute = (TargetFrameworkAttribute)targetFrameworkAttributes.First();
targetFramework = (targetFrameworkAttribute.FrameworkDisplayName);
}
Console.WriteLine("Version: {0}", Environment.Version.ToString());

Get the current dot net version of my application

How do I get the running dot net version of my asp.net application.
I tried the solution from here
Is there an easy way to check the .NET Framework version?
It gives the highest version installed but I need the running version.
Use Environment.Version for getting the run time version. It will give the version number of .Net CLR which is being used for executing current application.
You need to be careful here, it will only return run time version not framework version. The CLR for .NET 3.0 and .NET 3.5 is the same CLR from .NET 2.0.
Use Environment.Version - it gives you the exact version of .NET running the application.
Hope this one helps,
DirectoryEntry site = new DirectoryEntry(#"IIS://localhost/w3svc/1/Root");
PropertyValueCollection values = site.Properties["ScriptMaps"];
foreach (string val in values)
{
if (val.StartsWith(".aspx"))
{
string version = val.Substring(val.IndexOf("Framework") + 10, 9);
MessageBox.Show(String.Format("ASP.Net Version is {0}", version));
}
}
The script map property is an array of strings. If the app supports asp.net one of those strings will be a mapping of the aspx file extension to the asp.net handler which will a the full path to a DLL. The path will be something like
%windir%/Microsoft.NET/Framework//aspnet_isapi.dll.
You can get the version out of this string with some simple parsing.

Categories