How to add custom Java script code to ElectronHostHook in electronnet asp.net mvc - electron.net

I am trying to add this code snippet to the wed apis demo project but I tried and failed and there isnt much documentation on how to do it.
var os = require("os");
var bytesAvailable = os.totalmem(); // returns number in bytes
// 1 mb = 1048576 bytes
console.log("Total memory available MB :" + (bytesAvailable/1048576) );
it needs to have a type script file and a javascript file according to the implamentation with the create excel.js demo but im not sure how to go about that process.

FYI everyone looking at this, the developer made a decent tutorial for this but lets just go with im the type of developer who is kinda dumb but competent.
So Basically your gonna want to create a type script file using the index.ts file as a template
once you have a type script file place your custom JS in the onHostRead() part of the script
build it
this will create the js file and make it look similar to the other example files.
create a controller for your custom js like hosthook.cs, this is called the mainfunction in the api demo
add front facing logic to your software. ....so still testing idk If i got it right just yet
This did not work in visual studio code , I used visual studio 2022
dont install the type script nuget package visual studio recommends , its not in the documentation, will break build.
sometimes the people capable are too busy to help so dive deep in the code and get good (talking to myself here)
ipController.cs
using ElectronNET.API;
using ElectronNET.API.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace ElectronNET_API_Demos.Controllers
{
public class IPController : Controller
{
public IActionResult Index()
{
if (HybridSupport.IsElectronActive)
{
Electron.IpcMain.On("start-hoosthook", async (args) =>
{
var mainWindow = Electron.WindowManager.BrowserWindows.First();
var options = new OpenDialogOptions
{
Properties = new OpenDialogProperty[]
{
OpenDialogProperty.openDirectory
}
};
var folderPath = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
var resultFromTypeScript = await Electron.HostHook.CallAsync<string>("get-ip-address", folderPath);
Electron.IpcMain.Send(mainWindow, "ip-address-found", resultFromTypeScript);
});
}
return View();
}
}
}
ipAddress.ts
// #ts-ignore
import * as Electron from "electron";
import { Connector } from "./connector";
import { IPAddress } from "./ipAddress";
export class HookService extends Connector {
constructor(socket: SocketIO.Socket, public app: Electron.App) {
super(socket, app);
}
onHostReady(): void {
// execute your own JavaScript Host logic here
var os = require("os");
var result = console.log(os.networkInterfaces);
return result;
}
}
ipAddress.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HookService = void 0;
const connector_1 = require("./connector");
class HookService extends connector_1.Connector {
constructor(socket, app) {
super(socket, app);
this.app = app;
}
onHostReady() {
// execute your own JavaScript Host logic here
var os = require("os");
var result = console.log(os.networkInterfaces);
return result;
}
}
exports.HookService = HookService;
//# sourceMappingURL=ipAddress.js.map

Related

How to create a pdf file which takes a trdp file and adds values from another JSON file

I am very new to Telerik reporting and i am trying to create a c# console app which takes a simple trdp template file, inserts values into it from a JSON file during runtime and convert it into a pdf as output. Any help is appreciated as i am learning it from scratch.Thanks.
enter image description here
You can try the following C# code for console application, it takes trdp file and exports it to multiple formats, including PDF. You will find the exported documents in your console application Debug folder (if you run it in Debug configuration).
using System;
using System.Collections;
using System.IO;
using System.Linq;
using Telerik.Reporting;
using Telerik.Reporting.Processing;
namespace ConsoleApp2101
{
class Program
{
static void Main(string[] args)
{
var reportSource = new UriReportSource();
var processor = new ReportProcessor();
var deviceInfo = new Hashtable();
reportSource.Uri = #"C:\Program Files (x86)\Progress\Telerik Reporting R1 2021\Report Designer\Examples\MyReport.trdp";
deviceInfo.Add("DocumentTitle", "SomeOptionalTitle");
string[] availableFormats = new string[] { "PDF", "CSV", "DOCX", "XLSX", "PPTX", "RTF" };
foreach (var format in availableFormats)
{
var result = processor.RenderReport(format, reportSource, deviceInfo);
if (result.HasErrors)
{
Console.WriteLine(string.Join(",", result.Errors.Select(s => s.Message)));
}
else
{
File.WriteAllBytes($"MyReport.{format.ToLower()}", result.DocumentBytes);
}
}
Console.WriteLine("Completed!");
Console.ReadKey();
}
}
}
Reference:
https://docs.telerik.com/reporting/programmatic-exporting-report

CosmosDB Project Layout

