UWP: Cannot load PWM Controllers using Lightning on Raspberry Pi 2? - c#

i justed started working on an older Project i started once, but unfortunately the PWM Controller is not working anymore with the Lightning Driver. I am using Visual Studio 2017, the RPi2 is running at 10.0.15063.414 and I've installed the following Nuget-Packages:
Microsoft.IoT.Lightning (v1.1.0)
Microsoft.NETCore.UniversalWindowsPlatform (v5.3.3)
WinRTXamlToolkit.Controls.DataVisualization (v2.3.0)
The Project includes references to
Analyzer
Microsoft.IoT.Lightning
Microsoft.NETCore.UniversalWindowsPlatform
%ClassesLibrary%
UniversalWindows
Windows IoT Extensions for the UWP
WinRTXamlToolkit.Controls.DataVisualization,
where %ClassesLibrary% is an user-defined Project containing some classes for my Project. In the configuration web Interface of Windows IoT Core in the devices section, the Direct Memory Mapped Driver (Current Driver) is selected.
My initialization Code Looks like this
private static async Task InitOnboardHardware()
{
if (LightningProvider.IsLightningEnabled)
{
LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
GpioController gpioController = GpioController.GetDefault();
var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
if (pwmControllers != null)
{
m_PWMController = pwmControllers[1];
//m_PWMController = (await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider()))[1];
m_PWMController.SetDesiredFrequency(100);
m_RPin = m_PWMController.OpenPin(18);
m_GPin = m_PWMController.OpenPin(23);
m_BPin = m_PWMController.OpenPin(24);
m_WPin = m_PWMController.OpenPin(25);
m_RPin.SetActiveDutyCyclePercentage(0);
m_GPin.SetActiveDutyCyclePercentage(0);
m_BPin.SetActiveDutyCyclePercentage(0);
m_WPin.SetActiveDutyCyclePercentage(0);
m_RPin.Start();
m_GPin.Start();
m_BPin.Start();
m_WPin.Start();
m_IsHardwareInitialized = true;
}
}
}
The PwmController.GetControllersAsync-method never completes and my application gets stuck on starting up. Also the commented Shorter Version is not working anymore?!
I have really no clue what i could be missing. Therefore, i would greatly appreciate any help.
Thank you in advance!
EDIT: I also tried another sample (https://github.com/lprichar/WindowsIotPwmExample), where i replaced the embedded C/C++ lightning library by the NuGet Package (same Version as in my Project). The sample also Fails: the Pins are all null, because PwmController.GetControllersAsync never completes :-(
EDIT2: I forgot to mention that my package.appxmanifest file also includes the following changes
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
IgnorableNamespaces="uap mp iot">
as well as
<Capabilities>
<Capability Name="internetClient" />
<iot:Capability Name="lowLevelDevices" />
<DeviceCapability Name="109b86ad-f53d-4b76-aa5f-821e2ddf2141" />
</Capabilities>

Please also see my comment to the first post. I had to Change this line
GpioController gpioController = GpioController.GetDefault();
to an async method call
GpioController gpioController = await GpioController.GetDefaultAsync();
and now everythings runs fine!

Related

Blazor proj from scratch+nuget: "There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm'"

[Final update 07.12.2020 23:50 --> for everyone seeking for the anwser]
You are probably adding some nuget package which has in fields DEPENDENCIES .NET Core 3.1. For example Serilog.AspNetCore 3.4.0. In this very example you can include Serilog.AspNetCore 3.2.0 because it has in DEPENDENCIES only .NetStandard 2.0. See more explanation in #Ogglas answer.
There is not enough space on earth to ask the one and only question: "Why, o why Microsoft?":) The message is not clearly correlating issue with the solution - this is the lightest euphemism i am capable of making :)
For me, Blazor is very promising but it is still more a beta version. And not only for me. The startblazoring guys are claiming, that Blazor can be fickle sometimes. And I cannot agree more;) I am keeping finger crossed for it. But I suppose it would be a "ready product" only after .NET 6.0.
[Original Topic]
This is so frustrating :)
I hate errors, when I cannot simply interact and understood where it is coming from. I know, I am ignorant, and If I would pay more attention to "how is the blazor app created" I would understand in eye blink.
But for now it is only frustrating. What is? The error message:
Severity Code Description Project File Line Suppression State
Error NETSDK1082 There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm'. TestBlazorAppNoRuntimeError.Client C:\Program Files\dotnet\sdk\5.0.100\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.FrameworkReferenceResolution.targets 387
Really, what can you fix here?:D Ehhhhh. I understand that .NET 5 is a "new thing". I understand Blazor is a "new thing" But really? It is really easy to "break" ;) (with a message that is saying nothing)
So what did I do?
Did I create very complicated project with hundreds of thousands of files?
No
Did I add hundreds of thousands of nuget packages.
No
All it takes is to create Blazor Webassembly app and add one nuget package to the shared (common) library (FYI: IdentityServer4 package). That is all folks. Kudos if you would now, that this package specificly is causing this issue (because i found out only by mistake):
There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm'.
Really, there is a great correlation here: between the error message and the package being added (this was sarcasm if anyone missed it:) )
So if you want to reproduce it create create "Blazor Webassembly":
I don't suppose the options chosen are making the difference. But if this is the case - you can see what option I did choose. Then just add IdentityServer4 nuget package to shared library:
https://www.nuget.org/packages/IdentityServer4/
That is all
If you are too lazy - download this project and check for yourself:
https://ufile.io/751l5wgq
I saw hundreds of SOF topics regarding this message:
There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm'.
But none of those was so easy to reproduce.
Why I am creating this topic?
Because I did try to implement (by copy-pasting to my solution) what guys did create in Blazor boilerplate here:
https://github.com/enkodellc/blazorboilerplate
At the beginning, by mistake, I've added Identity4 NuGet instead of Identity4.storage and that is why I did observe such behavior (such error) and did correlate this package with this error. When I rolled back from Identity4 to Identity4.storage everything was correct once again. But after that I did a lot of code transfer from this repository. And once I've ended, right now, everything is compiling but once again I have:
There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm'.
And it is driving me crazy. Maybe you would have some idea, how to find out WHAT is causing this error (exactly the same as previously Identity4 nuget package was causing it)
[UPDATE 06.12.2020 12:30]
The question here is more: "Why is it happening and how to locate package causing the issue" I know that I can second guess what is causing this message to appear.
I did a little investigation. This error is showing in this target:
<ResolveRuntimePackAssets FrameworkReferences="#(FrameworkReference)"
ResolvedRuntimePacks="#(ResolvedRuntimePack)"
UnavailableRuntimePacks="#(UnavailableRuntimePack)"
SatelliteResourceLanguages="$(SatelliteResourceLanguages)"
DesignTimeBuild="$(DesignTimeBuild)">
<Output TaskParameter="RuntimePackAssets" ItemName="RuntimePackAsset" />
</ResolveRuntimePackAssets>
<ItemGroup>
<ReferenceCopyLocalPaths Include="#(RuntimePackAsset)"
Condition="'$(CopyLocalLockFileAssemblies)' == 'true' and ('$(SelfContained)' == 'true' or '%(RuntimePackAsset.RuntimePackAlwaysCopyLocal)' == 'true')" />
</ItemGroup>
so I did google ResolveRuntimePackAssets and found this repo and this file:
https://github.com/dotnet/sdk/blob/release/5.0.2xx/src/Tasks/Microsoft.NET.Build.Tasks/ResolveRuntimePackAssets.cs and such code:
foreach (var unavailableRuntimePack in UnavailableRuntimePacks)
{
if (frameworkReferenceNames.Contains(unavailableRuntimePack.ItemSpec))
{
// This is a runtime pack that should be used, but wasn't available for the specified RuntimeIdentifier
// NETSDK1082: There was no runtime pack for {0} available for the specified RuntimeIdentifier '{1}'.
Log.LogError(Strings.NoRuntimePackAvailable, unavailableRuntimePack.ItemSpec,
unavailableRuntimePack.GetMetadata(MetadataKeys.RuntimeIdentifier));
}
}
Looks like the code "causing" the issue (this calls for writing down information in message about: unavailableRuntimePack.ItemSpec - it would be so much easier;))
So right now the only thing is to locate what is filling this: UnavailableRuntimePacks property. I don't see any code doing that so it have to be some reflection. I've located this code which is probably doing it:
https://github.com/dotnet/sdk/blob/release/5.0.2xx/src/Tasks/Microsoft.NET.Build.Tasks/ProcessFrameworkReferences.cs
And this method:
private void ProcessRuntimeIdentifier(
string runtimeIdentifier,
KnownRuntimePack selectedRuntimePack,
string runtimePackVersion,
List<string> additionalFrameworkReferencesForRuntimePack,
HashSet<string> unrecognizedRuntimeIdentifiers,
List<ITaskItem> unavailableRuntimePacks,
List<ITaskItem> runtimePacks,
List<ITaskItem> packagesToDownload,
string isTrimmable,
bool addToPackageDownload)
{
var runtimeGraph = new RuntimeGraphCache(this).GetRuntimeGraph(RuntimeGraphPath);
var knownFrameworkReferenceRuntimePackRuntimeIdentifiers = selectedRuntimePack.RuntimePackRuntimeIdentifiers.Split(';');
string runtimePackRuntimeIdentifier = NuGetUtils.GetBestMatchingRid(
runtimeGraph,
runtimeIdentifier,
knownFrameworkReferenceRuntimePackRuntimeIdentifiers,
out bool wasInGraph);
if (runtimePackRuntimeIdentifier == null)
{
if (wasInGraph)
{
// Report this as an error later, if necessary. This is because we try to download
// all available runtime packs in case there is a transitive reference to a shared
// framework we don't directly reference. But we don't want to immediately error out
// here if a runtime pack that we might not need to reference isn't available for the
// targeted RID (e.g. Microsoft.WindowsDesktop.App for a linux RID).
var unavailableRuntimePack = new TaskItem(selectedRuntimePack.Name);
unavailableRuntimePack.SetMetadata(MetadataKeys.RuntimeIdentifier, runtimeIdentifier);
unavailableRuntimePacks.Add(unavailableRuntimePack);
}
else if (!unrecognizedRuntimeIdentifiers.Contains(runtimeIdentifier))
{
// NETSDK1083: The specified RuntimeIdentifier '{0}' is not recognized.
Log.LogError(Strings.RuntimeIdentifierNotRecognized, runtimeIdentifier);
unrecognizedRuntimeIdentifiers.Add(runtimeIdentifier);
}
}
else if (addToPackageDownload)
{
foreach (var runtimePackNamePattern in selectedRuntimePack.RuntimePackNamePatterns.Split(';'))
{
string runtimePackName = runtimePackNamePattern.Replace("**RID**", runtimePackRuntimeIdentifier);
if (runtimePacks != null)
{
TaskItem runtimePackItem = new TaskItem(runtimePackName);
runtimePackItem.SetMetadata(MetadataKeys.NuGetPackageId, runtimePackName);
runtimePackItem.SetMetadata(MetadataKeys.NuGetPackageVersion, runtimePackVersion);
runtimePackItem.SetMetadata(MetadataKeys.FrameworkName, selectedRuntimePack.Name);
runtimePackItem.SetMetadata(MetadataKeys.RuntimeIdentifier, runtimePackRuntimeIdentifier);
runtimePackItem.SetMetadata(MetadataKeys.IsTrimmable, isTrimmable);
if (selectedRuntimePack.RuntimePackAlwaysCopyLocal)
{
runtimePackItem.SetMetadata(MetadataKeys.RuntimePackAlwaysCopyLocal, "true");
}
if (additionalFrameworkReferencesForRuntimePack != null)
{
runtimePackItem.SetMetadata(MetadataKeys.AdditionalFrameworkReferences, string.Join(";", additionalFrameworkReferencesForRuntimePack));
}
runtimePacks.Add(runtimePackItem);
}
TaskItem packageToDownload = new TaskItem(runtimePackName);
packageToDownload.SetMetadata(MetadataKeys.Version, runtimePackVersion);
packagesToDownload.Add(packageToDownload);
}
}
}
After analysing it, the reason why Identity4 (for example) is causing this issue is because runtimePackRuntimeIdentifier is null and wasInGraph was true :) But what does mean, we have to dig a little bit further. The key thing here is the method GetBestMatchingRid:
public static string GetBestMatchingRid(RuntimeGraph runtimeGraph, string runtimeIdentifier,
IEnumerable<string> availableRuntimeIdentifiers, out bool wasInGraph)
{
wasInGraph = runtimeGraph.Runtimes.ContainsKey(runtimeIdentifier);
HashSet<string> availableRids = new HashSet<string>(availableRuntimeIdentifiers);
foreach (var candidateRuntimeIdentifier in runtimeGraph.ExpandRuntime(runtimeIdentifier))
{
if (availableRids.Contains(candidateRuntimeIdentifier))
{
return candidateRuntimeIdentifier;
}
}
// No compatible RID found in availableRuntimeIdentifiers
return null;
}
So here we see that runtimePackRuntimeIdentifier was null because it was not found on: availableRuntimeIdentifiers. And this variable is defined as:
var knownFrameworkReferenceRuntimePackRuntimeIdentifiers = selectedRuntimePack.RuntimePackRuntimeIdentifiers.Split(';');
So let's see how is it defined (in the code below variable runtimePackForRuntimeIDProcessing is selectedRuntimePack from the above mention)
KnownRuntimePack runtimePackForRuntimeIDProcessing;
if (knownFrameworkReference.Name.Equals(knownFrameworkReference.RuntimeFrameworkName, StringComparison.OrdinalIgnoreCase))
{
// Only add runtime packs where the framework reference name matches the RuntimeFrameworkName
// Framework references for "profiles" will use the runtime pack from the corresponding non-profile framework
runtimePackForRuntimeIDProcessing = selectedRuntimePack.Value;
includeInPackageDownload = true;
}
else if (!knownFrameworkReference.RuntimePackRuntimeIdentifiers.Equals(selectedRuntimePack?.RuntimePackRuntimeIdentifiers))
{
// If the profile has a different set of runtime identifiers than the runtime pack, use the profile.
runtimePackForRuntimeIDProcessing = knownFrameworkReference.ToKnownRuntimePack();
includeInPackageDownload = true;
}
else
{
// For the remaining profiles, don't include them in package download but add them to unavaliable if necessary.
runtimePackForRuntimeIDProcessing = knownFrameworkReference.ToKnownRuntimePack();
includeInPackageDownload = false;
}
But this is as far as I can go. I don't understand without further investigation how this selectedRuntimePack.RuntimePackRuntimeIdentifiers should be defined. This is the key thing here. Clearly for some reasons IdentityServer4 doesn't belong to selectedRuntimePack.RuntimePackRuntimeIdentifiers and this is the answer I am looking for :)
IdentityServer4 4.1.1 (latest version) is dependent upon .NETCoreApp 3.1
https://www.nuget.org/packages/IdentityServer4/
If you create a Blazor WebAssembly App using .NET Core 3.1 it will work in the Server App.
However when using .NET Core 3.1 both Client and Shared uses .NET Standard 2.1 and is therefore not compatible. These error messages are a lot clearar though:
Error Package restore failed. Rolling back package changes for
'BlazorApp.Shared'.
Error NU1202 Package IdentityServer4 4.1.1 is not compatible with
netstandard2.1 (.NETStandard,Version=v2.1). Package IdentityServer4
4.1.1 supports: netcoreapp3.1 (.NETCoreApp,Version=v3.1) BlazorApp.Shared
As I mentioned in this link, it seems there is an issue regarding to the following package. So remove the package from your project and every other project that has been referenced by your Blazor project(right-click on project, choose edit project file then remove the following):
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" />
In my case (and hopefully in yours too) the only use of this package was the get the constant string "Bearer" with the field member JwtBearerDefaults.AuthenticationScheme. So instead of this just simply use "Bearer" string.
I had the same issue while working on a blazor wasm/server/shared projects. In my case, I narrowed down the issue to the project sdk types:
Client.csproj:
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
Server.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
Shared.csproj definition causing the issue:
<Project Sdk="Microsoft.NET.Sdk.Razor">
Shared.csproj definition without issue:
<Project Sdk="Microsoft.NET.Sdk">
The client wasm project did not like that the shared one was declared as Microsoft.NET.Sdk.Razor and had to change it to Microsoft.NET.Sdk in order to get rid of the error in the title.
I still need to dig further in to better understand the full differences between those two project types but I hope this can help anyone else facing this issue.

