I used cefsharp, I need to generate folders according to certain rules and download the web content to the specified directory. I'm going to replace it with webview2. I find that there is no way to specify the default download directory. Do you have any way?
It may evolve in the future, but currently, you must define the WEBVIEW2_USER_DATA_FOLDER environment variable manually as explained here WebView2 Globals, something like this:
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER", #"c:\temp\mydata");
MyWebView.CoreWebView2Initialized += MyWebView_CoreWebView2Initialized;
}
private void MyWebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
// udf will contain c:\temp\mydata
var udf = sender.CoreWebView2.Environment.UserDataFolder;
}
...
}
Related
This question already has answers here:
Set same icon for all my Forms
(8 answers)
Closed 1 year ago.
I am working on a project where my requirement is that i have to use a same icon on all my windows forms . I have atleast 50 windows forms and many more had to be added . So is there a way to set a default icon for all windows forms rathee than doing manually on each form page .
you have multiple solution for this problem
best idea would be to inherit from a common base-Form that sets the Icon in the constructor.
from : Form or : System.Windows.Forms.Form to : MyCustomForm
and then just change MyCustomForm icon with write this line in MyCustomForm Cunstrunctor
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
then you just change project icon from project properties > Application > Icon and Manifest > browse for a *.ico file and add it there.
this approach can change other property in all from for example font,size,anchor,...
If you have many forms like:
public class MyAppForm1 : Form {
...
}
Then instead of deriving from Form, then you create an intermediate MyIconForm:
public class MyIconForm : Form {
public MyIconForm() : base() {
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
}
}
Then you just have to update all your forms to:
public class MyAppForm1 : MyIconForm {
...
}
The short answer is no, there is no central location where you can set the icon to be used by all forms in your project. You have to do it yourself. There are a bunch of methods you can use, including using reflection to set the backing field for Form.DefaultIcon during program initialization.
First step: get an icon.
There are a couple of options here. You can load an icon from a file, a resource or an embedded resource (yes, two different types of resource). Or the application icon, but you said you don't have one.
For standard resources:
Open project properties
Click Add Resource, Add Existing File and browse to your icon.
Icon is added to Properties.Resources with a property named after the file.
For content files (distributed with the application):
Add icon file to project (Add Existing Item)
Set file's Build Action property to Content.
Set file's Copy to Output Directory to Copy Always or Copy if newer.
Load icon using new Icon(iconFilename).
For embedded resources:
Add icon file to project (Add Existing Item)
Set file's Build Action to Embedded Resource.
Use Assembly.CurrentAssembly.GetManifestResourceStream to open the resource as a stream.
Of the three I'd choose standard resource for most things.
Making it work 1: Form Constructor
Add the appropriate loading code to every form's constructor:
public partial class Form1 : Form
{
public Form1()
{
// Using standard resource method
Icon = Properties.Resources.FormIcon;
InitializeComponent();
}
}
Making it work 2: Base Class
This is a fairly simple option, assuming you have control over the source for all of your forms and are OK with going through all of them to change their base class. The base class simply sets the form's icon during construction:
public class DefaultIconForm : Form
{
// Using content file method
private static readonly Icon _defaultIcon = new Icon("FormIcon.ico");
public DefaultIconForm()
{
Icon = _defaultIcon;
}
}
public partial class Form1 : DefaultIconForm
{
public Form1()
{
InitializeComponent();
}
}
You'll need to change all of your forms and remember to inherit from DefaultIconForm for all future forms.
Making it work 3: modify Form.DefaultIcon
This one is a slightly nasty trick that relies on reflection and could fail on you at some point, but it means not having to change any other code in your application.
Open your Program.cs file and add this method to the Program class:
private static void SetDefaultFormIcon()
{
var field = typeof(Form).GetField("defaultIcon", BindingFlags.Static | BindingFlags.NonPublic);
// And for completeness, this is the Embedded Resource method
using (var stream = typeof(Program).Assembly.GetManifestResourceStream($"{Application.ProductName}.FormIcon.ico"))
{
var ico = new Icon(stream);
field?.SetValue(null, ico);
}
}
Now call SetDefaultFormIcon() from main() to initialize.
As written it works on both .NET Framework and .NET 5 WinForms applications. There's no guarantee that the defaultIcon hidden static field won't change in future, so be prepared for it to break at some point.
My WPF app has .xyz files that can open it (used the WIX installer), however, in my WPF app, I'd like to somehow capture this and call some loading functionality of the file that was double-clicked on from the File Explorer before the application was started.
Right now, if you double click the appropriate xyz file from File Explorer, it opens the application but obviously nothing else happens. Is there a way in my WPF code to detect this and call the necessary function passing in the filepath/name?
In Application there is the StartUp event where you can set your arguments.
Follow this example
You should be able to the file path in your App.xaml.cs class:
public partial class App : Application
{
public static string FilePath { get; private set; }
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (e.Args != null && e.Args.Length > 0)
FilePath = e.Args[0];
}
}
If you store in a static property like this, you could access it from any class in your app:
string filePath = App.FilePath;
I would like to store an API key in a configuration file without checking it into source control, and read the data in my UWP app.
A common solution is to store the key in .config file (such as app.config or web.config) and access it like so:
var apiKey = ConfigurationManager.AppSettings.Get("apiKey");
I'm working on a Universal Windows (UWP) app and can't access the System.Configuration namespace that holds ConfigurationManager.
How can I access AppSettings in UWP app?
Alternatively, what's the best way to access configuration data in an UWP app?
In my specific use case I needed to use an external file that is not tracked by source control. There are two ways to access data from resource or configuration files.
One is to open and parse a configuration file. Given a file sample.txt with Build Action Content (Copy to Output Directory doesn't matter), we can read it with
var uri = new System.Uri("ms-appx:///sample.txt");
var sampleFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
or
var packageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var sampleFile = await packageFolder.GetFileAsync("sample.txt");
followed by
var contents = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
Alternatively, we can use Resources. Add a new Resource item to the project, called resourcesFile.resw. To access data, use:
var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile");
var token = resources.GetString("secret");
I wrote more verbose answer in a blog post Custom resource files in UWP
It's an old question, but here my solution :
Create a partial class Config.cs (for example) with all the properties you'r needed
Add a partial method void Init()
Call Init in the constructor
Create an other file Config.partial.cs with the void Init() method filling all your properties
-> Use #if DEBUG / #else / #endif to switch from Debug/Release
-> Use exclude Config.partial.cs from Github to not import it in the repository
Now it compile and it's not in the repository
Alternatively you can set in Config.cs default (not secret) datas.
Config.cs :
public partial class Config
{
public Config()
{
Init();
}
partial void Init();
public string ApiKey{ get; private set; }= "DefaultValueAPIKEY";
}
Config.partial.cs
public partial class Config
{
partial void Init()
{
#if DEBUG
this.ApiKey = "DebugAPIKEY";
#else
this.ApiKey = "ReleaseAPIKEY";
#endif
}
}
I'm thinking that what you call "ApiKey" is the static key that an API gives you to generate an access token. If this is the case, maybe the best way to achieve this is to create a static class out of the source control with that value inside of it, something like this:
public static class MyCredentials
{
public static string MyApiKey = "apiKey";
}
Then you access that value easily from your code:
var myApiKey = MyCredentials.MyApiKey;
If you want to store values in a plain-text file instead you will have to write/read it manually using StorageFile and FileIO classes.
Instead, if "ApiKey" means the dynamic access token, then the best solution is use ApplicationDataContainer as stratever says.
You don't need to create a configuration file. UWP has a built-in solution to store local settings/configurations. Please check this tutorial:
https://msdn.microsoft.com/en-us/library/windows/apps/mt299098.aspx
Using ApplicationDataContainer, you will be able to get a value by key:
Object value = localSettings.Values["exampleSetting"];
I've written a diagnostic analyzer to check if Const names have been created in a resx file in the solution and localize them to use the resx file. I need to gain access to the Document/Solution my field declaration has been registered in
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeConstDeclaration, SyntaxKind.FieldDeclaration);
}
public static void AnalyzeConstDeclaration(SyntaxNodeAnalysisContext context)
{
var semantic = (FieldDeclarationSyntax)context.Node;
}
I don't see a way to get the Document/Solution in the AnalysisContext
Nor do I see a way to get it from the SyntaxNodeAnalysisContext or the Semantic Model.
How can I get the Solution or Document in the Diagnostic Analyzer?
Edit
I tried getting the solution through the AdhocWorkspace however the current projects are not populated so that will not work.
var solution = new AdhocWorkspace().CurrentSolution;
I would like to store an API key in a configuration file without checking it into source control, and read the data in my UWP app.
A common solution is to store the key in .config file (such as app.config or web.config) and access it like so:
var apiKey = ConfigurationManager.AppSettings.Get("apiKey");
I'm working on a Universal Windows (UWP) app and can't access the System.Configuration namespace that holds ConfigurationManager.
How can I access AppSettings in UWP app?
Alternatively, what's the best way to access configuration data in an UWP app?
In my specific use case I needed to use an external file that is not tracked by source control. There are two ways to access data from resource or configuration files.
One is to open and parse a configuration file. Given a file sample.txt with Build Action Content (Copy to Output Directory doesn't matter), we can read it with
var uri = new System.Uri("ms-appx:///sample.txt");
var sampleFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
or
var packageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var sampleFile = await packageFolder.GetFileAsync("sample.txt");
followed by
var contents = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
Alternatively, we can use Resources. Add a new Resource item to the project, called resourcesFile.resw. To access data, use:
var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile");
var token = resources.GetString("secret");
I wrote more verbose answer in a blog post Custom resource files in UWP
It's an old question, but here my solution :
Create a partial class Config.cs (for example) with all the properties you'r needed
Add a partial method void Init()
Call Init in the constructor
Create an other file Config.partial.cs with the void Init() method filling all your properties
-> Use #if DEBUG / #else / #endif to switch from Debug/Release
-> Use exclude Config.partial.cs from Github to not import it in the repository
Now it compile and it's not in the repository
Alternatively you can set in Config.cs default (not secret) datas.
Config.cs :
public partial class Config
{
public Config()
{
Init();
}
partial void Init();
public string ApiKey{ get; private set; }= "DefaultValueAPIKEY";
}
Config.partial.cs
public partial class Config
{
partial void Init()
{
#if DEBUG
this.ApiKey = "DebugAPIKEY";
#else
this.ApiKey = "ReleaseAPIKEY";
#endif
}
}
I'm thinking that what you call "ApiKey" is the static key that an API gives you to generate an access token. If this is the case, maybe the best way to achieve this is to create a static class out of the source control with that value inside of it, something like this:
public static class MyCredentials
{
public static string MyApiKey = "apiKey";
}
Then you access that value easily from your code:
var myApiKey = MyCredentials.MyApiKey;
If you want to store values in a plain-text file instead you will have to write/read it manually using StorageFile and FileIO classes.
Instead, if "ApiKey" means the dynamic access token, then the best solution is use ApplicationDataContainer as stratever says.
You don't need to create a configuration file. UWP has a built-in solution to store local settings/configurations. Please check this tutorial:
https://msdn.microsoft.com/en-us/library/windows/apps/mt299098.aspx
Using ApplicationDataContainer, you will be able to get a value by key:
Object value = localSettings.Values["exampleSetting"];