Facing Issue Creating an Addon, Visual Studio, G1ANT - add-on

I tried making an addon using the existing selenium addon codes and resources.
I was able to make an addon with just one command (for testing) to open Flipkart.
I used the selenium.open command code and edited it slightly by entering default value of URL argument as (flipkart.com).
I was successfully able to build my solution (I made sure to add all the nuget packages and other necessities)
Now when I try to load the addon in my studio, I'm getting an error mentioning that it expected command postfix for the FlipkartOpen command.
Can anyone please let me know the reason for this error and maybe a possible solution to fix it?
Here's the error image: G1ANT Studio Error for New Addon.
And here's my code sample:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using G1ANT.Language;
using OpenQA.Selenium;
namespace G1ANT.Addon.Flipkart.Commands
{
[Command(Name = "Flipkart.Open", Tooltip = "This command opens flipkart in a web browser provided in the Argument.")]
public class FlipkartOpen : Command
{
public FlipkartOpen(AbstractScripter scripter) : base(scripter)
{
}
public class Arguments : CommandArguments
{
// Enter all arguments you need
[Argument(Required = true, Tooltip = "Name of a web browser")]
public TextStructure Type { get; set; } = new TextStructure(string.Empty);
[Argument(DefaultVariable ="Url", Tooltip = "Website Url")]
public TextStructure Url { get; set; } = new TextStructure("www.flipkart.com");
[Argument(DefaultVariable = "timeoutselenium", Tooltip = "Specifies time in milliseconds for G1ANT.Robot to wait for the command to be executed")]
public override TimeSpanStructure Timeout { get; set; } = new TimeSpanStructure(SeleniumSettings.SeleniumTimeout);
[Argument(Tooltip = "By default, waits until the webpage fully loads")]
public BooleanStructure NoWait { get; set; } = new BooleanStructure(false);
[Argument(Tooltip = "Result variable")]
public VariableStructure Result { get; set; } = new VariableStructure("result");
}
// Implement this method
public void Execute(Arguments arguments)
{
try
{
SeleniumWrapper wrapper = SeleniumManager.CreateWrapper(
arguments.Type.Value,
arguments.Url?.Value,
arguments.Timeout.Value,
arguments.NoWait.Value,
Scripter.Log,
Scripter.Settings.UserDocsAddonFolder.FullName);
int wrapperId = wrapper.Id;
OnScriptEnd = () =>
{
SeleniumManager.DisposeAllOpenedDrivers();
SeleniumManager.RemoveWrapper(wrapperId);
SeleniumManager.CleanUp();
};
Scripter.Variables.SetVariableValue(arguments.Result.Value, new IntegerStructure(wrapper.Id));
}
catch (DriverServiceNotFoundException ex)
{
throw new ApplicationException("Driver not found", ex);
}
catch (Exception ex)
{
throw new ApplicationException($"Error occured while opening new selenium instance. Url '{arguments.Url.Value}'. Message: {ex.Message}", ex);
}
}
}
}

To remove this error, when you add new class, write Command.cs at the end while adding. Try FlipkartopenCommand.cs
This should remove your error.

Related

Visual studio how to add custom tool/code generator configuration options

I wanted to easily turn some json schema files into classes. So googling I found NJsonSchema and I implemented this in a visual studio custom tool so I can set this on relevant json files and get my classes out. This al works and I pasted the code below. This code comes from this very answer. Though it does need a little updating for VS2022.
I find that documentation on how to do this is rather rare and the thing I am missing is how I can add something like configuration options for the custom tool.
Take for example the line "ClassStyle = CSharpClassStyle.Record," that is something one might want configurable for the user. But I cannot find anything on how to do that. Anyone have a good pointer/answer on this?
Preferably a way to add take the config from some custom properties in the file its properties that are available when the custom tool is configured on a project file.
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.Text;
using NJsonSchema.CodeGeneration.CSharp;
using NJsonSchema;
namespace ClassGeneratorForJsonSchema
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("GenerateClassesFromJsonSchema", "Use NJsonSchema to generate code from a json schema.", "1.0")]
[Guid("202E7E8B-557E-46CB-8A1D-3024AD68F44A")]
[ComVisible(true)]
[ProvideObject(typeof(ClassGeneratorForJsonSchema))]
[CodeGeneratorRegistration(typeof(ClassGeneratorForJsonSchema), "ClassGeneratorForJsonSchema", "{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}", GeneratesDesignTimeSource = true)]
public sealed class ClassGeneratorForJsonSchema : IVsSingleFileGenerator
{
#region IVsSingleFileGenerator Members
public int DefaultExtension(out string pbstrDefaultExtension)
{
pbstrDefaultExtension = ".cs";
return pbstrDefaultExtension.Length;
}
public int Generate(string wszInputFilePath, string bstrInputFileContents,
string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
{
try
{
var schema = JsonSchema.FromJsonAsync(bstrInputFileContents).Result;
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()
{
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
ClassStyle = CSharpClassStyle.Record,
Namespace = wszDefaultNamespace
});
byte[] bytes = Encoding.UTF8.GetBytes(generator.GenerateFile());
int length = bytes.Length;
rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);
pcbOutput = (uint)length;
}
catch (Exception ex)
{
pcbOutput = 0;
}
return VSConstants.S_OK;
}
#endregion
}
}

