XPSDocumentWriter - Printing Specific Pages to Specific Trays - wpf

I'm currently working on a printing application. This app has the requirement that certain pages need to come from specific trays on the printer. Here's the guts of what I've got so far:
foreach (var dto in dispensersToPrint)
{
var documents = FilterDocumentSections(DispenserDocumentsToPrint.RetrieveByDispenserId(dto.DispenserId));
var groupedDocs = documents.GroupBy(t => t.DocumentTypeId);
var queueName = Properties.Settings.Default.PrinterName;
var queue = RawPrinterHelper.GetPrintQueue(queueName);
var seq = new FixedDocumentSequence();
var xpsWriter = PrintQueue.CreateXpsDocumentWriter(queue);
foreach (var docGroup in groupedDocs)
{
var printTicket = queue.DefaultPrintTicket.Clone();
var printTray = MapPrintTray((DocumentSectionType)docGroup.Key);
if (!printTray.IsNullOrEmpty())
{
printTicket = RawPrinterHelper.ModifyPrintTicket(printTicket, "psk:JobInputBin", printTray);
}
var fixedDoc = new FixedDocument();
fixedDoc.PrintTicket = printTicket;
foreach (var doc in docGroup)
{
var pageContent = new PageContent();
var fixedPage = new FixedPage();
var localFileName = string.Empty;
var unzippedFileName = string.Empty;
//copy files locally
localFileName = CopyFileToLocalMachine(doc.FileName);
//unzip file
unzippedFileName = EmfPrintingHelper.UnzipEmfFile(localFileName);
var itemToPrint = new PrintableEmfImage
{
DataContext = new EmfImageViewModel { FileName = unzippedFileName }
};
fixedPage.Children.Add(itemToPrint);
pageContent.Child = fixedPage;
fixedDoc.Pages.Add(pageContent);
}
var docRef = new DocumentReference();
docRef.SetDocument(fixedDoc);
seq.References.Add(docRef);
}
xpsWriter.Write(seq);
}
At a real high level:
For each Dispenser (Work Order) i need to print; i first start by grouping by the DocumentType (i.e. Print type A to tray 1)
I then create a new FixedDocumentSequence
For each DocumentType; I then create a fixed document. I then modify the print ticket to look at the appropriate tray.
I then build each individual page for each document type; and add them to the FixedDocument
Once the building of the FixedDocument is complete; I append it to the DocumentSequence.
I then send the FixedDocumentSequence to the xpsWriter.
But for some reason; these settings aren't being honored. I get all the documents printing out of the same tray.
Here are some of my observations so far:
The modifying of the print ticket does work; I've verified this by sending a modified printTicket into the xpsWriter; but this applies the settings to the entire job; which is a no go for me.
When querying my print capabilities; i noticed that i only have JobInputBin. I don't quite think this means this printer doesn't support the functionality; as multi-tray printing works from a similar WindowsForms app (which uses PageSettings.PaperSource)
Any ideas on what I could try next? Has anyone been successful doing something like this before?

I'll start off by saying, I don't have access to a printer with trays, so I am unfortunately not capable of testing this solution. That said, I'll direct your attention to an MSDN forum post, here, where the original poster was in pursuit of the same tray-per-page behavior.
Based on your posted code, you may have already seen some of what's in this post, judging by your posted code having at least some implementation of ModifyPrintTicket().
In the post, there are several different users, each citing a solution for their specific version of the problem. However, the one that seems most relevant in this case is the solution regarding namespaces not being correctly accounted for in ModifyPrintTicket() (as posted by
Jo0815). I say 'most relevant' because the poster speaks of the print tray being disregarded. They (wittersworld) provide an alternate implementation to correct the issue. In the post on MSDN, the link to the complete source is broken, but can be located here.
The gist is, on ModifyPrintTicket(), they add a namespaceUri parameter, then withing changed this:
if (node != null)
{
node.Attributes["name"].Value = newValue;
}
to this:
if (node != null)
{
if (newValue.StartsWith("ns0000"))
{
// add namespace to xml doc
XmlAttribute namespaceAttribute = xmlDoc.CreateAttribute("xmlns:ns0000");
namespaceAttribute.Value = namespaceUri;
xmlDoc.DocumentElement.Attributes.Append(namespaceAttribute);
}
node.Attributes["name"].Value = newValue;
}
allowing the user to specify the printer-specific namespace used.
I hope this is helpful.

