.NET 6 WinForm ClickOnce get open arguments - c#

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;
}

Related

Print method from WebBrowser not working in a console application unless a MessageBox.Show() is called

I have a program that is supposed to print a string provided as argument to the default printer in the system. The string is HTML-formatted.
As an attempt to develop a solution, I came up with the following code:
Program.cs
using System;
using System.Windows.Forms;
using System.Threading;
namespace Print2
{
class Program
{
private const bool DEBUG = false;
[STAThread]
static void Main(string[] args)
{
string html = args[0];
RunBrowserThread(html);
}
// Mostly based on code by Hans Passant <https://stackoverflow.com/users/17034/hans-passant>
// See: https://stackoverflow.com/a/4271581/3258851
// (CC BY-SA 2.5)
private static void RunBrowserThread(string html)
{
var t = new Thread(() => {
var wb = new WebBrowser();
wb.DocumentCompleted += Browser_DocumentCompleted;
wb.DocumentText = html;
Application.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
static void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var wb = sender as WebBrowser;
wb.Print();
if (DEBUG)
MessageBox.Show("Printed " + wb.DocumentText);
Application.ExitThread();
}
}
}
This is a Console Application (.NET Core 3.1), and I manually edited the .csproj file according to this in order to have support for System.Windows.Forms.WebBrowser:
Print2.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<Version>1.0.0-beta10</Version>
<AssemblyVersion>1.0.0.10</AssemblyVersion>
<FileVersion>1.0.0.10</FileVersion>
</PropertyGroup>
</Project>
The problem I'm facing is: when the DEBUG constant is set to false (and, as a consequence, no messagebox is shown), the wb.Print() call doesn't seem to work as the document is not placed to the printer's pool. The exit code does not indicate an error.
How do I get the program to work without having to display a messagebox?
What I have tried, to no effect:
defining <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> in the .csproj according to the linked answer
calling Thread.Sleep() or t.Join() right after the call to t.Start().
This is not a matter of the application exiting too soon, as I can Thread.Sleep all I want (and confirm under the Windows Task Manager) and still the behavior is the same.

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

Namespace Microsoft.Win32 could not be found

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:

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)

Xamarin.mac Resources localization doesn't change by current culture

I am trying to use .resx files for localization in xamarin.mac
Inside AppDelegate I changed current culture of the thread :
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo ("ru");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo ("ru");
also I have two resource files inside my app:
But strings are always shown from the default resource file... Any solution?
I also use native language change, here is whole AppDelegate constructor :
public AppDelegate ()
{
string [] lang = { "ru", "en" };
NSUserDefaults.StandardUserDefaults.SetValueForKey (NSArray.FromObjects (lang), (Foundation.NSString)"AppleLanguages");
NSUserDefaults.StandardUserDefaults.Synchronize ();
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo ("ru");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo ("ru");
Resources.Culture = GetCurrentCultureInfo ();
}
BTW , xamarin studio 6.1.1 (build 15) doesn't allow me to add resource.ru.resx if I have resource.ru in my project , kinda bug !
I have created resource-ru.resx file and than renamed it .
You need to set the app culture after retrieving it from the OS, something like this (warning, this is from Xamarin iOS, but for the documentation it works the same way, if not advice me and I will delete the post):
//Add this somewhere
public System.Globalization.CultureInfo GetCurrentCultureInfo ()
{
var netLanguage = "en";
if (NSLocale.PreferredLanguages.Length > 0) {
var pref = NSLocale.PreferredLanguages [0];
netLanguage = pref.Replace ("_", "-"); // turns en_US into en-US
}
try
{
return new System.Globalization.CultureInfo(netLanguage);
}catch{
try{
return new System.Globalization.CultureInfo(netLanguage.Substring(0, netLanguage.IndexOf("-")));
}
catch{
return new System.Globalization.CultureInfo("en");
}
}
}
//And finally add this at the start of the app
AppResources.Culture = GetCurrentCultureInfo();
Likely you are running into
https://bugzilla.xamarin.com/show_bug.cgi?id=45696
You can work around it using a custom msbuild step. Shown here (due to length):
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<CreateAppBundleDependsOn>$(CreateAppBundleDependsOn);WorkAroundLocalizationBug-ES;WorkAroundLocalizationBug-FR</CreateAppBundleDependsOn>
</PropertyGroup>
<Target Name="WorkAroundLocalizationBug-ES" Inputs="$(OutputPath)es/XMLocalizationSample.resources.dll" Outputs="$(AppBundleDir)/Contents/MonoBundle/es/XMLocalizationSample.resources.dll">
<Copy SourceFiles="$(OutputPath)es/XMLocalizationSample.resources.dll" DestinationFiles="$(AppBundleDir)/Contents/MonoBundle/es/XMLocalizationSample.resources.dll" />
</Target>
<Target Name="WorkAroundLocalizationBug-FR" Inputs="$(OutputPath)fr/XMLocalizationSample.resources.dll" Outputs="$(AppBundleDir)/Contents/MonoBundle/fr/XMLocalizationSample.resources.dll">
<Copy SourceFiles="$(OutputPath)fr/XMLocalizationSample.resources.dll" DestinationFiles="$(AppBundleDir)/Contents/MonoBundle/fr/XMLocalizationSample.resources.dll" />
</Target>
</Project>
A full sample can be found here: https://github.com/xamarin/mac-samples/tree/master/XMLocalizationSample

Categories

Resources