Asking for advice and references.
Using Visual Studio, I have an Azure Web Apps project in my solution. Now, I'm programming my Stored Procedures for CosmosDB. Using the CosmosDB Emulator, I can simply insert the Stored Procedure code directly into the browser editor window. All good and fine, and everything is working beautifully.
I also have a NodeJS project sitting alongside my Web App project. This allows me to store the Stored Procedures as files. The associated Console App is able to connect and modify the CosmosDB Emulator as expected.
My question is, using Visual Studio, what is the best way to lay out my project, so that it's not done on napkins and prayers?
I'm wondering how I should be structuring my project layout and assets to align with current "best practices". Is there any information, articles or posts that you guys/gals have found that talk about this specifically? Would I be running all of these procedures against CosmosDB manually, or are there automated procedures people have devised? I would like to be able to test these stored procedures first, against the Emulator, and with little-to-no source code change, update staging.
Thanks!
I have just recently asked myself the same question regarding stored procedure migrations.. I am currently running a basic Migrate Method that will get stored procedure content from a js file and replace/create the stored procedure, this runs on startup (in startup.cs)
The main gist of the code below, you will need to create the very basic internal methods (comments welcome):
using System;
using System.IO;
using System.Threading.Tasks;
using App.Data.Access;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.Documents;
namespace App.Data.StoredProcedures
{
public class Migrations : IMigrations
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IDocumentDbContext _documentDbContext;
public Migrations(IHostingEnvironment hostingEnvironment,IDocumentDbContext documentDbContext)
{
_hostingEnvironment = hostingEnvironment;
_documentDbContext = documentDbContext;
}
public async Task<bool> Migrate()
{
try
{
await AddUpdateBulkDeleteStoredProcedure();
return true;
}
catch (Exception exception)
{
throw new Exception("Error running CosmosDb stored procedure migrations,error" + exception.Message);
}
}
public string GetStoredProcedureScript(string filename)
{
var script = Path.Combine(_hostingEnvironment.WebRootPath, "App_Data", "CosmosDbStoredProcedures", filename);
return IO.File.ToString(script);
}
public async Task<bool> AddUpdateBulkDeleteStoredProcedure()
{
const string storedProcedureId = "BulkDeleteStoredProcedure";
var function = GetStoredProcedureScript($"{storedProcedureId}.js");
if (string.IsNullOrWhiteSpace(function))
{
throw new Exception($"Error running DocumentDb Stored procedure migrations, {storedProcedureId} content is empty");
}
try
{
await _documentDbContext.Client.ReplaceStoredProcedureAsync(_documentDbContext.GetStoredProcedureUri(storedProcedureId), new StoredProcedure {Id = storedProcedureId, Body = function});
return true;
}
catch
{
// ignore
}
await _documentDbContext.Client.CreateStoredProcedureAsync(_documentDbContext.DocumentCollectionUri, new StoredProcedure {Id = storedProcedureId, Body = function});
return true;
}
}
}

Xamarin Forms - calling rest service from viewmodel of pcl

