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;
}
}
}
Related
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
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
Scripts works fine when I run the exe when I am logged into the machine. But when I schedule the .exe on VisualCron, it throws an exception. I tried the same .exe on windows scheduler, I am able to run the job.
Error details given below. How do I work around this issue. Please help.
Code:
using log4net;
using Microsoft.VisualStudio.TestTools.UITest.Common;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace SeleniumDocManager
{
class To_Run_IE
{
private static ILog log;
static void ConfigureLog4Net()
{
log4net.GlobalContext.Properties["applicationname"] = "Selenium";
log4net.Config.XmlConfigurator.Configure();
log = LogManager.GetLogger(System.Reflection.Assembly.GetExecutingAssembly().GetType());
}
static string CreateFileFolder()
{
//Environment.CurrentDirectory = "C:\\myCSharp\\mySelenium";
Environment.CurrentDirectory = "E:\\Jobs\\Visualcron\\QA\\myInfoCenter";
string foldername = Path.Combine(Environment.CurrentDirectory, DateTime.Now.ToString("yyyy-MM-dd"));
if (!Directory.Exists(foldername))
{
Directory.CreateDirectory(foldername);
}
return foldername;
}
static void Main(string[] args)
{
ConfigureLog4Net();
string todayFolder = CreateFileFolder();
string programOutputPath = Path.Combine(todayFolder, "ProgramOutput.txt");
IWebDriver driver = new InternetExplorerDriver();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(programOutputPath, true))
{
file.WriteLine("Starting Test, page title is: " + driver.Title);
}
string outputpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Console.Write ("outputpath is :" + outputpath + " ");
log.Debug("Starting Test, page title is: " + driver.Title);
System.Console.WriteLine("Starting Test, page title is: " + driver.Title);
System.Console.WriteLine("Page source is: " + driver.PageSource);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("http://cf-qa-web01:100/Home/Attachments/B1C56889-54D6-E211-ACC3-0050569D4561");
System.Threading.Thread.Sleep(5000);
By byXpath = By.XPath("//select[#id='DocumentType']");
System.Threading.Thread.Sleep(5000);
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byXpath));
IWebElement element = driver.FindElement(byXpath);
var selectElement = new SelectElement(element);
int options = selectElement.Options.Count;
System.Threading.Thread.Sleep(5000);
Screenshot s0 = ((ITakesScreenshot)driver).GetScreenshot();
System.Threading.Thread.Sleep(5000);
s0.SaveAsFile(Path.Combine(todayFolder, string.Format("{0}_{1:yyyy-MM-dd_HH-mm-ss}.jpeg", "Document_Manager_Initial_Screenshot", DateTime.Now)),
System.Drawing.Imaging.ImageFormat.Gif);
System.Threading.Thread.Sleep(2000);
try
{
Console.WriteLine(selectElement.Options[0].Text);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(programOutputPath, true))
{
file.WriteLine("Capture # " + selectElement.Options[0].Text);
}
string _getssName = selectElement.Options[0].Text;
//new SelectElement(driver.FindElement(byXpath)).SelectByIndex(0);
Console.WriteLine("Capturing " + "Select Document Type" + " dropdown screenshot");
System.Threading.Thread.Sleep(5000);
Screenshot sss = ((ITakesScreenshot)driver).GetScreenshot();
System.Threading.Thread.Sleep(5000);
sss.SaveAsFile(Path.Combine(todayFolder, string.Format("{0}_{1}_{2:yyyy-MM-dd_HH-mm-ss}.jpeg", " Select Document Type ", "dropdown", DateTime.Now))
Error Details:
Unhandled Exception: OpenQA.Selenium.UnhandledAlertException: Modal dialog present at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) at OpenQA.Selenium.Remote.RemoteWebDriver.GetScreenshot() at SeleniumDocManager.To_Run_IE.Main(String[] args) Exception in Task: Non zero exit code
By default, all Tasks are executed in the background by the VisualCron service, normally running as SYSTEM account. If, for some reason, your executable tries to show an interface it will block the system as there is no desktop in the background to display or interact with the message.
You might want to know the reason why it throws the error. But if it works outside of VisualCron the cause is normally that you are not;
using a Credential
"Load profile" has not been checked in the Credential settings
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).
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.