Open another application from the current one

We have a UWP app in the Windows Store. From this app we would like to launch various apps on the same system. For this process we need to do 2 things.
Check if the app exists on the system
If yes, launch it. If no, give feedback
We tried a couple of things but i'm searching for the best way to do this.
We would like to launch both other UWP apps and Standalone apps.
I tried messing with the Unity PlayerPrefs, but that acts weird. It works if I make a custom PlayerPref and check if it exists from within 1 app, but as soon as I make a playerpref in the UWP and check for it in the Standalone I get nothing. And vice versa ofcourse. (Yes I know UWP saves its playerprefs somewhere else)
What would be the best general solution to this? Continue messing around with Playerprefs and search for different paths depending on the app we want to open?(Standalone, UWP) or some other way?
EDIT: What I have so far:
if (Input.GetKeyDown(KeyCode.Backspace))
{
PlayerPrefs.SetString("42069" , "testing_this");
PlayerPrefs.Save();
Debug.Log("Wrote key 42069 to registry with: -value testing_this-");
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (PlayerPrefs.HasKey("42069"))
{
Debug.Log("I found the key 42069 in my registry");
cube.SetActive(true);
}
else
{
Debug.Log("I cant find key 42069 in my registry");
}
}
if (Input.GetKeyDown(KeyCode.S))
{
const string registry_key = #"SOFTWARE\DefaultCompany";
using(RegistryKey key = Registry.CurrentUser.OpenSubKey(registry_key))
{
if (key != null)
foreach (string subKeyName in key.GetSubKeyNames())
{
if (subKeyName == "RegistryTesting")
{
Debug.Log("I found the key on path: " + registry_key);
}
}
}
}
EDIT: No one? I know there is a way. All I need to do is check whether a standalone app exists from a UWP app. But I do not have acces to the register in a UWP app. I know there are some ways with bridges etc, but I have no clue how and where to start.
I encountered a somewhat similar situation but I was checking to see if the app was running and if not, start it. In my situation, the app I wanted to check and launch was not something I wrote nor was it UWP so my solution may not work for you as the capabilities to do so are restricted.
First adding restricted capabilities to the package.appxmanifest (code).
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap"
Then adding "appDiagnostics" capability to the app.
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="appDiagnostics" />
</Capabilities>
Now you have the ability to request permission to access running processes and check.
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.System;
using Windows.System.Diagnostics;
class ProcessChecker
{
public static async Task<bool> CheckForRunningProcess(string processName)
{
//Requests permission for app.
await AppDiagnosticInfo.RequestAccessAsync();
//Gets the running processes.
var processes = ProcessDiagnosticInfo.GetForProcesses();
//Returns result of searching for process name.
return processes.Any(processDiagnosticInfo => processDiagnosticInfo.ExecutableFileName.Contains(processName));
}
}
Launching a non UWP app/process is a bit dirty but possible.
First, a simple console (non uwp) app is needed. Replace the directoryPath in the code below with your applicable directory path.
using System;
using System.Diagnostics;
namespace Launcher
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length != 3) return;
string executable = args[2];
string directoryPath = "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\";
Process.Start(directoryPath + executable);
}
catch (Exception e)
{
Console.ReadLine();
}
}
}
}
Build the console app and place the Launcher.exe in your UWP app asset folder.
Now you need to add the capability to run the Launcher and to do so, add "runFullTrust" capability to the UWP app.
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="runFullTrust" />
<rescap:Capability Name="appDiagnostics" />
</Capabilities>
For desktop, you also need to add desktop capabilities and extension to the package.appxmanifest (code).
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
IgnorableNamespaces="uap mp rescap"
Then further below in the package.appxManifest and inside .
<Extensions>
<desktop:Extension Category="windows.fullTrustProcess" Executable="Assets\Launcher.exe" >
<desktop:FullTrustProcess>
<desktop:ParameterGroup GroupId="SomeGroup1" Parameters="ProcessName1.exe"/>
<desktop:ParameterGroup GroupId="SomeGroup2" Parameters="ProcessName2.exe"/>
</desktop:FullTrustProcess>
</desktop:Extension>
</Extensions>
Finally, add the "Windows Desktop Extensions for the UWP" references needed for your app versions.
Now you can call your Launcher and start the necessary process.
public static async void LaunchProcess(int groupId)
{
switch (groupId)
{
case 1:
await FullTrustProcessLauncher.LaunchFullTrustProcessForAppAsync("SomeGroup1");
break;
case 2:
await FullTrustProcessLauncher.LaunchFullTrustProcessForAppAsync("SomeGroup2");
break;
}
}
Combining the above, one possibility may be...
public enum ProcessResult
{
ProcessAlreadyRunning,
FailedToLaunch,
SuccessfulLaunch
}
public static async Task<ProcessResult> CheckLaunchCheckProcess1()
{
if (await CheckForRunningProcess("ProcessName1.exe")) return ProcessResult.ProcessAlreadyRunning;
LaunchProcess(1);
return await CheckForRunningProcess("ProcessName1.exe") ? ProcessResult.SuccessfulLaunch : ProcessResult.FailedToLaunch;
}
This is just an example of how to accomplish launching non uwp apps within a single uwp app. For a windows store app submissions, restricted capabilities require approval and can delay or halt deployment if denied.
If the both the calling app and launching app are uwp and written by you, the appropriate solution may be using URI for app to app communication, MS doc link Launch an app with a URI