Navigation does not exist in current context Xamarin Comunity Toolkit Extensions

I want to open a pop up window using xamarin comunity toolkit extensions but when i try to call
Navigation it says that it does not exist even if i have included xct.extensions. There is NavigationExtensions but I don't know what I'm supposed to pass as first parameter and it says that my FilterPopup is of incorect type
using Xamarin.CommunityToolkit.Extensions;
namespace Appointments.ViewModels
{
public class WallViewModel
{
public ObservableCollection<Stylist> Stylists { get; set; }
public AsyncCommand OpenModalFiltersComand;
public WallViewModel()
{
OpenModalFiltersComand = new AsyncCommand(OpenModalFilters);
}
async Task OpenModalFilters()
{
NavigationExtensions.ShowPopup(AppShell, FilterPopup);
Navigation // error
}
}
}
My FilterPopup
namespace Appointments.Popups
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class FilterPopup : Popup
{
public FilterPopup()
{
InitializeComponent();
}
}
}
EDIT---------
I'm using shell navigation
ShowPopup takes an INavigation and an instance of a PopupBase. Navigation is a property of Page types, so your VM does not have a reference to it.
var nav = App.Current.MainPage.Navigation;
var filter = new FilterPopup();
NavigationExtensions.ShowPopup(nav, filter);

Scandit Barcode Scanner Shows Blank camera on scanning

I am trying to implement scandit barcode scanner in my application.i downloaded its sample demo and its works fine.
same code i tried to implement in my app.but it shows black screen on scanning .
I gave camera access also. cant find any thing missing.
Please help if someone also faced same issue. any suggestion most appreciated.
thanks in advance
This is my code
using FormBot.ViewModels.Abstract;
using Scandit.BarcodePicker.Unified;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace FormBot.ViewModels
{
public class SerialNumberViewModel: BaseViewModelDemo
{
private string _recognizedCode;
public ICommand StartScanningCommand => new Command(async () => await StartScanning());
public string RecognizedCode
{
get
{
return (_recognizedCode == null) ? "" : "Code scanned: " + _recognizedCode;
}
set
{
_recognizedCode = value;
}
}
public SerialNumberViewModel()
{
ScanditService.ScanditLicense.AppKey = "Key";
ScanditService.BarcodePicker.DidScan += BarcodePickerOnDidScan;
}
private async void BarcodePickerOnDidScan(ScanSession session)
{
RecognizedCode = session.NewlyRecognizedCodes.LastOrDefault()?.Data;
await ScanditService.BarcodePicker.StopScanningAsync();
}
private async Task StartScanning()
{
await ScanditService.BarcodePicker.StartScanningAsync(false);
}
}
}
in app.xaml.cs
private static string appKey = "key";
ScanditService.ScanditLicense.AppKey = appKey;
set android:hardwareAccelerated="true" in AndroidManifest.xml file worked for me.

Using WebAPI in LINQPad?

