public string GetResult(Guid jobId) { _status = new ConversionJobStatus("Word Automation Services", jobId, null); string result; if (_status.Count == _status.Succeeded + _status.Failed) { result = "Completed, Successful: " + _status.Succeeded + ", Failed: " + _status.Failed; } else { result = "In progress, Successful: " + _status.Succeeded + ", Failed: " + _status.Failed; } return result; }
protected void Page_Load(object sender, EventArgs e) { using (SPSite spSite = new SPSite(Web.Url)) { using (SPWeb spWeb = spSite.OpenWeb()) { try { var proxies = SPServiceContext.Current.GetProxies(typeof(WordServiceApplicationProxy)); if (proxies.Any()) { _proxy = proxies.First(); } else { return; } if (spSite.SiteSubscription != null) { _jobStatuses = ConversionJobStatus.GetAllJobs(_proxy.DisplayName, spSite.UserToken, spSite.SiteSubscription.Id); } else { _jobStatuses = ConversionJobStatus.GetAllJobs(_proxy.DisplayName, spSite.UserToken, null); } } catch (SPException exception) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASHistory", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred", exception.StackTrace); return; } catch (InvalidOperationException exception2) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to contact the Word Automation Services. Validate that the" + "Word Automation Service is Started.", exception2.StackTrace); return; } GetJobHistory(); } } }
public Guid ConvertDocuments(SPSite spSite, SPWeb spWeb, ArrayList files, DocSaveFormat docSaveFormat, DocSaveBehaviour docSaveBehaviour) { SaveFormat savFormat = GetSaveFormat(docSaveFormat); SaveBehavior savBehaviour = getSaveBehavior(docSaveBehaviour); const string wordAutomationServiceName = "Word Automation Services"; var job = new ConversionJob(wordAutomationServiceName) {UserToken = spSite.UserToken}; job.Settings.UpdateFields = true; job.Settings.OutputFormat = savFormat; job.Settings.OutputSaveBehavior = savBehaviour; job.Settings.AddThumbnail = true; foreach (string file in files) { job.AddFile(spWeb.Url + "/" + SourceLibrary + "/" + file, spWeb.Url + "/" + DestinationLibrary + "/" + Path.GetFileNameWithoutExtension(file) + Extension); } job.Start(); _status = new ConversionJobStatus(wordAutomationServiceName, job.JobId, null); return job.JobId; }
static void Main(string[] args) { Console.WriteLine("OPG DocStorageConverter"); Console.WriteLine(""); Console.WriteLine("Connecting to:\t\t" + Settings.siteUrl); using (SPSite spSite = new SPSite(Settings.siteUrl)) { SPFolder folderToConvert = spSite.RootWeb.GetFolder(Settings.fileconvert); ConversionJob job = new ConversionJob(Settings.wordAutomationServiceName); job.UserToken = spSite.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.PDF; job.Settings.FixedFormatSettings.UsePDFA = true; foreach (SPFile file in folderToConvert.Files) { if (Files.HasExtension(file.Name, new string[] { ".docx", ".docm", ".dotx", ".dotm", ".doc", ".dot", ".rtf", ".mht", ".mhtml", ".xml" })) { string filePath = (Settings.siteUrl + "/" + file.Url); Console.WriteLine("Found:\t\t\t" + filePath); using (SPWeb web = spSite.OpenWeb()) { if (web.GetFile(filePath).Exists) { Console.WriteLine("Already Exists:\t\t" + Files.StripExtension(filePath) + ".pdf"); Console.WriteLine("Deleting:\t\t" + Files.StripExtension(filePath) + ".pdf"); SPFile eFile = web.GetFile(Files.StripExtension(filePath) + ".pdf"); eFile.Delete(); eFile.Update(); } } job.AddFile(filePath, Files.StripExtension(filePath) + ".pdf"); } } try { job.Start(); } catch (InvalidOperationException) { Console.WriteLine("Done:\t\t\tNo files to convert"); return; } Console.WriteLine("\t\t\tConversion job started"); ConversionJobStatus status = new ConversionJobStatus(Settings.wordAutomationServiceName, job.JobId, null); Console.WriteLine("Job length:\t\t" + status.Count); while (true) { Thread.Sleep(5000); status = new ConversionJobStatus(Settings.wordAutomationServiceName, job.JobId, null); if (status.Count == status.Succeeded + status.Failed) { Console.WriteLine("Completed:\t\tSuccessful: " + status.Succeeded + ", Failed: " + status.Failed); ReadOnlyCollection <ConversionItemInfo> failedItems = status.GetItems(ItemTypes.Failed); foreach (ConversionItemInfo failedItem in failedItems) { Console.WriteLine("Failed converting:\t" + failedItem.InputFile); Console.WriteLine(failedItem.ErrorMessage); } Console.WriteLine("\t\t\tSetting meta on files that successfully converted"); ReadOnlyCollection <ConversionItemInfo> convertedItems = status.GetItems(ItemTypes.Succeeded); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web = spSite.OpenWeb()) { web.AllowUnsafeUpdates = true; foreach (ConversionItemInfo convertedItem in convertedItems) { SPFile inFile = web.GetFile(convertedItem.InputFile); SPFile outFile = web.GetFile(convertedItem.OutputFile); try { SPListItem inListItem = inFile.Item; SPListItem outListItem = outFile.Item; Console.WriteLine("Set metadata on:\t" + outFile.Url); foreach (SPField field in inListItem.Fields) { try { if (outListItem.Fields.ContainsField(field.InternalName) == true && field.ReadOnlyField == false && field.InternalName != "Attachments" && field.InternalName != "Name") { outListItem[field.InternalName] = inListItem[field.InternalName]; Console.WriteLine("Setting field:\t\t" + field.InternalName); } } catch (Exception e) { Console.WriteLine("Failed to set field:\t" + field.InternalName + " : " + e.Message); } } outListItem.Update(); outFile.Update(); } catch (Exception e) { Console.WriteLine("Failed to set on:\t" + outFile.Url + " from : " + inFile.Url); Console.WriteLine(e.Message); } } web.AllowUnsafeUpdates = false; } }); Console.WriteLine("\t\t\tDeleting only items that successfully converted"); foreach (ConversionItemInfo convertedItem in convertedItems) { Console.WriteLine("Deleting item:\t\tName:" + convertedItem.InputFile); folderToConvert.Files.Delete(convertedItem.InputFile); } break; } Console.WriteLine("In progress:\t\tSuccessful: " + status.Succeeded + ", Failed: " + status.Failed); } Console.WriteLine("Done:\t\t\tFinished"); } }
private byte[] ConvertDocument(SPWeb web, byte[] docToConvert, string docFileName, bool isImmediate, String conversionLibName, int timeOutSecs, bool deleteDocs) { byte[] result = null; SPList conversionLib = web.Lists[conversionLibName]; SPFolder folder = conversionLib.RootFolder; // Get the default proxy for the current Word Automation Services instance SPServiceContext serviceContext = SPServiceContext.GetContext(web.Site); WordServiceApplicationProxy wordServiceApplicationProxy = (WordServiceApplicationProxy)serviceContext.GetDefaultProxy(typeof(WordServiceApplicationProxy)); ConversionJob job = new ConversionJob(wordServiceApplicationProxy); job.UserToken = web.CurrentUser.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; job.Settings.OutputFormat = SaveFormat.PDF; //String docFileName = Guid.NewGuid().ToString("D"); docFileName = Guid.NewGuid().ToString("D"); // we replace possible existing files on upload // although there is a minimal chance for GUID duplicates :-) SPFile docFile = folder.Files.Add(docFileName + ".docx", docToConvert, true); conversionLib.AddItem(docFileName + ".docx", SPFileSystemObjectType.File); String docFileUrl = String.Format("{0}/{1}", web.Url, docFile.Url); String pdfFileUrl = String.Format("{0}/{1}.pdf", web.Url, docFile.Url.Substring(0, docFile.Url.Length - 5)); job.AddFile(docFileUrl, pdfFileUrl); // let's do the job :-) // Start-SPTimerJob "Word Automation Services" job.Start(); if (isImmediate) { //Feature scope must be Web Application to use this function StartServiceJob("Word Automation Services Timer Job"); } ConversionJobStatus cjStatus = new ConversionJobStatus(wordServiceApplicationProxy, job.JobId, null); // set up timeout TimeSpan timeSpan = new TimeSpan(0, 0, timeOutSecs); DateTime conversionStarted = DateTime.Now; int finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed; while ((finishedConversionCount != 1) && ((DateTime.Now - conversionStarted) < timeSpan)) { // wait a sec. Thread.Sleep(1000); cjStatus = new ConversionJobStatus(wordServiceApplicationProxy, job.JobId, null); finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed; } // timeouted -> cancel conversion if (finishedConversionCount != 1) { job.Cancel(); } // we can output the possible failed conversion error(s) foreach (ConversionItemInfo cii in cjStatus.GetItems(ItemTypes.Failed)) { Utility.LogError(string.Format("Failed conversion. Input file: '{0}'; Output file: '{1}'; Error code: '{2}'; Error message: '{3}';", cii.InputFile, cii.OutputFile, cii.ErrorCode, cii.ErrorMessage), "Document Generator"); } SPFile convertedFile = web.GetFile(pdfFileUrl); // shouldn't be null (unless there is a conversion error) // but we check for sure if ((convertedFile != null) && (convertedFile.Exists)) { Stream pdfStream = convertedFile.OpenBinaryStream(); result = new byte[pdfStream.Length]; pdfStream.Read(result, 0, result.Length); // delete result doc if requested if (deleteDocs) { convertedFile.Delete(); } } // delete source doc if requested if (deleteDocs) { docFile.Delete(); } return result; }
private OASResponse GetConvertedFile(string fileid, OASModels.ConversionSettings settings, SPUserToken userToken) { OASResponse oasResponse = new OASResponse(); using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken))) { using (SPWeb web = site.OpenWeb()) { try { // Get list of "old" file and delete them RemoveOldFiles(web); //check conversion type DocType dtype = GetJobType(web, fileid); switch (dtype) { case DocType.DOCX: // check if the current file conversion is finished ConversionJobStatus status = new ConversionJobStatus(ConfigurationManager.AppSettings["WASName"], Guid.Parse(fileid), null); if (status.Succeeded == 1) { // return finished document SPFile dest = GetFinishedFile(web, fileid); if (dest != null) { oasResponse.Content = Convert.ToBase64String(dest.OpenBinary()); oasResponse.ErrorCode = OASErrorCodes.Success; // remove converted file RemoveConversionFiles(web, fileid); } else { oasResponse.ErrorCode = OASErrorCodes.ErrFileNotExists; oasResponse.Message = "Converted file not exists"; } } else if (status.InProgress == 1 || status.NotStarted == 1) { //file not converted yet oasResponse.ErrorCode = OASErrorCodes.Success; } else { // something went wrong and file was not converted oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert; oasResponse.Message = "File conversion job error"; RemoveConversionFiles(web, fileid); } break; case DocType.PPTX: // check if the current file conversion is finished if (IsJobFinished(web, fileid)) { // return finished document SPFile dest = GetFinishedFile(web, fileid); if (dest != null) { oasResponse.Content = Convert.ToBase64String(dest.OpenBinary()); oasResponse.ErrorCode = OASErrorCodes.Success; // remove converted file RemoveConversionFiles(web, fileid); } else { oasResponse.ErrorCode = OASErrorCodes.ErrFileNotExists; oasResponse.Message = "Converted file not exists"; } } break; } } catch (Exception ex) { oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert; oasResponse.Message = ex.Message; } } } return(oasResponse); }
static void Main(string[] args) { string siteURL = args[0]; string docLib = args[1]; using (SPSite spSite = new SPSite(siteURL)) { SPDocumentLibrary library = spSite.RootWeb.Lists[docLib] as SPDocumentLibrary; string docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Automation.xml"; SPFile file = spSite.RootWeb.GetFile(docPath); XDocument automation = XDocument.Load(new StreamReader(file.OpenBinaryStream())); XElement autoElement = automation.Element("Automation"); string masterName = autoElement.Attribute("Master").Value; string printerName = autoElement.Attribute("Printer").Value; // Open the master document docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/" + masterName + ".docx"; SPFile masterFile = spSite.RootWeb.GetFile(docPath); Stream docStream = new MemoryStream(); Stream docMasterStream = masterFile.OpenBinaryStream(); BinaryReader docMasterReader = new BinaryReader(docMasterStream); BinaryWriter docWriter = new BinaryWriter(docStream); docWriter.Write(docMasterReader.ReadBytes((int)docMasterStream.Length)); docWriter.Flush(); docMasterReader.Close(); docMasterStream.Dispose(); Package package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite); WordprocessingDocument master = WordprocessingDocument.Open(package); string guid; Uri XMLUri = CreateCustomXML(master, automation.Descendants("Record").First(), out guid); BindControls(master, guid); master.Close(); docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output 00001.docx"; spSite.RootWeb.Files.Add(docPath, docStream, true); // Loop through all the records from the XML file int count = 1; foreach (XElement element in automation.Descendants("Record")) { if (count != 1) { package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite); master = WordprocessingDocument.Open(package); foreach (CustomXmlPart part in master.MainDocumentPart.CustomXmlParts) { if (part.Uri == XMLUri) { Stream stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(stream); sw.Write(element.ToString()); sw.Flush(); sw.Close(); break; } } master.Close(); docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + count.ToString("D5") + ".docx"; spSite.RootWeb.Files.Add(docPath, docStream, true); } count++; } // Use Word Automation Services to convert to XPS files ConversionJob job = new ConversionJob(WordAutomationServicesName); job.UserToken = spSite.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.XPS; job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; SPList listToConvert = spSite.RootWeb.Lists[docLib]; job.AddLibrary(listToConvert, listToConvert); job.Start(); for (; ;) { Thread.Sleep(5000); ConversionJobStatus status = new ConversionJobStatus(WordAutomationServicesName, job.JobId, null); if (status.Count == status.Succeeded + status.Failed) { break; } } // Print output XPS files LocalPrintServer srv = new LocalPrintServer(); PrintQueue pq = srv.GetPrintQueue(printerName); for (int num = 1; num < count; num++) { XpsDocumentWriter xdw = PrintQueue.CreateXpsDocumentWriter(pq); docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + num.ToString("D5") + ".xps"; SPFile docFile = spSite.RootWeb.GetFile(docPath); package = Package.Open(docFile.OpenBinaryStream(), FileMode.Open, FileAccess.Read); XpsDocument xdoc = new XpsDocument(package); xdoc.Uri = new Uri(docPath); xdw.Write(xdoc.GetFixedDocumentSequence()); xdoc.Close(); } } }
protected override ConversionJob CreateDataObject() { bool test = false; ShouldProcessReason reason; if (!base.ShouldProcess(null, null, null, out reason)) { if (reason == ShouldProcessReason.WhatIf) { test = true; } } if (test) { Logger.Verbose = true; } SPWeb contextWeb = null; object input = null; object output = null; if (ParameterSetName == "Library") { input = InputList.Read(); output = OutputList.Read(); if (input != null) { contextWeb = ((SPList)input).ParentWeb; } } else if (ParameterSetName == "Folder") { input = InputFolder.Read(); output = OutputFolder.Read(); if (input != null) { contextWeb = ((SPFolder)input).ParentWeb; } } else if (ParameterSetName == "File") { input = InputFile.Read(); if (!((SPFile)input).Exists) { throw new Exception("The specified input file does not exist."); } output = OutputFile; if (input != null) { contextWeb = ((SPFile)input).ParentFolder.ParentWeb; } if (contextWeb != null) { input = contextWeb.Site.MakeFullUrl(((SPFile)input).ServerRelativeUrl); } } if (input == null) { throw new Exception("The input can not be a null or empty value."); } if (output == null) { throw new Exception("The output can not be a null or empty value."); } WordServiceApplicationProxy proxy = GetWordServiceApplicationProxy(contextWeb.Site.WebApplication); ConversionJobSettings settings = new ConversionJobSettings(); settings.OutputFormat = OutputFormat; settings.OutputSaveBehavior = OutputSaveBehavior; settings.UpdateFields = UpdateFields; settings.AddThumbnail = AddThumbnail; settings.CompatibilityMode = CompatibilityMode; settings.EmbedFonts = EmbedFonts; settings.SubsetEmbeddedFonts = SubsetEmbeddedFonts; settings.MarkupView = MarkupView; settings.RevisionState = RevisionState; ConversionJob job = new ConversionJob(proxy, settings); job.UserToken = contextWeb.CurrentUser.UserToken; if (ParameterSetName == "Library") { job.AddLibrary((SPList)input, (SPList)output); } else if (ParameterSetName == "Folder") { job.AddFolder((SPFolder)input, (SPFolder)output, Recurse); } else if (ParameterSetName == "File") { job.AddFile((string)input, (string)output); } job.Start(); if (Wait) { ConversionJobStatus jobStatus = null; do { Thread.Sleep(1000); jobStatus = new ConversionJobStatus(proxy, job.JobId, null); } while (jobStatus.Failed == 0 && jobStatus.Succeeded == 0); } return(job); }
private void GetJobStatus() { try { using (SPSite spSite = new SPSite(Web.Url)) { using (SPWeb spWeb = spSite.OpenWeb()) { try { var proxies = SPServiceContext.Current.GetProxies(typeof(WordServiceApplicationProxy)); if (proxies.Any()) { _proxy = proxies.First(); } else { litErr.Visible = true; return; } if (spSite.SiteSubscription != null) { _jobStatuses = ConversionJobStatus.GetAllJobs(_proxy.DisplayName, spSite.UserToken, spSite.SiteSubscription.Id); } else { _jobStatuses = ConversionJobStatus.GetAllJobs(_proxy.DisplayName, spSite.UserToken, null); } } catch (SPException exception) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to find the Word Automation Services Proxy", exception.StackTrace); return; } catch (InvalidOperationException exception2) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to contact the Word Automation Services. Validate that the" + "Word Automation Service is Started.", exception2.StackTrace); return; } } } } catch (SPException exception) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred", exception.StackTrace); } if (_jobStatuses.Count == 0 || _jobStatuses == null) { litErr.Visible = true; return; } foreach (var job in _jobStatuses.Reverse().Take(100)) { var itemType = GetItemType(); var cJobStatus = new ConversionJobStatus(_proxy.DisplayName, job.JobId, null).GetItems(itemType); foreach (var jS in cJobStatus) { if (itemType == ItemTypes.Canceled || itemType == ItemTypes.InProgress) { var row = new TableRow(); table1.Rows.Add(row); var cell = new TableCell { Text = jS.ConversionId.ToString() }; var cell2 = new TableCell { Text = jS.StartTime.ToString() }; var cell3 = new TableCell { Text = jS.InputFile }; var cell4 = new TableCell { Text = jS.OutputFile }; row.Cells.Add(cell); row.Cells.Add(cell2); row.Cells.Add(cell3); row.Cells.Add(cell4); } else if (itemType == ItemTypes.Failed) { var row = new TableRow(); table1.Rows.Add(row); var cell = new TableCell { Text = jS.ConversionId.ToString() }; var cell2 = new TableCell { Text = jS.InputFile }; var cell3 = new TableCell { Text = jS.ErrorCode.ToString(CultureInfo.InvariantCulture) }; var cell4 = new TableCell { Text = jS.ErrorMessage }; row.Cells.Add(cell); row.Cells.Add(cell2); row.Cells.Add(cell3); row.Cells.Add(cell4); } else if (itemType == ItemTypes.NotStarted) { var row = new TableRow(); table1.Rows.Add(row); var cell = new TableCell { Text = jS.ConversionId.ToString() }; var cell2 = new TableCell { Text = jS.InputFile }; var cell3 = new TableCell { Text = jS.OutputFile }; row.Cells.Add(cell); row.Cells.Add(cell2); row.Cells.Add(cell3); } else if (itemType == ItemTypes.Succeeded) { var row = new TableRow(); table1.Rows.Add(row); var cell = new TableCell { Text = jS.ConversionId.ToString() }; var cell2 = new TableCell { Text = jS.InputFile }; var cell3 = new TableCell { Text = jS.OutputFile }; var cell4 = new TableCell { Text = jS.CompleteTime.Value.ToString(CultureInfo.InvariantCulture) }; row.Cells.Add(cell); row.Cells.Add(cell2); row.Cells.Add(cell3); row.Cells.Add(cell4); } } } if (table1.Rows.Count < 2) { litErr.Visible = true; } else { litErr.Visible = false; } }