Related

Programmatically add Checkbox Content Controls to Word document using OpenXML

Is there an easy/straightforward way to dynamically add (not edit the value of) multiple checkbox controls in a .docx document body?
I tried appending a single SdtContentCheckBox after a new paragraph like this but with no luck:
newParagraph.Append(new SdtContentCheckBox());
and also followed the instructions here:
https://www.codeproject.com/Tips/370758/Add-dynamic-content-controls-to-a-word-document and here: How do I create a check box in C# using Open XML SDK
The first one showed only how to add a text content control and the second one straight up resulted in a corrupted .docx file.
Any help would be appreciated!
Closest working code I could find was this:
https://social.msdn.microsoft.com/Forums/office/en-US/f6ce8ecf-0ed8-4f18-958a-a086f212d1e2/how-to-create-a-checked-checkbox-form-field-using-the-sdk?forum=oxmlsdk
public static Paragraph GenerateParagraph()
{
var element =
new Paragraph(
new Run(
new FieldChar(
new FormFieldData(
new FormFieldName(){ Val = "Check1" },
new Enabled(),
new CalculateOnExit(){ Val = BooleanValues.Zero },
new CheckBox(
new AutomaticallySizeFormField(),
new DefaultCheckboxFormFieldState(){ Val = BooleanValues.Zero }))
){ FieldCharType = FieldCharValues.Begin }),
new BookmarkStart(){ Name = "Check1", Id = 0 },
new Run(
new FieldCode(" FORMCHECKBOX "){ Space = "preserve" }),
new Run(
new FieldChar(){ FieldCharType = FieldCharValues.End }),
new BookmarkEnd(){ Id = 0 },
new Run(
new Text("My check box"))
){ RsidParagraphAddition = "00784880", RsidRunAdditionDefault = "00B77989" };
return element;
}
Using this I was able to dynamically add Legacy Checkboxes (i.e. neither Content control nor ActiveX control), but at least it is a start!
If someone knows how to add Checkbox Content controls, feel free to post a reply below and I'll mark it as Correct.
Even though you found yourself the answer, I'll leave this here in case anyone stumbles upon this looking for something related.
There's a tool called Open XML SDK 2.5 Productivity Tool, which you can download from here that allows you to reverse-engineer a word .docx document to obtain the C# code to generate it from scratch.
In order to get the code that you are looking for to generate any kind of word element (a checkbox, a table, a bulleted list...), you need to create a word document with said element and save it.
Then, open it using the Open XML SDK 2.5 Productivity Tool and click on the "Reflect Code" button. The generated code will show you how to create those elements, styles and other formatting included.
With that, I got the code necessary to get a paragraph with a checkbox
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
public static Paragraph GenerateCheckboxParagraph(string internalName, int internalId, string textAfterTextbox)
{
var run1 = new Run(
new FieldChar(
new FormFieldData(
new FormFieldName() { Val = internalName },
new Enabled(),
new CalculateOnExit() { Val = OnOffValue.FromBoolean(false) },
new CheckBox(
new AutomaticallySizeFormField(),
new DefaultCheckBoxFormFieldState() { Val = OnOffValue.FromBoolean(false) }))
)
{
FieldCharType = FieldCharValues.Begin
}
);
var run2 = new Run(new FieldCode(" FORMCHECKBOX ") { Space = SpaceProcessingModeValues.Preserve });
var run3 = new Run(new FieldChar() { FieldCharType = FieldCharValues.End });
var run4 = new Run(new Text(textAfterTextbox));
var element =
new Paragraph(
run1,
new BookmarkStart() { Name = internalName, Id = new StringValue(internalId.ToString()) },
run2,
run3,
new BookmarkEnd() { Id = new StringValue(internalId.ToString()) },
run4
);
return element;
}