SystemNavigationManagerPreview does not exist in current Context

So I wanted to try to disable the "X" (Close) Button in my UWP app. For testing I created a new UWP app. I then went to my Visual Studio projects:
\Visual Studio 2015\Projects\closerequesthandled\closerequesthandled
and opened Packageand edited following things:
First I added xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" and rescap
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap">
Then I added <rescap:Capability Name="confirmAppClose"/>
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="confirmAppClose"/>
</Capabilities>
I get this warning:
But I read that this warning does nothing besides warning you so it still should work out.
Then I added this as a test to the MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += this.OnCloseRequest;
}
private void OnCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
{
var x = 0;
}
}
But SystemNavigationManagerPreview and SystemNavigationCloseRequestedPreviewEventArgs gets a red underline:
The name `SystemNavigationManagerPreview` does not exist in the current context
and
The type or nmespace name `SystemNavigationCloseRequestedPreviewEventArgs` could not be found (are you missing a using directive or an assembly reference?)
How can I make this work?
This seems to be the same question on MSDN. From your folder we noticed that you are using Visual Studio 2015, and Visual Studio 2015 only support to 14393 SDK. As Stefan and my MSDN post mentioned, you have to set your min target version to 15063 first, then you can use the Windows.UI.Core.Preview API. So Visual Studio 2017 is required here for this specific feature.

