I want to create simple toast notification to action center in windows 10 from this example. But I got problem on Step 2:
using Windows.UI.Notifications;
It`s missing. But I have spent a lot of time to find it and got no result. I really have no idea where I can find or at least download it.
What I tried:
After long search I found Windows.UI.dll in C:\Windows\System32 but when I try to add it as reference into project I got this error. Even after I tried to copy it and made this fully accessible nothing changed
I tried to reinstall .Net (I`m using 4.5.2)
Installed Windows 10 SDK
Tried to import with global
Added
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
Added System.Runtime.dll reference
Example code which probably is useless for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
namespace MessagerClient.Notifications {
class DefaultWindowsNotification {
public static void notificationTest() {
string title = "Andrew sent you a picture";
string content = "Check this out, Happy Canyon in Utah!";
string image = "http://blogs.msdn.com/something.jpg";
string logo = "ms-appdata:///local/Andrew.jpg";
ToastVisual visual = new ToastVisual() {
BindingGeneric = new ToastBindingGeneric() {
Children =
{
new AdaptiveText()
{
Text = title
},
new AdaptiveText()
{
Text = content
},
new AdaptiveImage()
{
Source = image
}
},
AppLogoOverride = new ToastGenericAppLogo() {
Source = logo,
HintCrop = ToastGenericAppLogoCrop.Circle
}
}
};
Console.WriteLine("NOTIFICATION");
//Can`t use because of Windows.UI library
ToastNotificationManager.CreateToastNotifier().Show(visual);
}
}
}
You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:
Edit the .csproj file with a text editor, Notepad will do. Insert this:
<PropertyGroup>
<TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
</PropertyGroup>
Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.
Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.
Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:
using Windows.UI.Notifications;
...
private void button1_Click(object sender, EventArgs e) {
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var text = xml.GetElementsByTagName("text");
text[0].AppendChild(xml.CreateTextNode("Hello world"));
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}
Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.
If anyone should happen to stumble on this, see this similar but newer post -
Toast Notifications in Win Forms .NET 4.5
Read Stepan Hakobyan's comment at the bottom.
Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.
Related
this is my first question here so please don't be to harsh on me :) Anyway, let's get right to it:
For an application I need to convert a PDF file to an Image file (Specific format doesn't matter but preferably png or jpg). To get this done, I try to use ImageMagick but when I try to convert anything, it will throw an error.
Now after some research I came to the conclusion I needed to have Ghostscript installed, which I tried to get from the NuGet package manager integrated in Visual Studio 2017. Anyway, when I try to install said package, it throws the following error:
Severity Code Description Project File Line Suppression >State
Error Failed to add reference to 'gsdll32'.
Please make sure that the file is accessible, and that it is a valid >assembly or COM component.
I'm trying to accomplish this using Visual Studio 2017 with C#. The API's I am using are:
+Magick.NET-Q16-AnyCPU V7.11.1
+GhostScriptSharp V1.3.1.4
+Ghostscript V9.2.0 (Throws error)
In case it is required to understand what I am trying, here is the code that I am trying to compile:
using ImageMagick.Configuration;
using ImageMagick.Defines;
using ImageMagick.ImageOptimizers;
using ImageMagick;
using GhostscriptSharp;
using GhostscriptSharp.Settings;
public MagickImageCollection PDFOutput;
public Image Current;
public org.pdfclown.documents.Page CurrentPage;
private void BtnConvert_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
ImageMagick.MagickNET.Initialize();
MagickReadSettings Settings = new MagickReadSettings();
Settings.Density = new Density(300, 300);
Settings.Format = MagickFormat.Jpg;
using (MagickImageCollection Images = new MagickImageCollection())
{
Images.Add(openFileDialog1.FileName);
int Page = 1;
int i = 0;
foreach(MagickImage Image in Images)
{
Image.Write("FilePage #" + Page);
PDFOutput[i] = Image;
Page++;
i++;
}
MessageBox.Show(PDFOutput.Count.ToString());
}
}
catch(Exception E)
{
MessageBox.Show(E.Message);
}
Am I missing something regarding the GhostScipt install? Does it only work when downloaded directly from the GhostScript website?
I hope that I have provided enough context to my problem and I'll be looking forward to any answers I may get on this.
Many thanks in advance!!
Kind Regards,
Melvin
Yes GhostScript is licensed in such a way, that people don't include it in their wrappers/nugets. You need to make sure you have the dll.
You generally have to download it (gsdll32.dll), add it to the project and output it to your output path (or anything similar, like install it) so that your application can find the gsdll32.dll and load it.
Also note you will need the appropriate bitness aswell
im an currently following this guide to add windows toast notifications to my app.
https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/send-local-toast-desktop
i need to create a shortcut that contains the System.AppUserModel.ID and System.AppUserModel.ToastActivatorCLSID.
now the website says to just have your installer create this and they recommend using WIX. which is fine but i would rather just create the shortcut from C# code.
so there is this example that creates the shortcut via C#.
https://code.msdn.microsoft.com/windowsdesktop/sending-toast-notifications-71e230a2
but it only shows adding the AppUserModel.ID and not the ToastActivatorCLSID...
here is some of that code...
private void InstallShortcut(String shortcutPath)
{
// Find the path to the current executable
String exePath = Process.GetCurrentProcess().MainModule.FileName;
IShellLinkW newShortcut = (IShellLinkW)new CShellLink();
// Create a shortcut to the exe
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath));
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetArguments(""));
// Open the shortcut property store, set the AppUserModelId property
IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut;
using (PropVariant appId = new PropVariant(APP_ID))
{
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(System Properties.System.AppUserModel.ID, appId));
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.Commit());
}
// Commit the shortcut to disk
IPersistFile newShortcutSave = (IPersistFile)newShortcut;
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true));
}
the thing is that the AppUserModel does not have a ToastActivatorCLSID property. seems strange.
i figured i could just add another using block to add the ToastActivatorCLSID property like this
using (PropVariant clsId = new PropVariant(CLSID))
{
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(System Properties.System.AppUserModel.ToastActivatorCLSID, CLSID));
ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.Commit());
}
but the SystemProperties.System.AppUserModel.ToastActivatorCLSID doesnt exist.
right now the appuser model is coming from Microsoft.WindowsAPICodePack.Shell.PropertySystem.
this page shows it should exist
https://learn.microsoft.com/en-us/windows/desktop/properties/props-system-appusermodel-toastactivatorclsid
i would if with that information i could make some kind of interface or something to add in that ToastActivatorCLSID.
there is very little on the internet on this topic. Don't know if there is a different reference or something.
any help would be great
I've been running into the same problem and I've found a work around.
Clone this github repo: https://github.com/aybe/Windows-API-Code-Pack-1.1
open the WindowsAPICodePack12.sln in visual studio.
open Shell > PropertySystem > SystemProperties.cs
find the AppUserModel class on line 2302
add this code to the class:
public static PropertyKey ToastActivatorCLSID
{
get
{
PropertyKey key = new PropertyKey(new Guid("{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}"), 26);
return key;
}
}
Build the project. Open the bin folder (where the built projects go) and find Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll
Reference these dlls in your project instead of the original code pack.
This is a cosmetic issue but my application has a default icon on the control panel. Many other applications have custom icons.
My application does have custom icons for the menu and task bar.
How can the icon displayed on the Control Panel be changed using Visual Studio 2015 or later?
Update:
There has been a change in how Visual Studio creates installers. I'm not sure when it occurred, but 2015 definitely does not have a "deployment project". The majority of the hits on Google suggest going to the deployment project properties which does not exist under VS 2015 apps.
This was why I included the tag for visual-studio-2015. Sorry, not to have mentioned that in the original question. It would have been good information.
Using the registry is a possibility but the registry path mentioned, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, does not exist. It does sound kludgy to have the application check it's own icon in the registry all the time. It sounds like an installer function to me.
A post on the Microsoft Developer Network provided an answer. It also modifies the registry. I enhanced it by removing hard-coded values for the application name and the icon file.
// These references are needed:
// using System.Reflection;
// using System.Deployment.Application;
// using System.IO;
// using Microsoft.Win32;
private static void SetAddRemoveProgramsIcon(string iconName)
{
// only run if deployed
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.IsFirstRun)
{
try
{
string assemblyTitle="";
object[] titleAttributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
if (titleAttributes.Length > 0 && titleAttributes[0] is AssemblyTitleAttribute)
{
assemblyTitle = (titleAttributes[0] as AssemblyTitleAttribute).Title;
}
string iconSourcePath = Path.Combine(System.Windows.Forms.Application.StartupPath, iconName);
if (!File.Exists(iconSourcePath))
{
return;
}
RegistryKey myUninstallKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Uninstall");
string[] mySubKeyNames = myUninstallKey.GetSubKeyNames();
for (int i = 0; i < mySubKeyNames.Length; i++)
{
RegistryKey myKey = myUninstallKey.OpenSubKey(mySubKeyNames[i], true);
object myValue = myKey.GetValue("DisplayName");
if (myValue != null && myValue.ToString() == assemblyTitle)
{
myKey.SetValue("DisplayIcon", iconSourcePath);
break;
}
}
}
catch (Exception) { }
}
return;
}
The original article by Robin Shahan is here: RobinDotNet
For WPF application we need to replace the following code
string iconSourcePath = Path.Combine(System.Windows.Forms.Application.StartupPath, iconName);
Replace with below code
string iconSourcePath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Startup), "TestIcon.ico");
I know you want 2015 but others may be looking for this in newer versions, like I was.
In Visual Studio 2019 Community we can go to the properties panel for the main setup project and the top property is AddRemoveProgramsIcon.
I have just come through this case today. I know it is old but will be useful for new seekers. To expose icon in Control Panel do the following:
Make a folder in [solution Folder][Project Folder]\bin\debug\images
Copy your icon in the new folder
In Set Up project always refer to the icon in the new created folder.
Solved my problem easily
I recently started working with Xamarin to build Android apps in C#.
There is one issue I have had in particular that makes it very hard for me to make any progress:
error CS0117
I have two identical projects, the issue only shows up in one of them.
It originally occured in both but rebuilding a few times fixed the first one.
The second one seems to be more persistent.
I really need to find a solution to this issue, as referencing is very basic and needed. Not to mention, it happens in every new project.
Here is my code:
NoteMath
using System;
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace NoteMath_v1._0._1
{
[Activity(Label = "noteMath", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Window.RequestFeature(Android.Views.WindowFeatures.NoTitle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
EditText etInput = FindViewById<EditText>(Resource.Id.etInput);
TextView tvConsole = FindViewById<TextView>(Resource.Id.tvConsole);
etInput.KeyPress += (object sender, EditText.KeyEventArgs e) =>
{
e.Handled = false;
if (e.Event.Action == Android.Views.KeyEventActions.Down && e.KeyCode == Android.Views.Keycode.Enter)
{
tvConsole.Append("\n>" + HandleInput.TransferInput(etInput.Text));
etInput.Text = "";
e.Handled = true;
}
};
}
}
}
The code you posted looks good. The error is clearly not coming from there. You´ve got something wrong in any of your resource layout or xml files.
The problem actually is that Visual Studio won´t show up Resource generation errors in the Errors panel, eventhough it should be like that (I think this will be fixed in future versions). At the moment it is just telling you that the class Id doesn´t exists.
Resources.designer.cs is a class generated by Xamarin when you edit any resource file. It containts references to any declaration, id, etc in the xml/axml files. If the resource has an error, Resources.designer.cs generation will fail, but you get a really vague error hint.
The first thing you can try is rebuilding your Android project, forcing all resources to be generated again. Otherwise try the following:
Good news is that you can see generation errors by changing build output verbosity to "detailed":
Now compile your project again and check the output window. It will tell you exactly what the problem is.
After you fix it, Resource.Id class will be generated.
For me, this worked:
Step 1.
Project > Update NugetPackages
Step 2.
Build > Clean All
Step 3.
Build > Build All
I am super new. The only thing that really worked for me was manually running this powershell script in my project root:
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
I am not sure why the live view/build output isn't more helpful, or that visual studio isn't cleaning these files correctly in my xamarin project.
Special thanks to this guy:
https://montemagno.com/easily-clean-bin-obj-folders/
I am new to c# and visual studio and have run into some trouble.
I have created a project with references to "Windows" and ".Net" in visual studio because I want to test a little with smart cards.
The code:
using System;
using Windows.Devices.Enumeration;
using Windows.Devices.SmartCards;
class HandleSmartCard
{
public async void checkNumberOfSmartCards()
{
string selector = SmartCardReader.GetDeviceSelector();
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
// return "2";
}
}
So far it looks fine. However I also want the project to be able to use
System.Windows.Forms; which I have used in a previos test.
I add reference to System.Windows.Forms; and try to create a form. However in that form when I try this:
Form prompt = new Form();
System.Windows.Forms.Button confirmation = new System.Windows.Forms.Button() { Dock = DockStyle.Bottom };
confirmation.Click += (sender, e) => { prompt.Close(); };
I get a red line under "Close" with the message:
Reference to type component claims it is defined in system but could
not be found.
System is referenced at top of file, but I am guessing it is the wrong type of system right?
Can I somehow use "both Systems" in one project so to speak?
I hope someone understands what I mean and can help me understand this.
You're most likely working on a UWP app. The API for UWP apps is a very small subset of the full .NET framework. You can find more information here
https://msdn.microsoft.com/en-us/library/windows/apps/mt185501.aspx
You're attempting to reference System.Windows.Forms which is not allowed in UWP applications.
Looks like you're trying to create a popup to ask the user something. For this, use the MessageDialog class.
https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.popups.messagedialog.aspx