EpiServer - get absolute friendly url for given culture for page

I've a following setup in my Manage Websites panel
General Url is set to alloy.com
alloy.no is set for no culture
alloy.se is set for sv culture
alloy.com is set for en culture
In my code, i want to get the friendly external url for given language for given page.
So for Search page I want to get absolute friendly url in all languages.
I use following code to get friendly url for page (found on Anders G. Nordby blog):
var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();
var pageAddress = urlResolver.GetUrl(reference, language);
var builder = new UrlBuilder(pageAddress);
Global.UrlRewriteProvider.ConvertToExternal(builder, null, Encoding.UTF8);
var friendlyUrl = builder.Uri.IsAbsoluteUri
? builder.ToString()
: UriSupport.AbsoluteUrlBySettings(builder.ToString());
return friendlyUrl;
It is simple if I will use the alloy.com webpage and in my custom code generate friendly url.
no - alloy.no/søk
se - alloy.se/sök
en - alloy.com/search
But when I use alloy.no to enter edit mode and I will try to generate address for no i get alloy.com/søk when it should be alloy.no/søk.
I found that if I use alloy.no to go to Edit Mode, code :
urlResolver.GetUrl(reference, language)
returns only /søk and code
UriSupport.AbsoluteUrlBySettings(builder.ToString())
add the General URL (alloy.com) instead of alloy.no.
How can I improve this code to take correct host name for page in different culture?
The GetUrl method of the UrlResolver will return a URL to a page that is relative or absolute depending on the current request context. A URL will be relative if the page is located in the current site and absolute if in another site or if the call is made outside a request.
If you are using EPiServer.CMS.Core version 8.0 or later there is also support for identifying one site as the primary site. This update also made it possible to explicitly request that the URL should be to the primary site by setting the ForceCanonical flag on the VirtualPathArguments parameter. If not the flag is not set, it will prefer the current site URL over the primary (given the requested content is located on the current site).
So, with this in mind, you can assume that the returned URL, if not absolute, will be relative to the currently requested site and safely combine it with the currently requested URL such as:
private static string ExternalUrl(this ContentReference contentLink, CultureInfo language)
{
var urlString = UrlResolver.Current.GetUrl(contentLink, language.Name, new VirtualPathArguments { ForceCanonical = true });
if (string.IsNullOrEmpty(urlString) || HttpContext.Current == null) return urlString;
var uri = new Uri(urlString, UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri) return urlString;
return new Uri(HttpContext.Current.Request.Url, uri).ToString();
}
In most cases I would probably prefer not to use HttpContext.Current directly and instead pass in the current request URL. But in this case I have opted to use it directly to keep the example more contained.
We have a support case regarding this. We want the url resolver to always return an absolute url when requesting the canonical url. This is our current solution:
public static string ExternalUrl(this PageData p, bool absoluteUrl, string languageBranch)
{
var result = ServiceLocator.Current.GetInstance<UrlResolver>().GetUrl(
p.ContentLink,
languageBranch,
new VirtualPathArguments
{
ContextMode = ContextMode.Default,
ForceCanonical = absoluteUrl
});
// HACK: Temprorary fix until GetUrl and ForceCanonical works as expected,
// i.e returning an absolute URL even if there is a HTTP context that matches the page's
// site definition and host.
if (absoluteUrl)
{
Uri relativeUri;
if (Uri.TryCreate(result, UriKind.RelativeOrAbsolute, out relativeUri))
{
if (!relativeUri.IsAbsoluteUri)
{
var siteDefinitionResolver = ServiceLocator.Current.GetInstance<SiteDefinitionResolver>();
var siteDefinition = siteDefinitionResolver.GetDefinitionForContent(p.ContentLink, true, true);
var hosts = siteDefinition.GetHosts(p.Language, true);
var host = hosts.FirstOrDefault(h => h.Type == HostDefinitionType.Primary) ?? hosts.FirstOrDefault(h => h.Type == HostDefinitionType.Undefined);
var basetUri = siteDefinition.SiteUrl;
if (host != null)
{
// Try to create a new base URI from the host with the site's URI scheme. Name should be a valid
// authority, i.e. have a port number if it differs from the URI scheme's default port number.
Uri.TryCreate(siteDefinition.SiteUrl.Scheme + "://" + host.Name, UriKind.Absolute, out basetUri);
}
var absoluteUri = new Uri(basetUri, relativeUri);
return absoluteUri.AbsoluteUri;
}
}
}
return result;
}
I also ran into this issue when writing a scheduled job running on a multilanguage, multihostname site. In order to get an absolute url with the right hostname in a HttpContext-less situation I had to combine Henrik's code with Dejan's code from here: https://www.dcaric.com/blog/episerver-how-to-get-external-page-url.
This is what I came up with:
public static string ExternalUrl(this ContentReference contentLink, CultureInfo language)
{
var urlString = UrlResolver.Current.GetUrl(contentLink, language.Name, new VirtualPathArguments { ForceCanonical = true });
var uri = new Uri(urlString, UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri) return urlString;
string externalUrl = HttpContext.Current == null
? UriSupport.AbsoluteUrlBySettings(urlString)
: HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + urlString;
return externalUrl;
}
I've manage to write something base on the Johan & Henry answers:
public static string GetExternalAbsoluteFriendlyUrl(
this ContentReference reference,
string language)
{
var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();
var friendlyUrl = urlResolver.GetUrl(reference, language);
if (string.IsNullOrEmpty(friendlyUrl))
return friendlyUrl;
var uri = new Uri(friendlyUrl, UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri)
return friendlyUrl;
if (HttpContext.Current != null)
return new Uri(HttpContext.Current.Request.Url, uri).ToString();
var siteDefinitionResolver =
ServiceLocator.Current.GetInstance<SiteDefinitionResolver>();
var siteDefinition =
siteDefinitionResolver.GetDefinitionForContent(reference, true, true);
return new Uri(siteDefinition.SiteUrl, friendlyUrl).ToString();
}

