-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathoffice.cs
345 lines (292 loc) · 12.1 KB
/
office.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
public class Startup
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("oleacc.dll", SetLastError = true)]
internal static extern IntPtr GetProcessHandleFromHwnd(IntPtr hwnd);
[DllImport("kernel32.dll")]
internal static extern int GetProcessId(IntPtr handle);
const UInt32 WM_CLOSE = 0x0010;
Word.Application msword;
Excel.Application msexcel;
PowerPoint.Application mspowerpoint;
TaskFactory scheduler;
public async Task<object> Invoke(object input)
{
scheduler = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(1));
return new {
word = (Func<object,Task<dynamic>>)word,
excel = (Func<object,Task<dynamic>>)excel,
powerPoint = (Func<object,Task<dynamic>>)powerPoint,
close = (Func<object,Task<dynamic>>)close,
};
}
void Delay(int stage) {
//Thread.Sleep(100);
}
private void CreateWord() {
lock(this) {
if (msword == null) {
msword = new Word.Application();
msword.Visible = true;
msword.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
msword.ChangeFileOpenDirectory(Directory.GetCurrentDirectory());
msword.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
}
}
}
private void CreateExcel() {
lock (this) {
if (msexcel == null) {
msexcel = new Excel.Application();
msexcel.Visible = true;
msexcel.DisplayAlerts = false;
msexcel.DefaultFilePath = Directory.GetCurrentDirectory();
msexcel.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
msexcel.AskToUpdateLinks = false;
}
}
}
private void CreatePowerPoint() {
lock(this) {
if (mspowerpoint == null) {
mspowerpoint = new PowerPoint.Application();
mspowerpoint.Visible = MsoTriState.msoTrue;
mspowerpoint.DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone;
mspowerpoint.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
//No way to do this in powerpoint, it seems
//mspowerpoint.?Path? = Directory.GetCurrentDirectory();
}
}
}
public async Task<dynamic> word(dynamic opts) {
var file = Path.GetFullPath(opts.input as string);
var pdfFile = Path.GetFullPath(opts.output as string);
return await scheduler.StartNew(() => {
Thread.Sleep(100);
CreateWord();
var doc = msword.Documents.OpenNoRepairDialog(file, false, true, false, "", "", true, "", "", Type.Missing, Type.Missing, true, true, Type.Missing, true, Type.Missing);
Delay(0);
try {
Delay(1);
doc.ExportAsFixedFormat(pdfFile, Word.WdExportFormat.wdExportFormatPDF);
Delay(2);
}
finally {
(doc as Word._Document).Close(false);
Marshal.ReleaseComObject(doc);
}
//closeInternal();
return pdfFile;
});
}
public async Task<dynamic> excel(dynamic opts) {
var file = Path.GetFullPath(opts.input as string);
var pdfFile = Path.GetFullPath(opts.output as string);
return await scheduler.StartNew(() => {
Thread.Sleep(100);
CreateExcel();
var book = msexcel.Workbooks.Open(file, 2, true, Type.Missing, "", "", false, Type.Missing, Type.Missing, false, false, Type.Missing, false, true, Excel.XlCorruptLoad.xlNormalLoad);
Delay(0);
try {
Delay(1);
book.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFile, Excel.XlFixedFormatQuality.xlQualityStandard, true, false);
Delay(2);
} finally {
(book as Excel._Workbook).Close(false);
Marshal.ReleaseComObject(book);
}
//closeInternal();
return pdfFile;
});
}
public async Task<dynamic> powerPoint(dynamic opts) {
var file = Path.GetFullPath(opts.input as string);
var pdfFile = Path.GetFullPath(opts.output as string);
return await scheduler.StartNew(() => {
Thread.Sleep(100);
CreatePowerPoint();
var presso = mspowerpoint.Presentations.Open(file, MsoTriState.msoTrue, WithWindow: MsoTriState.msoFalse);
Delay(0);
try {
Delay(1);
// presso.ExportAsFixedFormat(pdfFile, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF, PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint);
presso.SaveAs(pdfFile, PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
Delay(2);
} finally {
presso.Close();
Marshal.ReleaseComObject(presso);
}
//closeInternal();
return pdfFile;
});
}
private void closeInternal() {
Delay(4);
if (msword != null) {
try {
(msword as Word._Application).Quit();
}
catch (Exception) { }
Marshal.ReleaseComObject(msword);
msword = null;
}
if (msexcel != null) {
try {
msexcel.Quit();
}
catch (Exception) { }
Marshal.ReleaseComObject(msexcel);
msexcel = null;
}
if (mspowerpoint != null) {
try {
mspowerpoint.Quit();
}
catch (Exception) { }
Marshal.ReleaseComObject(mspowerpoint);
mspowerpoint = null;
}
Thread.Sleep(1000);
}
//Close open office apps on cleanup
public async Task<object> close(dynamic opts) {
//Powerpoint & co sometimes need some more time before they can quit grafeully
return await scheduler.StartNew(() => {
closeInternal();
return true;
});
}
~Startup() {
close(null).Wait();
}
}
// <summary>
/// Provides a task scheduler that ensures a maximum concurrency level while
/// running on top of the ThreadPool.
/// </summary>
public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler
{
/// <summary>Whether the current thread is processing work items.</summary>
[ThreadStatic]
private static bool _currentThreadIsProcessingItems;
/// <summary>The list of tasks to be executed.</summary>
private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); // protected by lock(_tasks)
/// <summary>The maximum concurrency level allowed by this scheduler.</summary>
private readonly int _maxDegreeOfParallelism;
/// <summary>Whether the scheduler is currently processing work items.</summary>
private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks)
/// <summary>
/// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the
/// specified degree of parallelism.
/// </summary>
/// <param name="maxDegreeOfParallelism">The maximum degree of parallelism provided by this scheduler.</param>
public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
{
if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism");
_maxDegreeOfParallelism = maxDegreeOfParallelism;
}
/// <summary>Queues a task to the scheduler.</summary>
/// <param name="task">The task to be queued.</param>
protected sealed override void QueueTask(Task task)
{
// Add the task to the list of tasks to be processed. If there aren't enough
// delegates currently queued or running to process tasks, schedule another.
lock (_tasks)
{
_tasks.AddLast(task);
if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
}
/// <summary>
/// Informs the ThreadPool that there's work to be executed for this scheduler.
/// </summary>
private void NotifyThreadPoolOfPendingWork()
{
ThreadPool.UnsafeQueueUserWorkItem(_ =>
{
// Note that the current thread is now processing work items.
// This is necessary to enable inlining of tasks into this thread.
_currentThreadIsProcessingItems = true;
try
{
// Process all available items in the queue.
while (true)
{
Task item;
lock (_tasks)
{
// When there are no more items to be processed,
// note that we're done processing, and get out.
if (_tasks.Count == 0)
{
--_delegatesQueuedOrRunning;
break;
}
// Get the next item from the queue
item = _tasks.First.Value;
_tasks.RemoveFirst();
}
// Execute the task we pulled out of the queue
base.TryExecuteTask(item);
}
}
// We're done processing items on the current thread
finally { _currentThreadIsProcessingItems = false; }
}, null);
}
/// <summary>Attempts to execute the specified task on the current thread.</summary>
/// <param name="task">The task to be executed.</param>
/// <param name="taskWasPreviouslyQueued"></param>
/// <returns>Whether the task could be executed on the current thread.</returns>
protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
// If this thread isn't already processing a task, we don't support inlining
if (!_currentThreadIsProcessingItems) return false;
// If the task was previously queued, remove it from the queue
if (taskWasPreviouslyQueued) TryDequeue(task);
// Try to run the task.
return base.TryExecuteTask(task);
}
/// <summary>Attempts to remove a previously scheduled task from the scheduler.</summary>
/// <param name="task">The task to be removed.</param>
/// <returns>Whether the task could be found and removed.</returns>
protected sealed override bool TryDequeue(Task task)
{
lock (_tasks) return _tasks.Remove(task);
}
/// <summary>Gets the maximum concurrency level supported by this scheduler.</summary>
public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } }
/// <summary>Gets an enumerable of the tasks currently scheduled on this scheduler.</summary>
/// <returns>An enumerable of the tasks currently scheduled.</returns>
protected sealed override IEnumerable<Task> GetScheduledTasks()
{
bool lockTaken = false;
try
{
Monitor.TryEnter(_tasks, ref lockTaken);
if (lockTaken) return _tasks.ToArray();
else throw new NotSupportedException();
}
finally
{
if (lockTaken) Monitor.Exit(_tasks);
}
}
}