When I tried to use the Selfhosted WebAPI in LINQPad, I just kept getting the same error that a controller for the class didn't exist.
Do I have to create separate assemblies for the WebAPI (Controllers/Classes) and then reference them in my query?
Here's the code I'm using
#region namespaces
using AttributeRouting;
using AttributeRouting.Web.Http;
using AttributeRouting.Web.Http.SelfHost;
using System.Web.Http.SelfHost;
using System.Web.Http.Routing;
using System.Web.Http;
#endregion
public void Main()
{
var config = new HttpSelfHostConfiguration("http://192.168.0.196:8181/");
config.Routes.MapHttpAttributeRoutes(cfg =>
{
cfg.AddRoutesFromAssembly(Assembly.GetExecutingAssembly());
});
config.Routes.Cast<HttpRoute>().Dump();
AllObjects.Add(new UserQuery.PlayerObject { Type = 1, BaseAddress = "Hej" });
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
using(HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Server open, press enter to quit");
Console.ReadLine();
server.CloseAsync();
}
}
public static List<PlayerObject> AllObjects = new List<PlayerObject>();
public class PlayerObject
{
public uint Type { get; set; }
public string BaseAddress { get; set; }
}
[RoutePrefix("players")]
public class PlayerObjectController : System.Web.Http.ApiController
{
[GET("allPlayers")]
public IEnumerable<PlayerObject> GetAllPlayerObjects()
{
var players = (from p in AllObjects
where p.Type == 1
select p);
return players.ToList();
}
}
This code works fine when in a separate Console Project in VS2012.
I started using AttributeRouting via NuGET when I didn't get the "normal" WebAPI-routing to work.
The error I got in the browser was: No HTTP resource was found that matches the request URI 'http://192.168.0.196:8181/players/allPlayers'.
Additional error: No type was found that matches the controller named 'PlayerObject'
Web API by default will ignore controllers that are not public, and LinqPad classes are nested public, we had similar problem in scriptcs
You have to add a custom controller resolver, which will bypass that limitation, and allow you to discover controller types from the executing assembly manually.
This was actually fixed already (now Web API controllers only need to be Visible not public), but that happened in September and the latest stable version of self host is from August.
So, add this:
public class ControllerResolver: DefaultHttpControllerTypeResolver {
public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) {
var types = Assembly.GetExecutingAssembly().GetExportedTypes();
return types.Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList();
}
}
And then register against your configuration, and you're done:
var conf = new HttpSelfHostConfiguration(new Uri(address));
conf.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver());
Here is a full working example, I just tested against LinqPad. Note that you have to be running LinqPad as admin, otherwise you won't be able to listen at a port.
public class TestController: System.Web.Http.ApiController {
public string Get() {
return "Hello world!";
}
}
public class ControllerResolver: DefaultHttpControllerTypeResolver {
public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) {
var types = Assembly.GetExecutingAssembly().GetExportedTypes();
return types.Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList();
}
}
async Task Main() {
var address = "http://localhost:8080";
var conf = new HttpSelfHostConfiguration(new Uri(address));
conf.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver());
conf.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var server = new HttpSelfHostServer(conf);
await server.OpenAsync();
// keep the query in the 'Running' state
Util.KeepRunning();
Util.Cleanup += async delegate {
// shut down the server when the query's execution is canceled
// (for example, the Cancel button is clicked)
await server.CloseAsync();
};
}

The specified table does not exist on sql ce

I get an exception
The specified table does not exist [Limits]
while I'm trying saving new item
(App.Current as App).context.Limits.InsertOnSubmit(new Limit() { Date = DateTime.Now, Value = inputLimit });//this works
(App.Current as App).context.SubmitChanges();//here I get exception
Also I get an error on this line:
var currentLimit = (App.Current as App).context.Limits.Where(l => l.Date.Date == DateTime.Now.Date).FirstOrDefault();
Here is a "model"
public class CalCounterContext:DataContext
{
public CalCounterContext(string connstring):base(connstring)
{
}
public Table<Limit> Limits;
public Table<Meal> Meals;
}
[Table]
public class Limit
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "Int NOT NULL IDENTITY", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id { get; set; }
[Column]
public DateTime Date { get; set; }
[Column]
public int Value { get; set; }
}
Sometimes it works, sometimes, doesn't. What could be a reson of my problem?
This normally happens when you add a table in a later version of the database then what is being used. When you create your database context, check to see if it is up to date, and if not, update the database using the DatabaseSchemaUpdater class as described here. If it is just while you are creating the app, uninstall and re-install the app.
Also, I ran into a strange issue where intermittently I would get this error even once the app was in production without any reasoning. Often is occured when I would launch the app and then hit the home or back button to end it quickly. I ended up re-implementing the GetTable<> function used to instantiate my ITable variable in a base database class so that it would do a hard check to see if the table actually existed:
public Table<TEntity> VerifyTable<TEntity>() where TEntity : class
{
var table = GetTable<TEntity>();
try
{
// can call any function against the table to verify it exists
table.Any();
}
catch (DbException exception)
{
if (exception.Message.StartsWith("The specified table does not exist."))
{
var databaseSchemaUpdater = this.CreateDatabaseSchemaUpdater();
databaseSchemaUpdater.AddTable<TEntity>();
databaseSchemaUpdater.Execute();
}
else
{
throw;
}
}
return table;
}
I had the same intermittent error you had. Try removing the database from the device and installing the app again. I found my issue was being caused because I was making changes to the model and when I re-ran the app, I would get this error.

Resources