VSIX extension for VS2012 not running when debugging

I created a new VSIX extension project in Visual Studio 2012, and wrote a MEF classifier (as a test) that should simply highlight all text in a .mylang file. Here are the relevant parts of my .NET 4.5 code:
internal static class MyLangLanguage
{
public const string ContentType = "mylang";
public const string FileExtension = ".mylang";
[Export(typeof(ClassificationTypeDefinition))]
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
[Export]
[FileExtension(FileExtension)]
[ContentType(ContentType)]
internal static FileExtensionToContentTypeDefinition MyLangSyntaxFileExtensionDefinition = null;
}
[Export(typeof(IClassifierProvider))]
[ContentType(MyLangLanguage.ContentType)]
[Name("MyLangSyntaxProvider")]
internal sealed class MyLangSyntaxProvider : IClassifierProvider
{
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry = null;
public IClassifier GetClassifier(ITextBuffer buffer)
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new MyLangSyntax(ClassificationRegistry, buffer));
}
}
internal sealed class MyLangSyntax : IClassifier { }
Here is the full code.
These are the relevant parts from my source.extension.vsixmanifest file. Based on suggestions and similar files I found across the web, I added the dependency on MPF and the two assets.
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<!-- ... -->
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="4.5" />
<Dependency d:Source="Installed" Id="Microsoft.VisualStudio.MPF.11.0" DisplayName="Visual Studio MPF 11.0" Version="[11.0,12.0)" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
</Assets>
</PackageManifest>
I also tried a version 1.0 manifest:
<?xml version="1.0" encoding="utf-8"?>
<Vsix Version="1.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2010">
<!-- ... -->
<References />
<Content>
<MefComponent>|%CurrentProject%|</MefComponent>
</Content>
</Vsix>
When I run it, it starts an experimental instance of Visual Studio 2012, and the Extensions and Updates window shows that my extension is active. However, it does not do anything when I load or create a .mylang file. Any exceptions I throw (as a test) from my extension are never thrown. Breakpoints are never hit, and get an exclamation mark with the following warning:
The breakpoint will not currently be hit. No symbols have been loaded for this document.
It feels as if my extension is never really loaded at all. My problem is similar to this problem and this problem, but I'm using Visual Studio 2012 which uses a new VSIX manifest format.
What I know:
I can find my DLL and VSIX file in the %localappdata%\Microsoft\VisualStudio\11.0Exp\Extensions\MyLang\VSIXProject1\1.0 folder, so I know they are copied.
Their timestamp corresponds to when I last built the project, so I know they are up-to-date.
Project Properties > Debug > Start external program: is already automatically set to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe, and the Command line arguments were automatically set to /rootsuffix Exp.
The Visual Studio log (created with the /log option) has two entries related to my extension: Successfully loaded extension... and Extension is enabled....
My DLL does not appear on the Modules tab (list of all loaded DLLs) of the debugging Visual Studio, while some (not all) other extensions do appear.
It doesn't get loaded in Visual Studio 2012 or 2010 both on my laptop and my desktop PC.
What I've tried:
Set <IncludeAssemblyInVSIXContainer> to true in the .csproj file, per this suggestion, but it did not make any difference.
I can't add the line <MefComponent>|%CurrentProject%|</MefComponent> to the source.extension.vsixmanifest file as it uses a different format (2.0) than VSIX projects for previous versions of Visual Studio (1.0).
This suggestion (setting IncludeAssemblyInVSIXContainer and friends in my .csproj to true) but it does not make a difference. And my breakpoints are still showing the warning and not being hit.
Reset the VS Experimental instance using the Reset the Visual Studio 2012 Experimental Instance shortcut in the Start Menu, as per this suggestion. It didn't make a difference.
How can I at the very least be sure my VSIX MEF extension is loaded and works? And if possible, how can I make by breakpoint work and debug it?
Edit: The problem is you've improperly exported your ContentTypeDefinition as a ClassificationTypeDefinition. You should use the following instead:
[Export] // <-- don't specify the type here
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
Here's my two guesses right now:
Try removing the following line from your vsixmanifest. I assume you do not have a class in your project that extends Package, in which case Visual Studio might be refusing to load your package due to the following Asset line (your extension does not actually provide this asset).
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
If that fails, try replacing your current source.extension.vsixmanifest with one written to the old schema (version 1.0). I know this form still works in Visual Studio 2012 because all ~20 extensions I work on (with >10 public releases) use the old schema.
280Z28 solved the problem! For completeness, this is the full tried and tested code that will create a super simple VSIX Visual Studio MEF extension that colors all text in a .mylang file blue (or whatever the current keyword color is).
How to create a simple coloring MEF VSIX extension
Make sure you have the Visual Studio SDK installed. (VS2010 SP1 SDK, VS2012 SDK)
Create a new VSIX Project(From the template under Installed → Templates → Visual C# → Extensibility.)
Enter something in the Author field of the VSIX manifest editor, then save and close it.
Add references to the following libraries,version 10.0.0.0 for VS2010, or 11.0.0.0 for VS2012:
Microsoft.VisualStudio.CoreUtility.dll
Microsoft.VisualStudio.Language.StandardClassification.dll
Microsoft.VisualStudio.Text.Data.dll
Microsoft.VisualStudio.Text.Logic.dll
Microsoft.VisualStudio.Text.UI.dll
Microsoft.VisualStudio.Text.UI.Wpf.dll
Add a reference to the following library:
System.ComponentModel.Composition.dll version 4.0.0.0
Create and add a new code file MyLang.cs, and copy-and-paste the code below in it.
Edit source.extension.vsixmanifest as XML.
For Visual Studio 2010, add the following XML just before the closing tag </Vsix>, and save:
<Content>
<MefComponent>|%CurrentProject%|</MefComponent>
</Content>
(If there is already an empty <Content/>, remove it.)
For Visual Stuio 2012, add the following XML just before the closing tag </PackageManifest>, and save:
<Assets>
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
</Assets>
(If there is already an empty <Assets/>, remove it.)
Only for Visual Studio 2010:
Unload the VSIX project (right-click the project → Unload project).
Edit the .csproj project file (right-click the project → Edit MyProject.csproj).
Change the value at <IncludeAssemblyInVSIXContainer> to true.
Save and close the file.
Reload the VSIX project (right-click the project → Reload project).
Now build and run it. When you load a .mylang file, all text should be colored blue (or whatever the default keyword color is).
MyLang.cs
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace VSIXProject1
{
internal static class MyLangLanguage
{
public const string ContentType = "mylang";
public const string FileExtension = ".mylang";
[Export]
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
[Export]
[FileExtension(FileExtension)]
[ContentType(ContentType)]
internal static FileExtensionToContentTypeDefinition MyLangSyntaxFileExtensionDefinition = null;
}
[Export(typeof(IClassifierProvider))]
[ContentType(MyLangLanguage.ContentType)]
[Name("MyLangSyntaxProvider")]
internal sealed class MyLangSyntaxProvider : IClassifierProvider
{
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry = null;
public IClassifier GetClassifier(ITextBuffer buffer)
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new MyLangSyntax(ClassificationRegistry, buffer));
}
}
internal sealed class MyLangSyntax : IClassifier
{
private ITextBuffer buffer;
private IClassificationType identifierType;
private IClassificationType keywordType;
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
internal MyLangSyntax(IClassificationTypeRegistryService registry, ITextBuffer buffer)
{
this.identifierType = registry.GetClassificationType(PredefinedClassificationTypeNames.Identifier);
this.keywordType = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword);
this.buffer = buffer;
this.buffer.Changed += OnBufferChanged;
}
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan snapshotSpan)
{
var classifications = new List<ClassificationSpan>();
string text = snapshotSpan.GetText();
var span = new SnapshotSpan(snapshotSpan.Snapshot, snapshotSpan.Start.Position, text.Length);
classifications.Add(new ClassificationSpan(span, keywordType));
return classifications;
}
private void OnBufferChanged(object sender, TextContentChangedEventArgs e)
{
foreach (var change in e.Changes)
ClassificationChanged(this, new ClassificationChangedEventArgs(new SnapshotSpan(e.After, change.NewSpan)));
}
}
}
Set <IncludeAssemblyInVSIXContainer> to true in the .csproj file, per
this suggestion.
I had exactly the same problem and this solved it. Do a full rebuild.

