Namespace Microsoft.Win32 could not be found - c#

I installed Visual Studio yesterday. I would like to see what version of the .NET Framework is installed with Visual Studio, so I followed this code from Microsoft. (scroll a bit down for the code). I opened a new Visual C# project with 'Console App (.NET Core)' and copied the given code in it.
using System;
using Microsoft.Win32;
public class GetDotNetVersion
{
public static void Main()
{
GetDotNetVersion.Get45PlusFromRegistry();
}
private static void Get45PlusFromRegistry()
{
const string subkey = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
{
if (ndpKey != null && ndpKey.GetValue("Release") != null)
{
Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release")));
}
else
{
Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
}
}
}
// Checking the version using >= will enable forward compatibility.
private static string CheckFor45PlusVersion(int releaseKey)
{
if (releaseKey >= 461808)
return "4.7.2 or later";
if (releaseKey >= 461308)
return "4.7.1";
if (releaseKey >= 460798)
return "4.7";
if (releaseKey >= 394802)
return "4.6.2";
if (releaseKey >= 394254)
return "4.6.1";
if (releaseKey >= 393295)
return "4.6";
if (releaseKey >= 379893)
return "4.5.2";
if (releaseKey >= 378675)
return "4.5.1";
if (releaseKey >= 378389)
return "4.5";
// This code should never execute. A non-null release key should mean
// that 4.5 or later is installed.
return "No 4.5 or later version detected";
}
}
// This example displays output like the following:
// .NET Framework Version: 4.6.1
However, in the editor, the 'RegistryKey' is giving an error: "Namespace cannot be found." The second line 'using Microsoft.Win32;' is grey as if it is not called upon in the code.
When I look in the Solution Explorer panel in Visual Studio, I can list the dependencies. I do not see MicrosoftWin32.dll but I do see mscorlib.dll. I read somewhere that the Microsoft.Win32 namespace could be found there?
Can someone give me some clues as how to resolve this? Where can I find Microsoft.Win32 namespace? Why is it not available in this standard project?

If you use netcore you need to add package Microsoft.Win32.Registry:
Your project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Win32.Registry" Version="4.4.0" />
</ItemGroup>
</Project>
Result:

Related

.NET 6 WinForm ClickOnce get open arguments

I create a can edit ico file application, I publish with ClickOnce.
I want to click ico file to open my winform application, but my application can't get args(file path).
I try: string fileName = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
but ide show error message: Cannot resolve symbol 'ActivationArguments'
on my ClickOnceProfile.pubxml file:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<FileAssociation Include=".ico">
<Visible>False</Visible>
<Description>ico</Description>
<Progid>ico</Progid>
<DefaultIcon>Resources\ico.ico</DefaultIcon>
</FileAssociation>
</ItemGroup>
</Project>
BTY, if I use this code, I can get arg (not use ClickOnce), but I want to use ClickOnce, please help me.
[STAThread]
static void Main(string[]? args)
{
Application.Run(new Form1(args));
}
public Form1(string[]? args)
{
string filepath = args[0];
}
relevant information:
.NET 6
windows 11
windows forms
Step-1:
   Update the VS2022 to the lastest version.
Step-2:
  Project RightClick => Publish => Publish-Tab => Show All => Setting-tab => Options => Allow Url-Paramaters....
Step-3:
  Copy this file code to you app.
Step-4:
  Write Fllowing code:
var clickOnceInfo = new ClickOnceInfo();
if (!clickOnceInfo.IsNetworkDeployed)
{
MessageBox.Show("设计器只能从Web页面启动,无法独立使用");
return;
}
var query = clickOnceInfo.ActivationUri?.Query ?? "QueryEMPTY";
if (query == "QueryEMPTY")
{
MessageBox.Show("参数设置异常,无法启动设计器");
return;
}

NuGet dependency tree [duplicate]

