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

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

Related

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

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

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

Tags not being deleted in Microsoft Office Object model

I have this weird problem with the Powerpoint office model. For various reasons I store some user data in the tags of the presentation. But I need to be able to strip them out. The delete just fine in the object model, but when I save the presentation, the tags are restored. Here is a sample program:
// Reference to Microsoft.Office.Core and Microsoft.Office.Interop.Powerpoint
// required to execute this code.
using System;
using Ppt = Microsoft.Office.Interop.PowerPoint;
namespace PptCleaner
{
class Program
{
static void Main(string[] args)
{
var filename = args[0];
var app = new Ppt.Application();
var pres = app.Presentations.Open(filename);
// Presentation has four tags, so pres.Tags.Count == 4
while(pres.Tags.Count > 0)
pres.Tags.Delete(pres.Tags.Name(1));
// After loop pres.Tags.Count == 0
pres.Save();
// After save pres.Tags.Count has gone back to 4
pres.Close();
app.Quit();
}
}
}
Per OP's request this is the code with which I was unable to reproduce the issue:
using System;
using Microsoft.Office.Interop.PowerPoint;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Application ppt = new Application();
Presentation pres = ppt.Presentations.Open(#"C:\test2.pptm");
Console.WriteLine("count before: " + pres.Tags.Count);
while (pres.Tags.Count > 0) pres.Tags.Delete(pres.Tags.Name(1));
Console.WriteLine("count after: " + pres.Tags.Count);
pres.Save();
pres.Close();
ppt.Quit();
Console.ReadLine();
}
}
}
I had previously added four tags to test2.pptm via a macro in the workbook. The first time I ran this program I got the output 0 followed by 4, the second time I got 0 both times (as expected).

Powerpoint interop

I'm new to .NET. I want to make a console application that converts a .pptx file into a .wmv.I've managed to do this using powerpoint interop.But i have some problems.First If i build the application and tranfer it to another computer i get an exception Error HRESULT E_FAIL has been returned for COM object(i have powerpoint in both PCs).If i run it on the one that i wrote it i everything works alright.But not for the first time.Meaning that when i start my pc and run it i'll get the same exception and the second time i'll try to run it will run properly.What could be the problem?iguess something with interop and powerpoint but i can't figure it out.
Ok here is the code:
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Runtime.InteropServices;
using System.IO;
using System;
namespace Microsoft.Office.Interop.PowerPoint
{
class Program
{
static void Main(string[] args)
{
string fileName = args[0];
string exportName = args[1];
string exportPath = args[2];
Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
ppApp.Visible = MsoTriState.msoTrue;
ppApp.WindowState = PpWindowState.ppWindowMinimized;
Microsoft.Office.Interop.PowerPoint.Presentations oPresSet = ppApp.Presentations;
Microsoft.Office.Interop.PowerPoint._Presentation oPres = oPresSet.Open(fileName,
MsoTriState.msoFalse, MsoTriState.msoFalse,
MsoTriState.msoFalse);
try
{
oPres.CreateVideo(exportName);
oPres.SaveCopyAs(String.Format(exportPath, exportName),
PowerPoint.PpSaveAsFileType.ppSaveAsWMV,
MsoTriState.msoCTrue);
}
finally
{
ppApp.Quit();
}
}
}
}
_Presentation.CreateVideo doesn't create a video out of a powerpoint. It creates a video inside of a powerpoint. That's what the documentation says, anyway.
Try _Presentation.SaveAs and then use PpSaveAsFileType.ppSaveAsWMV for the file type.

Turn solution into a pdf or doc file

This might seem like an odd question, but I need to turn my code into a pdf - so I can hand it in. Yes sadly the school system demands the code on cd as a pdf. What I could do is open every class in my solution and copy paste it. But - as a programmer - I am lazy and would like to know if Visual Studio has any feature for this? or if there is any other way?
Edit: A third party program that iterates through all files in a folder, opens the file and copies it's content, into a pdf file. Would do aswell - it does not have to be within Visual Studio.
Got tired of waiting, here's what I came up with:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace GetFileContents
{
class Program
{
static string types = ".js,.cshtml,.cs,.less,.css";
private static string text = "";
static void Main(string[] args)
{
//This folder wraps the whole thing.
string folderPath = #"C:\randomFolderWhereProjectIs\";
string s = IterateIt(Directory.GetDirectories(folderPath).ToList());
//Save to file or whatever I just used the text visualiser in Visual Studio
}
private static string IterateIt(List<string> l)
{
foreach (var path in l)
{
var files = Directory.GetFiles(path).Select(c => new FileInfo(c)).Where(c => types.Split(',').Contains(c.Extension));
foreach (var fileInfo in files)
{
text += fileInfo.Name + "\r\n";
using (StreamReader reader = fileInfo.OpenText())
{
text += reader.ReadToEnd() + "\r\n";
}
}
text = IterateIt(Directory.GetDirectories(path).ToList());
}
return text;
}
}
}

Resources