Reference to the right "System" in c# project - c#

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

Related

Windows.UI.Notifications is missing

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.

C# ChromimunFX: How to create multiTab browsing, and isolate between each tab?

I’m trying to use an embedded browser into my WinForms application. I used CefSharp ChromiumWebBrowser, it work perfectly. However, CEFSharp requires the Visual C++ 2013, or the Visual C++ 2008….I think it is a complicated dependency. I'm creating a portable application without the dependency envirenment.
I have found another library, similar CefSharp, also use Chrominum, called ChromiumFX (visit: https://bitbucket.org/chromiumfx/chromiumfx ). The library uses the .Net Framework 3.5 (Default available in Windows 7) , no need to install Visual C++. And it is suitable for my application.
But I don’t find any way to create multi tabs application with this library. Here is what I tried to do:
private void LifeSpanHandler_OnBeforePopup(object sender, CfxOnBeforePopupEventArgs e)
{
e.SetReturnValue(true);
tabPage2.InvokeOnUiThreadIfRequired(() =>
{
ChromiumWebBrowser b = new ChromiumWebBrowser(e.TargetUrl);
b.Dock = DockStyle.Fill;
tabPage2.Controls.Add(b);
});
}
InvokeOnUiThreadIfRequired is an extension method:
public static void InvokeOnUiThreadIfRequired(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
But the application error and the program has crashed.
Another thing, when I created a new instance of ChromiumWebBrowser, I want it isolated with another instance, it means do not use the same cookies, sessions with any instance (private browser). In CefSharp, just create a new RequestContext for new instance:
webbrowser.RequestContext = new RequestContext();
But in ChromiumFX, I dont find any way to do that!
Somebody help me? Thank for you help!

How to add content to windows taskbar

I have been trying to figure out, for some time, how to add content to the taskbar next to the clock. You can see examples of this in NetSpeedMonitor or NetWorx. I am a noob to taskbar but I cannot find anything no matter how hard I look. I am not interested in ThumbButtonInfo or NotifyIcon. Here are a a couple examples of content in the taskbar(incase I'm not saying this right). I would like so be able to do something similar to the first one:
Thank you,
Rymn
There's an example in codeproject showing Extending Explorer with Band Objects using .NET and Windows Forms
Build a Release version of BandObjectLib and register it in the Global
Assembly Cache. The easiest way to do this is to open
BandObjectLib.sln in Visual Studio, set the active configuration to
Release and select 'Rebuild Solution' from the 'Build' menu. The
second project in the solution - RegisterLib - is a C++ utility
project that performs the 'gacutil /if BandObjectLib.dll' command that
puts assembly into GAC.
As you probably already know, Band Objects are COM components. And for
the .NET framework to find an assembly that implements a COM component
it must be either be registered in the GAC or located in the directory
of the client application. There are two possible client applications
for Band Objects - explorer.exe and iexplorer.exe. Explorer is located
in the windows directory and IE somewhere inside 'Program Files'. So
GAC is actually the only one option in this case. Thus .NET assemblies
that implement Band Objects should be registered in GAC and all
libraries they depend on - like BandObjectLib.dll - should also be
there.
Assemblies in the GAC must have strong names and thus key pairs are
required. I have provided the BandObjects.snk file with a key pair but
I encourage you to replace it with your own. See the sn.exe tool for
more details.
Create a new Windows Control Library project and call it SampleBars.
We are going to rely on the base functionality of BandObjectLib so we
have to add a reference to BandObjectLib\Relase\bin\BandObjectLib.dll.
As we are developing a 'Hello World Bar', rename UserControl1.cs and
the UserControl1 class inside it appropriately - into HelloWolrdBar.cs
and HelloWorldBar. Also put the following lines at the beginning of
HelloWorldBar.cs:
using BandObjectLib;
using System.Runtime.InteropServices;
Make HelloWorldBar class inherit BandObject instead of
System.Windows.Forms.UserControl. As I mentioned earlier, Band Objects
are COM components so we should use the Guid attribute. Use
guidgen.exe to generate your unique GUID or you can use the one I have
generated for you:
[Guid("AE07101B-46D4-4a98-AF68-0333EA26E113")]
We also have to sign our assembly with a strong name. You can do this
by putting the following line into AssemblyInfo.cs file:
[assembly: AssemblyKeyFile(#"..\..\..\BandObjects.snk")]
Now its time to decide what kind of Band Object we want to develop.
Lets make it an Explorer Toolbar as well as a Horizontal Explorer Bar
(also known as a Browser Communication Band). All we need to do to
implement this decision is to add custom BandObject attribute to our
HelloWorldBar class:
[Guid("AE07101B-46D4-4a98-AF68-0333EA26E113")]
[BandObject("Hello World Bar",
BandObjectStyle.Horizontal | BandObjectStyle.ExplorerToolbar,
HelpText = "Shows bar that says hello.")]
public class HelloWorldBar : BandObject
{ ...
That's enough to make our control available through 'View->Explorer
Bars' and 'View->Toolbars' explorer menus. It also takes care of menu
item text - "Hello World Bar", and hen the menu item is highlighted
status bar displays "Shows bar that says hello.". Don't you like
declarative programming and custom attributes?
Now it is time to open HelloWorldBar.cs in the Visual Studio Designer
and put some controls on it. Although in my version of HelloWorldBar I
decided to put a single button with 'Say Hello' caption on it you are
free to do something more personalized. I made the size of the button
equal to the size of the control's client area and also set its Anchor
property to the combination of all possible styles - 'Top, Bottom,
Left, Right'. The background color is 'HotTrack' and ForeColor is
'Info'.
The BandObject control has several properties specific to the Band
Objects (and so classes derived from it) - Title , MinSize, MaxSize
and IntegralSize. I set Title for HelloWorldBar to "Hello Bar" and
both MinSize and Size to '150, 24'. Oh, and in button's On Click event
handler I put code that displays a message box. This is what my final
code looks like (and most of it was generated by VS.Net):
using System;
using System.ComponentModel;
using System.Windows.Forms;
using BandObjectLib;
using System.Runtime.InteropServices;
namespace SampleBars
{
[Guid("AE07101B-46D4-4a98-AF68-0333EA26E113")]
[BandObject("Hello World Bar", BandObjectStyle.Horizontal
| BandObjectStyle.ExplorerToolbar, HelpText = "Shows bar that says hello.")]
public class HelloWorldBar : BandObject
{
private System.Windows.Forms.Button button1;
private System.ComponentModel.Container components = null;
public HelloWorldBar()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = (((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.button1.BackColor = System.Drawing.SystemColors.HotTrack;
this.button1.ForeColor = System.Drawing.SystemColors.Info;
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(150, 24);
this.button1.TabIndex = 0;
this.button1.Text = "Say Hello";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// HelloWorldBar
//
this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1 });
this.MinSize = new System.Drawing.Size(150, 24);
this.Name = "HelloWorldBar";
this.Size = new System.Drawing.Size(150, 24);
this.Title = "Hello Bar";
this.ResumeLayout(false);
}
#endregion
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Hello, World!");
}
}
}
Ok, now we are ready to build SampleBars.dll but its not enough to see
it in explorer yet. We have to put our assembly into the GAC as well
as register it as a COM server. There are tools - gacutil.exe and
regasm.exe that do just this. The C++ utility project named Register
in my version of the SampleBars solution liberates me from using these
tools manually. It has no files in it, just the following post-build
command (debug version):
cd $(ProjectDir)..\bin\Debug
gacutil /if SampleBars.dll
regasm SampleBars.dll
Of cause you have to make sure that Register project is the last one
to be built in the solution using Project Dependencies / Build Order.
After building the solution, and executing the gacutil and regasm
commands, we are finally ready to start Explorer and see our toolbar
and explorer bar. And if you did everything right you should be able
to see something like the picture at the top of the article. On this
picture you can also see how HelloWorldBar looks in the Windows
Taskbar. To achieve this all you need to do is to modify BandObject
attribute adding the BandObjectStyle.TaskbarToolBar flag.
Also you might want to look at this answer
According to Microsoft, Deskbands are not recommended for Windows
7, although they still work. Also keep in mind that Microsoft
requires that Deskbands support Aero on Windows 7 via IDeskband2
Interface, rather than IDeskband. Also, Micorosft has officially said
that IDeskBand2 may be altered or unavailable in subsequent versions
of the operating system or product.
Finally, be very careful about creating shell extensions in managed
code.

ApplicationView does not contain a definition for GetForCurrentView?

I'm currently following a tutorial from the MSDN which isn't very clear on somethings the issue that i am having is that the method that they are suggesting that i use is apparently not available to that class
Here is the link to the tutorial : http://msdn.microsoft.com/en-us/library/windows/apps/dn495655.aspx
Here is the code that i am using
In my App.Xaml.cs not my Main page i have an event handler
public App()
{
this.InitializeComponent();
Window.Current.SizeChanged += Current_SizeChanged;
this.Suspending += OnSuspending;
}
Underneath this the stub method
void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
{
// Get the new view state but its not allowing me to use getforcurrent state
// almost like it doesn't exist
string CurrentViewState = ApplicationView.GetForCurrentView().Orientation.ToString();
// Trigger the Visual State Manager
VisualStateManager.GoToState(this, CurrentViewState, true);
}
If anyone else has followed this tutorial can they tell me what is going wrong ?
Have i put the code in the wrong page
Am i missing a library
I am following this microsoft tutorial word for word and it giving me the error which is the title of my post i have done research and i am using the latest version of visual studio and it's still not letting me use this method because it do not exist apparently
Try using Windows.UI.ViewManagement; at the top of the program.
The minimum supported version of this API is Windows 8.1. So you can't use it with the Windows 8 API.
MSDN reference

Silverlight C# - ComponentOne Spellchecker not loading dictionary

This may be a long shot, but I'm using ComponentOne's Spellchecker control for Silverlight. I made a test project, added a plain textbox and a button to it, added the references to the C1.Silverlight and C1.Silverlight.SpellChecker bits, and added the dictionary file to my project.
In the code, I called up the spellchecker on button1's click event and it worked SPLENDIDLY. The spellchecker dialog shows up, and works exactly as it should.
Since that test was successful, I then tried to implement this into my existing project. I've had no success for absolutely NO reason that I can determine, since I used the EXACT SAME code.
Here's the code I use to call the component:
using C1.Silverlight;
using C1.Silverlight.SpellChecker;
using C1.Silverlight.Resources;
public partial class MainPage : UserControl
{
C1SpellChecker spellChecker = new C1SpellChecker();
public MainPage()
{
InitializeComponent();
spellChecker.MainDictionary.LoadAsync("C1Spell_en-US.dct");
}
private void btnSpelling_Click(object sender, RoutedEventArgs e)
{
var dlg = new C1SpellDialog();
spellChecker.CheckControlAsync(txtArticle, false, dlg);
}
The references to C1.Silverlight and C1.Silverlight.Spellchecker are added to this project as well, and the dictionary as been added in the same fashion as well. The issue seems to be that for whatever reason the dictionary is not loading, because the spellChecker.Enabled method returns whether or not the main dictionary has been loaded. If I call MessageBox.Show("SpellChecker Enabled = " + spellChecker.Enabled.ToString()); it shows false, even though the call to load the dictionary is there (as you can see).
What would cause the dictionary to not load? Have I added it to my project incorrectly somehow?
EDIT: I suspect that I have added the dictionary to the project incorrectly, because the ComponentOne reference states:
If C1SpellChecker cannot find the
spelling dictionary, it will not throw
any exceptions. The Enabled property
will be set to false and the component
will not be able to spell-check any
text.
I just don't know what's wrong though because it was added in the same way that it was in the test project (Right clicked on the project.web->Add->Existing Item)
As always, thank you!
-Sootah
You could add the dictionary to the Silverlight app as an embedded resource and then load it using this code:
public MainPage()
{
InitializeComponent();
// load C1SpellChecker dictionary from embedded resource
var asm = this.GetType().Assembly;
foreach (var res in asm.GetManifestResourceNames())
{
if (res.EndsWith(".dct"))
{
using (var s = asm.GetManifestResourceStream(res))
{
sc.MainDictionary.Load(s);
break;
}
}
}
}
I think this post is duplicated in our forum as well, but will answer first here. Please try this:
1) Try to access the .dct file using your browser. If you cannot see it, it's probably because your web server is not serving that type of files. You need ton configure the web server to allow it.
2) verify the URL you are using is correct.http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/86955/241328.aspx#241328
3) Check you are setting everything correctly: http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/81924/227790.aspx#227790
Hope this helps!

Categories