I created a class that connected to the API to retrieve the required data using httpclient. That file was called in the code behind file of the view and worked perfectly. Than I decided to implement the MVVM approach. As a result, I moved the code that initialized the rest service class to the view-model.
After doing that, i stopped getting the data. To investigate, I stated the the debugging session with the breakpoint placed at the line where i initialize the rest service class. Than i executed that line. By doing that, I found out that a huge android mono exception is thrown and the debugging session if stopped. The app exits the debugging session.
This has happened for the first time since i stated developing my app in Xamarin Forms. I have no idea about why it is breaking like that. Your help will be greatly appreciated.
This is the code that was working properly.
In the view code behind file
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SubtaskPage : ContentPage
{
protected override void OnAppearing()
{
base.OnAppearing();
PopulateSubtaskData();
}
private async void PopulateSubtaskData()
{
lstSubtasks.IsRefreshing = true;
try
{
RestService rs = new RestService();
SResponse = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
if (SResponse.Status == 1)
{
lstSubtasks.ItemsSource = SResponse.Subtasks;
}
else
{
await DisplayAlert("Error", SResponse.Message, "Ok");
}
}
catch (Exception E)
{
Debug.WriteLine(#"GetSubtasksAsync -> ERROR {0}", E.Message);
}
lstSubtasks.IsRefreshing = false;
}
}
The rest service class is as follows
This class is in a separate folder named "Services". ip and url have been changed for security reason.
class RestService
{
HttpClient client;
public List<Ticket> Tickets { get; private set; }
string Server1 = "server ip";
string Server2 = "server ip";
public RestService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<SubtasksResponse> GetSubtasksAsync(int UserId)
{
SubtasksResponse SubtaskResponse = new SubtasksResponse();
string ApiUrl = "URL";
string Url = "";
HttpResponseMessage response;
if (CrossConnectivity.Current.IsConnected)
{
Url = await GetActiveServerAsync();
if (Url != "")
{
var uri = string.Format(Url + ApiUrl, UserId);
try
{
response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
SubtaskResponse.Subtasks = JsonConvert.DeserializeObject<List<Ticket>>(content);
SubtaskResponse.Status = 1;
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Attempt to fetch data from server was unsuccessful. Please try again";
}
}
catch (Exception E)
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Error occured while fetching data from the server. Please try again";
}
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Remote Server Not Responding! Please try again later";
}
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "No Network Connection Found! Please connect to a network and try again";
}
return SubtaskResponse;
}
}
}
This was working fine until I added the view model into the mix.
This is how I am calling the function in the view model.
async Task<SubtasksResponse> PopulateSubtaskList()
{
RestService rs = new RestService();
IsBusy = true;
_subtaskList = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
IsBusy = false;
return _subtaskList;
}
"RestService rs = new RestService();" this is the line where the code breaks.
Here is the image of the exception that occurs when the code breaks.
Hope you get the clear picture of the situation. Please let me know if additional information is required.
Thanks
Don't do this. If you want to call rest from a mvvm Xamarin Forms app I can advice Refit. All the difficult work is already done for you and abstracted away. With a few lines of code you are up and running.
BTW the error message you are showing probably has nothing to do with your code but is a bug in a recent Xamarin version. See here: https://bugzilla.xamarin.com/show_bug.cgi?id=56787
Found the answer on this page (https://releases.xamarin.com/common-issues-in-the-xamarin-15-2-2-release-being-tracked-by-the-xamarin-team/).
The solution is as follows
Download the missing Mono.Posix file and unzip the archive.
Right-click the Mono.Posix.dll file in Explorer and select Properties.
Check the Digital Signatures tab to ensure the file shows a valid Xamarin Inc. signature.
At the bottom of the General tab, if an Unblock checkbox appears, enable it and select OK. (This checkbox appears depending on how the file was downloaded.)
For Visual Studio 2017, copy the Mono.Posix.dll file into the “Xamarin.VisualStudio” extension directory. For example, for a default installation of the Enterprise edition, copy the file into:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Xamarin.VisualStudio
For Visual Studio 2015, copy the file into the “Xamarin\Xamarin” extension directory:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Xamarin\Xamarin\
Quit and restart Visual Studio.
For more detail, visit the link given above.

Unable to load DLL 'e_sqlite3': The specified module could not be found

I have a Xamarin Forms solution. I added sqlite-net-pcl as reference to all projects. It works fine on Android but crashes on Windows 8.1 and Windows Phone 8.1. I have an IOS project but I don't have OSX at the moment to try it.
I use this in the Windows projects to access the database:
using System.IO;
using SQLite;
using Xamarin.Forms;
using HelloXamarin.Windows;
using Windows.Storage;
[assembly: Dependency(typeof(SQLiteDb))]
namespace HelloXamarin.Windows
{
public class SQLiteDb : ISQLiteDb
{
public SQLiteAsyncConnection GetConnection(string databaseName)
{
var documentsPath = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(documentsPath, databaseName);
return new SQLiteAsyncConnection(path);
}
}
}
Here are my references:
I get this exception when trying to access the database:
The type initializer for 'SQLite.SQLiteConnection' threw an exception.
Unable to load DLL 'e_sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at SQLitePCL.SQLite3Provider_e_sqlite3.NativeMethods.sqlite3_win32_set_directory(UInt32 directoryType, String directoryPath)
at SQLitePCL.SQLite3Provider_e_sqlite3..ctor()
at SQLitePCL.Batteries_V2.Init() at SQLite.SQLiteConnection..cctor()
I have no idea how to solve this, please help me!
The whole solution is available on GitHub:
https://github.com/apspot/HelloXamarin
For me, it worked by adding the e_sqlite3 bundle to the executable project
By this time the issue is still open. So before they come with some solid fix, you can use this work around, to solve the issue for now.
Add one helper class
using System;
using System.Diagnostics;
using System.IO;
namespace SQLitePCL
{
public class NativeLibraryHack
{
public static bool Hacked { get; private set; }
public static bool DoHack()
{
if (Hacked) return true;
try
{
const string runtimeFolderName = "/runtimes";
var destinationPath = typeof(SQLitePCL.raw).Assembly.Location
.Replace("\\", "/");
var destinationLength = destinationPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var destinationDirectory = destinationPath.Substring(0, destinationLength) + runtimeFolderName;
var sourcePath = new Uri(typeof(SQLitePCL.raw).Assembly.CodeBase)
.AbsolutePath;
var sourceLength = sourcePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var sourceDirectory = sourcePath.Substring(0, sourceLength) + runtimeFolderName;
if (Directory.Exists(sourceDirectory))
CopyFilesRecursively(new DirectoryInfo(sourceDirectory), new DirectoryInfo(destinationDirectory));
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
return false;
}
return (Hacked = true);
}
private static void CopyFilesRecursively(
DirectoryInfo source,
DirectoryInfo target
)
{
foreach (var dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
{
try
{
var destinationFile = Path.Combine(target.FullName, file.Name);
if (!File.Exists(destinationFile))
file.CopyTo(destinationFile);
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
}
}
}
}
}
And add the hack before your db migration script, I am using web api 2
so i did on RouteConfig.RegisterRoutes
NativeLibraryHack.DoHack();
using (KSDBContext db = new KSDBContext())
{
db.Database.Migrate();
}
You need to add the SQLite Extensions.
Go to Tools > Extensions and Updates
Go to Online, then search for SQLite.
Download SQLite for Windows Runtime
In your Windows Project, Add Reference and ensure you add the extension.
Also remove Microsoft.VCLibs from your references.
Try referencing Visual C++ 2015 Runtime for Universal Windows Platform Apps. That sorted it out for me.
Go to References
Add Reference
Extensions.
Check"Visual C++ 2015 Runtime for Universal Windows Platform Apps"
OK

Programmatically access TFS annotations to determine owner

I'm working on a project team and our application is in TFS. I'm attempting to determine how many lines of code each team member is responsible. In TFS, I'm aware of the Annotate feature in the Visual Studio interface which allows you to see who last modified each line of code so I know TFS has this information.
I've written a small console app which accesses my TFS project and all its files, but I now need to programmatically access annotations so I can see who the owner of each line is. Here is my existing code:
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
public class Program
{
static void Main(string[] args)
{
var credentials = new NetworkCredential(username, password, domain);
var server = new TfsTeamProjectCollection(new Uri(serverUrl), credentials);
var version = server.GetService(typeof(VersionControlServer)) as VersionControlServer;
var items = version.GetItems(projectPath, RecursionType.Full);
var fileItems = items.Items.Where(x => x.ItemType == ItemType.File);
foreach (var fileItem in fileItems)
{
var serverItem = fileItem.ServerItem;
//TODO: retrieve and parse annotations
}
}
}
I can't seem to figure out how to retrieve annotations once I have the TFS item. This link explains how to do it by calling TFPT, but after implementing it (tfpt annotate /noprompt <filename>), you are only give the last changeset and code per line, not the owner.
I also found a Microsoft.TeamFoundation.VersionControl.Server namespace that has an Annotation class. I installed TFS on my machine to have access to that DLL, but it doesn't seem like it is of any help to this problem.
How can you programmatically access TFS annotations to determine the owner of a line of code for a file?
You may have to query the branch when a Item's change type is Branch.
For a simple example, there is a scenario
$/Project
/Main`
/a.txt
/Develop
/a.txt (branched from main)
When you query the history of $/project/Develop/a.txt, you can also get the history of $/project/Main/a.txt using following code
void GetAllHistory(string serverItem)
{
var changesets=vcs.QueryHistory(serverItem,
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest,
0,
Microsoft.TeamFoundation.VersionControl.Client.RecursionType.None,
null,
new Microsoft.TeamFoundation.VersionControl.Client.ChangesetVersionSpec(1),
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest,
int.MaxValue,
true,
false);
foreach (var obj in changesets)
{
Microsoft.TeamFoundation.VersionControl.Client.Changeset cs = obj as Microsoft.TeamFoundation.VersionControl.Client.Changeset;
if (cs == null)
{
return;
}
foreach (var change in cs.Changes)
{
if (change.Item.ServerItem != serverItem)
{
return;
}
Console.WriteLine(string.Format("ChangeSetID:{0}\tFile:{1}\tChangeType:{2}", cs.ChangesetId,change.Item.ServerItem, change.ChangeType));
if ((change.ChangeType & Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Branch) == Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Branch)
{
var items=vcs.GetBranchHistory(new Microsoft.TeamFoundation.VersionControl.Client.ItemSpec[]{new Microsoft.TeamFoundation.VersionControl.Client.ItemSpec(serverItem, Microsoft.TeamFoundation.VersionControl.Client.RecursionType.None)},
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest);
GetAllHistory(items[0][0].Relative.BranchToItem.ServerItem);
}
}
}
}

Resources