Is there a way, either textual or graphical, to view the hierarchy of dependencies between NuGet packages?
If you're using the new .csproj, you could get all dependencies with reference in here (after project built):
{ProjectDir}\obj\project.assets.json
Like #neil-barnwell solution, but works with NuGet.Core 2.7+
Install-Package NuGet.Core
Here is the code
using System;
using System.Linq;
using System.Runtime.Versioning;
using System.IO;
using NuGet;
public class Program
{
public static void Main(string[] args)
{
var frameworkName = new FrameworkName(".NETFramework, Version=4.0");
// var packageSource = "https://www.nuget.org/api/v2/";
var packageSource = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "NuGet", "Cache");
var repository = PackageRepositoryFactory.Default.CreateRepository(packageSource);
const bool prerelease = false;
var packages = repository.GetPackages()
.Where(p => prerelease ? p.IsAbsoluteLatestVersion : p.IsLatestVersion)
.Where(p => VersionUtility.IsCompatible(frameworkName, p.GetSupportedFrameworks()));
foreach (IPackage package in packages)
{
GetValue(repository, frameworkName, package, prerelease, 0);
}
Console.WriteLine();
Console.WriteLine("Press Enter...");
Console.ReadLine();
}
private static void GetValue(IPackageRepository repository, FrameworkName frameworkName, IPackage package, bool prerelease, int level)
{
Console.WriteLine("{0}{1}", new string(' ', level * 3), package);
foreach (PackageDependency dependency in package.GetCompatiblePackageDependencies(frameworkName))
{
IPackage subPackage = repository.ResolveDependency(dependency, prerelease, true);
GetValue(repository, frameworkName, subPackage, prerelease, level + 1);
}
}
}
It is also possible to write code against the API in NuGet.Core. Install it via NuGet:
install-package nuget.core
Then you can get a repository object and walk the graph. Here's a sample app I just built:
using System;
using System.Collections.Generic;
using System.Linq;
using NuGet;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
var repo = new LocalPackageRepository(#"C:\Code\Common\Group\Business-Logic\packages");
IQueryable<IPackage> packages = repo.GetPackages();
OutputGraph(repo, packages, 0);
}
static void OutputGraph(LocalPackageRepository repository, IEnumerable<IPackage> packages, int depth)
{
foreach (IPackage package in packages)
{
Console.WriteLine("{0}{1} v{2}", new string(' ', depth), package.Id, package.Version);
IList<IPackage> dependentPackages = new List<IPackage>();
foreach (var dependency in package.Dependencies)
{
dependentPackages.Add(repository.FindPackage(dependency.Id, dependency.VersionSpec.ToString()));
}
OutputGraph(repository, dependentPackages, depth += 3);
}
}
}
}
In my case, this app outputs something like this:
MyCompany.Castle v1.1.0.3
Castle.Windsor v2.5.3
Castle.Core v2.5.2
MyCompany.Common v1.1.0.6
CommonServiceLocator v1.0
MyCompany.Enum v1.1.0.7
MyCompany.Common v1.1.0.6
CommonServiceLocator v1.0
MyCompany.Enum v1.1.0.7
MyCompany.Enum v1.1.0.7
MyCompany.Versioning v1.3
Castle.Core v2.5.2
Castle.Windsor v2.5.3
Castle.Core v2.5.2
CommonServiceLocator v1.0
NUnit v2.5.10.11092
RhinoMocks v3.6
I've found a nice NPM package to print the dependency tree into console. Of course if you don't mind using/installing NPM/Node.JS.
Considering other solutions, this is the most simple one, you don't need to write your own code or register something, and you get just such dependency tree as you expect. But it works only with packages.config format.
I can't believe this functionality is absent in free Visual Studio editions or nuget.exe too.
I Can Has .NET Core (GitHub repository) produces nice graphs of NuGet dependencies along with a Graphviz representation. And as its name implies, you also get .NET Core compatibility information for free.
If you prefer to run it locally on your computer, I Can Has .NET Core also offers a console mode.
I add a compatible solution with the latest version of nuget-core
install-package nuget.core
This is the console App to get the dependencies graph
class Program
{
static void Main()
{
Console.Write("Enter the local repo folder: ");
var repoFolder = Console.ReadLine();
var repo = new LocalPackageRepository(repoFolder);
IQueryable<IPackage> packages = repo.GetPackages();
OutputGraph(repo, packages, 0);
}
static void OutputGraph(LocalPackageRepository repository, IEnumerable<IPackage> packages, int depth)
{
foreach (IPackage package in packages)
{
Console.WriteLine("{0}{1} v{2}", new string(' ', depth), package.Id, package.Version);
IList<IPackage> dependentPackages = new List<IPackage>();
foreach (var dependencySet in package.DependencySets)
{
foreach (var dependency in dependencySet.Dependencies)
{
var dependentPackage = repository.FindPackage(dependency.Id, dependency.VersionSpec, true, true);
if (dependentPackage != null)
{
dependentPackages.Add(dependentPackage);
}
}
}
OutputGraph(repository, dependentPackages, depth + 3);
}
}
}
Package Visualized from NuGet 1.4 should work. See http://docs.nuget.org/docs/release-notes/nuget-1.4
Since this is an old question, it is important to note the following:
This is a built-in feature in the new csproj format. In Visual Studio 2017 and up, open the Solution Explorer and you can find you packages like:
{Your project}->Dependencies->Packages
You can open each NuGet dependency tree and run with it recursively, effectively seeing not only the dependency tree for specific packages, but also which NuGet packages your project actually installs.
Another option you have is to use the nuget-deps-tree npm package.
It supports both the packages.config format and the newer assets format used by .NET projects.
FYI, MyGet.org has this kind of visualization built-in. You can view dependency graphs on the Feed Details page.
https://github.com/mikehadlow/AsmSpy using this to identify assembly version across a project

