Powerpoint interop - 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.

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

Start PowerPoint Slideshow using Microsoft.Interop

I'm totally new to C#. Using the Microsoft.Office.Interop.PowerPoint namespace, I want to be able to start a PowerPoint Presentation from code. There's a path and a finished presentation, and I want it to start in full screen automatically.
How can I do that?
Thank you.
Try this:
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using PPT = Microsoft.Office.Interop.PowerPoint;
namespace PowerPointLauncher
{
public void StartPresentation()
{
PPT.Application app = new PPT.Application();
//optionally on SlideShowEnd close all powerpoint windows created by your application (app)
app.SlideShowEnd += App_SlideShowEnd;
var pres = app.Presentations.Open("d:\\test.ppt", MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);
app.ActivePresentation.SlideShowSettings.Run();
}
private void App_SlideShowEnd(Presentation Pres)
{
foreach (DocumentWindow window in Pres.Application.Windows)
{
window.Close();
}
}
}

.exe starts successfully with windows scheduler but not throws error on visualcron

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

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).

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