How to register a service with Mono.ZeroConf?

I'm trying to test the ZeroConf sample at http://www.mono-project.com/Mono.Zeroconf.
I'm running OpenSuse 11 and Mono 2.2.
My server code is:
using System;
using Mono.Zeroconf;
namespace zeroconftestserver
{
class MainClass
{
public static void Main(string[] args)
{
RegisterService service = new RegisterService ();
service.Name = "test server";
service.RegType = "_daap._tcp";
service.ReplyDomain = "local.";
service.Port = 6060;
// TxtRecords are optional
TxtRecord txt_record = new TxtRecord ();
txt_record.Add ("Password", "false");
service.TxtRecord = txt_record;
service.Register();
Console.WriteLine("Service registered!");
Console.ReadLine();
}
}
}
But I can't find my registered service with the sample client browser code nor with mzclient.
Thanks!
I've also tried to use the binaries provided at the Mono.Zeroconf project page and building the libs from source for use on Windows and was unable to publish a service that was findable by other clients. I tried both the example code on the site and the MZClient provided.
After a little more digging I found a project that used to the Mono.Zeroconf libs. By using the binaries checked into the Growl for Windows project at Google Code (which appear to be the latest version 0.9.0) I was able to successfully publish a findable service with both the sample code and MZClient.
So an apparent work around would be to grab the binaries (Mono.Zeroconf and Mono.Zeroconf.Providers.Bonjour) from that project and use those instead of the ones provided by the project.
The binaries at mono-project.com/Mono.Zeroconf are out of date and still contain code that causes this problem. The most recent code (with all the fixes) is at this link
but require you to compile the code yourself.
I wasn't able to get a service published either. I looked through the code and there is a bug in Service.cs, the UPort setter:
this.port = (ushort) IPAddress.HostToNetworkOrder((int) value); //overflow, port is always 0
It should be
this.port = (ushort) IPAddress.HostToNetworkOrder((short) value);
Recompiling after updating the source from the following link solved the issue
https://github.com/mono/Mono.Zeroconf/tree/master/src
He is using mzclient to test his Mono.Zeroconf code above. The entire point of Mono.Zeroconf is to provide cross platform, multiple mDNS provider support (Avahi and Bonjour).
There appears to be an issue with the EntryGroup DBus Avahi API and I am looking into it in Mono.Zeroconf. I'll post a solution here, as well as make a new Mono.Zeroconf release (I am the maintainer of the project) when I figure out the issue.

Categories