Does anyone have experience building a Console App (C#) using the package DocumentFormat.OpenXML.DotNet.Core from NuGet?

I have successfully started a console app solution in Visual Studio 2019, in C#, and have downloaded and installed the package DocumentFormat.OpenXML.DotNet.Core from NuGet. Since DocumentFormat.OpenXML does not play with .NET Core, I cannot use that. I have also successfully attached the package to the solution, and it appears in the Solution Explorer with no alerts. (Same method I have used in the past with other packages.)
This package is supposed to give my solution access to the OpenXML functionality, but I cannot get my program to recognize it.
I have tried inserting a using statement for DocumentFormat, but I get an error that the using statement is not necessary - and then it asks if I am missing a using statement or assembler reference.
I have tried changing the namespace to DocumentFormat, but then I have to add all the classes and all the functions, which it seems to me is the entire purpose of the package.
Here is the code (it's sample code just to get this working):
using System;
using DocumentFormat;
using S = DocumentFormat.OpenXml.Spreadsheet.Sheets;
using E = DocumentFormat.OpenXml.OpenXmlElement;
using A = DocumentFormat.OpenXml.OpenXmlAttribute;
namespace ConsoleApp1
{
class Program
{
static void ReadExcelFile()
{
try
{
//Lets open the existing excel file and read through its content . Open the excel using openxml sdk
using (SpreadsheetDocument doc = SpreadsheetDocument.Open("testdata.xlsx", false))
{
//create the object for workbook part
WorkbookPart workbookPart = doc.WorkbookPart;
Sheets thesheetcollection = workbookPart.Workbook.GetFirstChild<Sheets>();
StringBuilder excelResult = new StringBuilder();
//using for each loop to get the sheet from the sheetcollection
foreach (Sheet thesheet in thesheetcollection)
{
excelResult.AppendLine("Excel Sheet Name : " + thesheet.Name);
excelResult.AppendLine("----------------------------------------------- ");
//statement to get the worksheet object by using the sheet id
Worksheet theWorksheet = ((WorksheetPart)workbookPart.GetPartById(thesheet.Id)).Worksheet;
SheetData thesheetdata = (SheetData)theWorksheet.GetFirstChild<SheetData>();
foreach (Row thecurrentrow in thesheetdata)
{
foreach (Cell thecurrentcell in thecurrentrow)
{
//statement to take the integer value
string currentcellvalue = string.Empty;
if (thecurrentcell.DataType != null)
{
if (thecurrentcell.DataType == CellValues.SharedString)
{
int id;
if (Int32.TryParse(thecurrentcell.InnerText, out id))
{
SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
if (item.Text != null)
{
//code to take the string value
excelResult.Append(item.Text.Text + " ");
}
else if (item.InnerText != null)
{
currentcellvalue = item.InnerText;
}
else if (item.InnerXml != null)
{
currentcellvalue = item.InnerXml;
}
}
}
}
else
{
excelResult.Append(Convert.ToInt16(thecurrentcell.InnerText) + " ");
}
}
excelResult.AppendLine();
}
excelResult.Append("");
Console.WriteLine(excelResult.ToString());
Console.ReadLine();
}
}
}
catch (Exception)
{
}
}
}
}
I have refreshed the package,
I have started a new solution and added the package to it before typing anything in the code window,
I have tried updating and reinstalling both in the NuGet Package Manager Console and in the Manage NuGet Packages for Solution window.
Can someone please tell me what I'm missing?
Thanks in advance,
DJ
Not sure how you determined that the Open XML SDK as provided in the DocumentFormat.OpenXml NuGet package "does not play with .NET Core". As a contributor to the Open XML SDK, I can confirm that it definitely does play with .NET Core and you can clone my CodeSnippets GitHub repository to test this yourself. That repository contains a solution with multiple projects, a few of which use .NET Core (e.g., the CodeSnippets library, which targets netstandard2.0, and the CodeSnippets.Tests library, which targets netcoreapp3.0).
The DocumentFormat.OpenXml.DotNet.Core NuGet package that you use was last updated on July 30, 2016, i.e., almost four years ago. You should really replace this with the official DocumentFormat.OpenXml NuGet package.

How to use 'Microsoft.CognitiveServices.Speech' namespace with Azure Functions?

I'm testing the Microsoft Azure Speech services, specifically trying to use Text-To-Speech. So, I'm using a free layer of Azure, and created a TimeTrigger Azure Function to read an e-mail, traverse through HTML and then call the Speech Service with the SDK Microsoft.CognitiveServices.Speech. I'm using the function.proj to load the nuget packages, loading S22.Imap and HtmlAgilityPack without any issues. But the speech package is triggering an exception:
Unable to load DLL 'Microsoft.CognitiveServices.Speech.core.dll' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E).
Am I able to use this package in an Azure Function? If so, what am I doing wrong?
I tried to remove the <PackageReference Include="Microsoft.CognitiveServices.Speech" Version="1.6.0" /> line from function.proj and deleted project.assets.json to reload the package but it didn't work.
This is my function.proj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="S22.Imap" Version="3.6.0" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.9" />
<PackageReference Include="Microsoft.CognitiveServices.Speech" Version="1.6.0" />
</ItemGroup>
</Project>
And this is my run.csx:
using System;
using S22.Imap;
using System.Net.Mail;
using HtmlAgilityPack;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using System.Diagnostics;
public static void Run(TimerInfo myTimer, ILogger log)
{
var username = "sample#gmail.com";
var password = "sample";
var subsKey = "sample";
using(ImapClient client = new ImapClient("imap.gmail.com", 993, username, password, AuthMethod.Login, true))
{
IEnumerable<uint> uids = client.Search(SearchCondition.From("sample#sample.com"));
IEnumerable<MailMessage> messages = client.GetMessages(uids);
log.LogInformation($"Count: {messages.Count()}.");
var msg = messages.FirstOrDefault();
if(msg != null)
{
var doc = new HtmlDocument();
doc.LoadHtml(msg.Body);
var paragraphs = doc.DocumentNode.Descendants()
.Where(x => x.Name == "p" && !string.IsNullOrEmpty(x.InnerText.Trim()))
.ToList();
var mailText = string.Empty;
foreach(var par in paragraphs)
mailText += par.InnerText;
if(!string.IsNullOrEmpty(mailText))
{
var config = SpeechConfig.FromSubscription(subsKey, "myregion");
config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3);
config.SpeechSynthesisLanguage = "pt-BR";
using (var synthesizer = new SpeechSynthesizer(config))
{
using (var result = synthesizer.SpeakTextAsync(mailText).Result)
{
if (result.Reason == ResultReason.SynthesizingAudioCompleted)
{
//Do something with it
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
log.LogError($"CANCELED: Reason={cancellation.Reason}");
if (cancellation.Reason == CancellationReason.Error)
{
log.LogError($"CANCELED: ErrorCode={cancellation.ErrorCode}");
log.LogError($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
}
}
}
}
}
}
}
}
You could try to delete the function.proj then recreate one and add Microsoft.CognitiveServices.Speech at first.
Make sure the Microsoft.CognitiveServices.Speech.core.dll has been installed in win-x86 and win-x64. Please refer to this issue.
Mark as perquisite
When you publish mark Visual c++ 14 Runtime Libraries as prerequisite

Autofac is not loading module from Multi Target .Net Standard library

I'm developing a windows service and I'm referencing a .NET Standard library where I have an Autofac Module, I'm going call this library as A. I have the following PropertyGroup in the csproj:
<PropertyGroup>
<TargetFrameworks>net461;netstandard2.0</TargetFrameworks>
</PropertyGroup>
And this is the Autofac module quoted earlier:
public class DefaultModule:Module
{
protected override void Load(ContainerBuilder builder)
{
#if net461
builder.Register(context => {
return new BusSettings
{
HostAddress = System.Configuration.ConfigurationManager.AppSettings["HostAddress"],
Username = System.Configuration.ConfigurationManager.AppSettings["Username"],
Password = System.Configuration.ConfigurationManager.AppSettings["Password"],
QueueName=System.Configuration.ConfigurationManager.AppSettings["QueueName"]
};
}).AsSelf();
#else
builder.Register(context => {
var configuration = context.Resolve<IConfiguration>();
return new BusSettings
{
HostAddress = configuration["BusSettings:HostAddress"],
Username = configuration["BusSettings:Username"],
Password = configuration["BusSettings:Password"],
QueueName = configuration["BusSettings:QueueName"]
};
}).AsSelf();
#endif
Now I created .NET Framework console app using 4.61 as Target Framework.And this is the code I use to load the modules:
//Library A is loaded By ExtractCustomAssemblyModules
List<Assembly> assemblies = ExtractCustomAssemblyModules();
containerBuilder.RegisterAssemblyModules(assemblies.ToArray());//Register custom modules
When I execute containerBuilder.Build() I'm not seeing Autofac loading the module and registering the services I have in my custom module, so is giving me an exception because it couldn't found a dependency. Now, I created a .NET Core 2 Console application and did exactly the same, at the time to call containerBuilder.Build() the code jump to the module and I see the services been registered and no exception this time
Why is not loading the Autofac Module in the .NET framework Console App?
PS: I found this blog really useful, I switched the first target framework to .NET 4.61 as you can see in the PropertyGroup but still I'm seeing in grey 4.61 code inside the if.
Small Test
Lets build a sample library with
namespace MyClassLibrary
{
public class Foo
{
public static string Info { get; } = "Conditionals"
#if net461
+ " net461"
#endif
#if NET461
+ " NET461"
#endif
#if NETCORE
+ " NETCORE"
#endif
#if NETSTANDARD
+ " NETSTANDARD"
#endif
#if NETSTANDARD2_0
+ " NETSTANDARD2_0"
#endif
+ "";
}
}
and
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net461;netstandard2.0</TargetFrameworks>
</PropertyGroup>
</Project>
If we reference this library in a .Net Framework 4.6.1+ console application with a simple
using System;
namespace ConsoleApp.NetCore
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine( MyClassLibrary.Foo.Info );
}
}
}
the output is
Conditionals NET461
github: Complete Solution
Conclusion
The directive net461 is unknown but NET461 is known.
As you can see, size does matters :o)

Categories

Resources