Find and delete inactive tfs branches

Is there any built-in way to find and delete (tf destroy) branches of TFS project that were inactive (I mean there were no check in operations) for a long time, let's say 1 month. Either tfs tools or maybe sql script that can do it would be ok.
You can do it but you need to write a small program that uses the TFS API to check each branch and delete the unused ones.
You can use a simple C# console app and I can tell you from experience that the TFS public API is quite intuitive and easy to use. You can get started with it here.
Here's how to display all the branches.
Unused branches contain element modification history, rather than deleting them writelock the branch and leave it. The space that is recovered is not significant.
Well, whole thing wasn't hard, posting code here, might help someone:
private static string _tfLocation; //location of tf.exe
private static string _tfProject; //our team project
static void Main(string[] args)
{
_tfLocation = ConfigurationManager.AppSettings.Get("tfLocation");
_tfProject = ConfigurationManager.AppSettings.Get("tfProject");
var keepAliveBranches = ConfigurationManager.AppSettings.Get("keepAliveBranches").Split(',').ToList(); //branches that we keep anyway
var latestDate = DateTime.Now.AddMonths(-3); //we delete all branches that are older than 3 months
var folders = ExecuteCommand(string.Format("dir /folders \"{0}\"", _tfProject));
var branches = folders.Split('\r', '\n').ToList();
branches = branches.Where(b => !string.IsNullOrEmpty(b) && b.StartsWith("$")).Select(b => b.Remove(0, 1)).Skip(1).ToList();
branches.ForEach(b => b = b.Remove(0, 1));
foreach (var branch in branches)
{
if (keepAliveBranches.Contains(branch))
continue;
//get latest changeset
var lastChangeset = ExecuteCommand(string.Format("history \"{0}/{1}\" /recursive /stopafter:1 /format:brief /sort:descending /noprompt", _tfProject, branch));
var changesetDate = DateTime.Parse(Regex.Match(lastChangeset, #"\d{2}\.\d{2}\.\d{4}").Value); //get it's date
if (changesetDate < latestDate)
//destroy
ExecuteCommand(string.Format("destroy \"{0}/{1}\" /recursive /stopafter:1 /startcleanup /noprompt /silent", _tfProject, branch));
}
}
//execute console command and get results
private static string ExecuteCommand(string command)
{
var process = new Process()
{
StartInfo = new ProcessStartInfo(_tfLocation)
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
Arguments = command
},
};
process.Start();
var result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}

Winforms ReportViewer passing null for parameters even when the parameters are set

Even though I set the parameters in the code, I keep getting that a parameter must be set error. I have run profiler to see what is being passed to SSRS, and profiler indicates that parameters = null. Yet all of them are set in code. Anyone have any ideas? The code is as follows:
string strReportPath;
Microsoft.Reporting.WinForms.ReportParameter prmFranchiseOID;
Microsoft.Reporting.WinForms.ReportParameter prmSchoolOID;
Microsoft.Reporting.WinForms.ReportParameter prmRoomOID;
Microsoft.Reporting.WinForms.ReportParameter prmOrderDate;
Microsoft.Reporting.WinForms.ReportParameter prmLanguage;
Microsoft.Reporting.WinForms.ReportParameter prmContrast;
List<Microsoft.Reporting.WinForms.ReportParameter> prms = new List<ReportParameter>();
byte[] pdf = null;
try
{
prmFranchiseOID = new Microsoft.Reporting.WinForms.ReportParameter("FranchiseOID", "8D126AA2-2E5C-4B2B-8D19-167027F8C7D8");
prmSchoolOID = new Microsoft.Reporting.WinForms.ReportParameter("SchoolOID", "96FEE335-0CB9-413A-9DDC-78F8C67770C4");
prmRoomOID = new Microsoft.Reporting.WinForms.ReportParameter("RoomOID", "null");
prmOrderDate = new Microsoft.Reporting.WinForms.ReportParameter("OrderDate", DateTime.Now.AddDays(1).Date.ToString());
prmLanguage = new Microsoft.Reporting.WinForms.ReportParameter("Language", "en-CA");
prmContrast = new Microsoft.Reporting.WinForms.ReportParameter("Contrast", "true");
prms.Add(prmFranchiseOID);
prms.Add(prmSchoolOID);
prms.Add(prmRoomOID);
prms.Add(prmOrderDate);
prms.Add(prmLanguage);
prms.Add(prmContrast);
// Note: For Account Holder users, their specified report folder is "/LunchLady/User".
strReportPath = "/LunchLady/Franchise/" + urlReportName;
try
{
rvReport.ServerReport.ReportServerUrl = new System.Uri("https://testsql.thelunchlady.ca/ReportServer");
rvReport.ServerReport.ReportPath = strReportPath;
rvReport.ServerReport.SetParameters(prms);
string ReportType = "PDF";
pdf = rvReport.ServerReport.Render(ReportType);
Thanks
Having done extensive programming on the SSRS controls in ASP.NET, one thing that I've found which may or may not be relevant for WinForms is that each SSRS parameter is actually a collection in itself (due to parameters being able to be multi-select).
So what worked for us is that the collection (prms in your case) was of type
List<IEnumerable<ReportViewer.ReportParameter>> prms
Also when adding parameters using the SetParameters function we added them one at a time:
for (int i = 0; i < prms.Count; i++)
{
rvReport.ServerReport.SetParameters(prms[i]);
}
Again, this is what worked for us in ASP.NET, could be something for you to try.

Printing a WPF FlowDocument

I'm building a demo app in WPF, which is new to me. I'm currently displaying text in a FlowDocument, and need to print it.
The code I'm using looks like this:
PrintDialog pd = new PrintDialog();
fd.PageHeight = pd.PrintableAreaHeight;
fd.PageWidth = pd.PrintableAreaWidth;
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;
IDocumentPaginatorSource dps = fd;
pd.PrintDocument(dps.DocumentPaginator, "flow doc");
fd is my FlowDocument, and for now I'm using the default printer instead of allowing the user to specify print options. It works OK, except that after the document prints, the FlowDocument displayed on screen has changed to to use the settings I specified for printing.
I can fix this by manually resetting everything after I print, but is this the best way? Should I make a copy of the FlowDocument before I print it? Or is there another approach I should consider?
yes, make a copy of the FlowDocument before printing it. This is because the pagination and margins will be different. This works for me.
private void DoThePrint(System.Windows.Documents.FlowDocument document)
{
// Clone the source document's content into a new FlowDocument.
// This is because the pagination for the printer needs to be
// done differently than the pagination for the displayed page.
// We print the copy, rather that the original FlowDocument.
System.IO.MemoryStream s = new System.IO.MemoryStream();
TextRange source = new TextRange(document.ContentStart, document.ContentEnd);
source.Save(s, DataFormats.Xaml);
FlowDocument copy = new FlowDocument();
TextRange dest = new TextRange(copy.ContentStart, copy.ContentEnd);
dest.Load(s, DataFormats.Xaml);
// Create a XpsDocumentWriter object, implicitly opening a Windows common print dialog,
// and allowing the user to select a printer.
// get information about the dimensions of the seleted printer+media.
System.Printing.PrintDocumentImageableArea ia = null;
System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia);
if (docWriter != null && ia != null)
{
DocumentPaginator paginator = ((IDocumentPaginatorSource)copy).DocumentPaginator;
// Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
Thickness t = new Thickness(72); // copy.PagePadding;
copy.PagePadding = new Thickness(
Math.Max(ia.OriginWidth, t.Left),
Math.Max(ia.OriginHeight, t.Top),
Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), t.Right),
Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), t.Bottom));
copy.ColumnWidth = double.PositiveInfinity;
//copy.PageWidth = 528; // allow the page to be the natural with of the output device
// Send content to the printer.
docWriter.Write(paginator);
}
}
You can use the code from the URL below, it wraps the flow document in a fixed document and prints that, the big advantage is that you can use it to add margin, headers and footers.
https://web.archive.org/web/20150502085246/http://blogs.msdn.com:80/b/fyuan/archive/2007/03/10/convert-xaml-flow-document-to-xps-with-style-multiple-page-page-size-header-margin.aspx
The following works with both text and non-text visuals:
//Clone the source document
var str = XamlWriter.Save(FlowDoc);
var stringReader = new System.IO.StringReader(str);
var xmlReader = XmlReader.Create(stringReader);
var CloneDoc = XamlReader.Load(xmlReader) as FlowDocument;
//Now print using PrintDialog
var pd = new PrintDialog();
if (pd.ShowDialog().Value)
{
CloneDoc.PageHeight = pd.PrintableAreaHeight;
CloneDoc.PageWidth = pd.PrintableAreaWidth;
IDocumentPaginatorSource idocument = CloneDoc as IDocumentPaginatorSource;
pd.PrintDocument(idocument.DocumentPaginator, "Printing FlowDocument");
}
I am also generating a WPF report off a Flow document, but I am purposely using the flow document as a print preview screen. I there for want the margins to be the same. You can read about how I did this here.
In your scenario I'm thinking why not just make a copy of your settings, instead of the entire flow document. You can then re-apply the settings if you wish to return the document back to it's original state.

Resources