Can't get access to the Events in Visual Studio Community Toolkit - visual-studio-extensions

I'm trying to migrate my old Visual Studio extension to the new 2022 Studio. Found some fancy solution named 'Community Visual Studio Toolkit', but got some issues. When I use the ProvideAutoLoad attribute for loading my extension when a user opens some solution, I can't get access to the WindowEvents which I need to sign my event handlers. This is the error on debugging: https://snipboard.io/yUXIed.jpg
So this is the code I use, and here I have the error:
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MyPackage : ToolkitPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.RegisterCommandsAsync();
VS.Events.WindowEvents.ActiveFrameChanged += WindowEvents_ActiveFrameChanged;
}
}
And the thing is my old implementation works with this code:
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MyPackage : ToolkitPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.RegisterCommandsAsync();
// Getting `DTE2 dte` trough standard way...
dte.Events.WindowEvents.WindowActivated += WindowEvents_WindowActivated;
}
}
But I don't want to use old kinds of code in the new extension version, so, how to fix this issue in first example of implementation?

Well, I'm not sure about the "perfection" of this solution, but with this line of code added before access to the events - it works.
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
Seems like you have to be in main thread to access these events.

Related

Vimeo Networking Library Crash for Android 10 platform (api29)

I implemented vimeo networking using vimeo networking library(https://github.com/vimeo/vimeo-networking-java), exoplayer and explained in this post https://stackoverflow.com/a/65737556/8814924
Now the problem is when I was checking with API 30 it was getting error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emergingit.emergingstudy/com.emergingit.emergingstudy.activities.course.ExoPlayerActivity}: java.lang.IllegalStateException: Unable to extract the trust manager on Android10Platform, sslSocketFactory is class com.android.org.conscrypt.OpenSSLSocketFactoryImpl
Caused by: java.lang.IllegalStateException: Unable to extract the trust manager on Android10Platform, sslSocketFactory is class com.android.org.conscrypt.OpenSSLSocketFactoryImpl
which indicates the error on
VimeoClient.initialize(configuration);
which issue is dicscussed here : https://github.com/square/okhttp/issues/5878 , issue discussion :
I assume you are calling the deprecated form of sslSocketFactory, which is broken on newer Android versions. https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/OkHttpClient.kt#L719
/**
* Sets the socket factory used to secure HTTPS connections. If unset, the system default will
* be used.
*
* #deprecated [SSLSocketFactory] does not expose its [X509TrustManager], which is a field that
* OkHttp needs to build a clean certificate chain. This method instead must use reflection
* to extract the trust manager. Applications should prefer to call
* `sslSocketFactory(SSLSocketFactory, X509TrustManager)`, which avoids such reflection.
*/
#Deprecated(
message = "Use the sslSocketFactory overload that accepts a X509TrustManager.",
level = DeprecationLevel.ERROR
)
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory) = apply {
if (sslSocketFactory != this.sslSocketFactoryOrNull) {
this.routeDatabase = null
}
this.sslSocketFactoryOrNull = sslSocketFactory
this.certificateChainCleaner = Platform.get().buildCertificateChainCleaner(sslSocketFactory)
}
is there any solution possible with using the current version "1.1.3" of networking library for this or I have to wait till the library update ?
I primarily Solved the problem for Vimeo video streaming on the Android 10 platform using the Vimeo-Networking library (v1.1.3).
as the main problem is in the OkHttpClient build method
builder.sslSocketFactory(sSLSocketFactory);
//RetrofitClientBuilder.java#186
where with 1 parameter version is depricated and I needed to pass X509TTrustManager as 2nd parameter like this :
builder.sslSocketFactory(sSLSocketFactory, new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
});
So it solved my problem till this update comes in the stable version of this library. How I implemented this is described below :
Error was showing on VimeoClient.initialize(accessToken); line and I searched about the error and find out that it is caused because of this OkHttpClient method deprecation (with 1 parameter).
So I went into VimeoClient.java and saw in its constructor private Retrofit createRetrofit() was called and inside it private OkHttpClient createOkHttpClient() was called. and there public class RetrofitClientBuilder object was created and it's problemetic method was public OkHttpClient build() in which : if (sSLSocketFactory != null) { builder.sslSocketFactory(sSLSocketFactory); }
this deprecated method was called.
So I just had to create 2 new java file with name VimeoClientUpdated.java and RetrofitClientBuilderUpdated.java which is just a renamed copy of VimeoClient.java and RetrofitClientBuilder.java and now my RetrofitClientBuilderUpdated.java has no deprecated method rather the correct and VimeoClientUpdated.java is calling RetrofitClientBuilderUpdated.java
(I couldn't extend because of the final class and couldn't even wrap the class as to the gateway to that solution, I had to face the private method which wasn't possible to alter in wrapper class)
and finally just instead of calling VimeoClient.initialize(accessToken) I am calling my newly created VimeoClientUpdated(accessToken) which won't crash while playing Vimeo video on Android 10.
Suggest me if there is a better way of serving my purpose (solving deprecated library method calling from the android activity).
Cheers..!!

Xamarin Amazon IAP error using D8+R8 with Proguard in Release Failing but working Debug

I am using AmazonIapV2Android.dll provided by Amazon team for the Xamarin.Android project. I have implemented it last year and have been using successfully with Dx+proguard with using proguard rules as below. Those lines are also suggested by Amazon documentation. see the link
-dontwarn com.amazon.**
-keep class com.amazon.** {*;}
-keepattributes *Annotation*
Recently I have changed my xamarin.android project using d8+r8 using the same proguard file. Everything, google iap implementation also fine but Amazon IAP started throwing exception.
Jsonable.CheckForErrors
(System.Collections.Generic.Dictionary`2[TKey,TValue] jsonMap)
com.amazon.device.iap.cpt.AmazonException: java.lang.RuntimeException:
Missing type parameter.
at com.amazon.device.iap.cpt.RequestOutput.CreateFromJson
(System.String jsonMessage) [0x0002d] in
<26520843ea114e5a91256077e0412906>:0 \n at
com.amazon.device.iap.cpt.AmazonIapV2Impl+AmazonIapV2Base.GetProductData
(com.amazon.device.iap.cpt.SkusInput skusInput) [0x00013] in
I am using also linker as User and sdk assemblies, this is triggering obfuscation obviously and some methods are removed by the linker because using Sdk assemblies only or No Linking, everything works fine.
I have added the AmazonIapV2Android as linker to skip but it didnt help.
When I check the code implementation of the RequestOutput.CreateFromJson function implementation, it looks like as below.
using com.amazon.device.iap.cpt.json;
namespace com.amazon.device.iap.cpt
{
public sealed class RequestOutput : Jsonable
{
public string RequestId{get;set;}
public static RequestOutput CreateFromJson(string jsonMessage)
{
try
{
Dictionary<string, object> jsonMap = Json.Deserialize(jsonMessage) as Dictionary<string, object>;
Jsonable.CheckForErrors(jsonMap);
return CreateFromDictionary(jsonMap);
}
catch(System.ApplicationException ex)
{
throw new AmazonException("Error encountered while UnJsoning", ex);
}
}
and implementation for Jsonable in the dll looks as below
namespace com.amazon.device.iap.cpt
{
public abstract class Jsonable
{
public static Dictionary<string, object> unrollObjectIntoMap<T>(Dictionary<string, T> obj) where T:Jsonable
{
Dictionary<string, object> jsonableDict = new Dictionary<string, object>();
foreach (var entry in obj)
{
jsonableDict.Add (entry.Key, ((Jsonable)entry.Value).GetObjectDictionary());
}
return jsonableDict;
}
public static List<object> unrollObjectIntoList<T>(List<T> obj) where T:Jsonable
{
List<object> jsonableList = new List<object>();
foreach (Jsonable entry in obj)
{
jsonableList.Add(entry.GetObjectDictionary());
}
return jsonableList;
}
public abstract Dictionary<string, object> GetObjectDictionary();
public static void CheckForErrors(Dictionary<string, object> jsonMap)
{
object error;
if (jsonMap.TryGetValue("error", out error))
{
throw new AmazonException(error as string);
}
}
}
}
I have tried to use linker.xml with settings like below also but it didnt help either.
<assembly fullname="AmazonIapV2Android">
<namespace fullname="com.amazon.device.iap.cpt" />
<namespace fullname="com.amazon.device.iap.cpt.log" />
<namespace fullname="com.amazon.device.iap.cpt.json" />
</assembly>
I cannot figure out why should throw exception while i am defining keepclass for all methods and members under the namespace starting with com.amazon prefix.
Any idea what could be the reason here?
EDIT: just had several more tests and my initiale comment was slightly wrong. strange way app is working in debug with Linker set "SDK assemblies only" but in release it doesnt work even with "SDK assemblies only"
Obviously this is a known problem for using R8 and Amazon IAP. Typical amazon doesnt care and update their package. especially there is no update for Xamarin IAP since 2016.
Here are the links to problem
https://forums.developer.amazon.com/questions/205480/in-app-billing-not-working-since-android-studio-de.html
https://issuetracker.google.com/issues/134766810
Currently there are 3 workarounds,
disable r8. Bad is that no obfuscation, no optimization.
Use dx+proguard+multi dex instead of d8+r8. There is a problem here if you use androidx, androidx libraries dont work with dx+proguard, they work only with d8+r8, you need to go back to support libraries.
I am not sure but amazon website claims that it is claimed, it works with r8 but this is pobably for the android java library not for xamarin. Because as i cheked there is newer version to as jar. You can theoretically use Binding library to get a new dll and try but I read even for Android studio projects, this doesnt work. So i tried to create a binding library and it had many errors and api seems to be different than xamarin. It is a lot of effort for non-profitable app store.
here is the link to github issue on xamarin.android as well.

.NET Core Error 1053 the service did not respond to the start or control request in a timely fashion

I created a Windows Service starting from my .NET Core project following this
After this, I installed correctly it on my working machine and started it.
This is my service class:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace xxx
{
public class WindowsService
{
static void Main(string[] args)
{
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
using (var service = new Service())
{
ServiceBase.Run(service);
}
}
}
internal class Service : ServiceBase
{
public Service()
{
ServiceName = "...";
}
protected override void OnStart(string[] args)
{
try
{
base.OnStart(args);
Task.Run(() => xxxx);
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
}
}
protected override void OnStop()
{
base.OnStop();
}
protected override void OnPause()
{
base.OnPause();
}
}
}
So, I copied the file and installed it also on a server. Here, when I try to start it, I get:
After this, I start a lot of googling... for example, I tried the following steps :
Go to Start > Run > and type regedit
Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
With the control folder selected, right click in the pane on the right and - select new DWORD Value
Name the new DWORD: ServicesPipeTimeout
Right-click ServicesPipeTimeout, and then click Modify
Click Decimal, type '180000', and then click OK
Restart the computer
The weird point here is that the voice ServicesPipeTimeout didn't exist and I created it. Comparing the server with my working machine, there are also other value not present in the server. They are:
ServicesPipeTimeout
OsBootstatPath
Here the screenshot of regedit from the server:
Are these relevant?
I also tried to reinstall the service, recompile my files... how can I fix this problem? The error appears immediatly, it doesn't wait any timeout!
I had this problem when I switched my project to another location.
When I moved the project, I had copied the files in bin/debug folder too. The issue was resolved after I cleared the debug folder and created a new build.
See if this works!
It's a bit old question but someone may find this useful.
So I had the following code in Program.cs:
builder.SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json")
Changed it to:
builder.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).AddJsonFile("appsettings.json")
This seemed to fix the problem for me.
The problem with this error is that it is super generic.
Hopefully MS will give us some log in the future.
if you check the windows event viewer under applications it tells you what exactly is the exception that causes this error.
in my case the problem was i published the service in net6 and tried to run it on a pc with net7 installed. apparently it requires the exact major version that was used to publish the app.

JilOutputFormatter: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead

I have this formatter in my .NET Core 3.1 project (which I recently upgraded from 2.1):
public class JilOutputFormatter : TextOutputFormatter {
public JilOutputFormatter() =>
JilFormatterConfig.AddSupportedHeaders(SupportedMediaTypes, SupportedEncodings);
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) {
using (var writer = new StreamWriter(context.HttpContext.Response.Body)) {
JSON.Serialize(context.Object, writer, MyOptions);
writer.Flush();
}
return Task.FromResult(true);
}
}
And I'm adding it to pipeline with this snippet:
services.AddMvcCore(o => {
o.OutputFormatters.Insert(0, new JilOutputFormatter());
}).AddOthersBlahBlah();
It was working like a charm when the application was on 2.1. But now on 3.1 I'm getting this error:
An unhandled exception occurred while processing the request.
InvalidOperationException: Synchronous operations are disallowed. Call
WriteAsync or set AllowSynchronousIO to true instead.
I tried to async the write operation, but can't find the method on Jil. Do you have any idea please?
NOTE: I know there are some answers - like this one - that are saying how to AllowSynchronousIO. But I'm interested on how to async write in Jil.
You'll have to use the 3.0 alpha versions. Jil doesn't even include the word Task in the source code in the latest stable version, 2.17 (or Github search is having some issues).
Version 3.0 uses Pipelines directly. You can use the SerializeAsync(T, PipeWriter , Encoding, Options, CancellationToken). Maybe you can work with HttpContext.Response.BodyWriter. I haven't tested this though.
Eg :
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context,
Encoding selectedEncoding)
{
var data=context.Object;
var writer=contest.Response.BodyWriter;
await JSON.SerializeAsync(data,writer,selectedEncoding);
}
Errors can revolve around ReadAsync, WriteAsync, and FlushAsync with outputs similar to what is listed below.
Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.
Synchronous operations are disallowed. Call FlushAsync or set AllowSynchronousIO to true instead.
As a temporary workaround, you can set the value of AllowSynchronousIO in your ConfigureServices method found in your Startup class.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
// If using IIS:
services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
// other services
}
It isn’t a great workaround, but it will keep you moving forward. The better solution is to upgrade your libraries and perform all your actions asynchronously.
See the detailed post .NET Core 3.0 AllowSynchronousIO Workaround by Khalid Abuhakmeh
TLDR: As of Dotnet Core 5.0, the default web-server (Kestral) is designed to perform only Async Level work to be the most performant. Enable Sync within Kestral.
Rational: Due to to the majority of software being more IO Dependent than CPU Dependent, Async Programming allows for the system to perform other work, while waiting for the IO to complete (IE; Writing to Disk, Reading something from the network).
Place this within Startup.cs within the ConfigurationService function.
services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});

SignalR, Owin do not work after VS2015 move and package updates

I recently upgraded to VS2015 (did not remove VS2013 or 2010). NuGet did not instal properly. While the project ran it loaded with streaming messages re package updating. I just removed and reinstalled NuGet and updated all packages.
Now I have 2 problems that could be related.
1) 134 errors. Everything to do with SignalR and Owin is failing with messages like:
'type or namespace 'Hub' could not be found'.
Here is the key code. Other Usings were greyed out as unnecessary, and are removed.
using System;
namespace SignalR
{
[Microsoft.SignalR.HubName("SeekerHub")]
public class SeekerHub : Hub
{
private static Decimal number;
public static void SendMessage(string message)
{
//StartTimer();
//var callingClient = Context.ConnectionId;
var hubContext = GlobalHost.ConnectionManager.GetHubContext<SeekerHub>();
if (Decimal.TryParse(message, out number))
{
if (number == 0)
{ }
hubContext.Clients.All.receiveUpdate(message);
}
else
hubContext.Clients.All.receiveNotification(message);
}
}
}
2) 6 warnings that relate to updating. All relate to the same SignalR/Owin area but the message suggests that it is looking in the VS2013/localhost xyz/ file and not in the VS2015 file. Is there a way I can change the pointer when the package looks to update itself?
Thanks, in advance, for any help.

Resources