Last active
August 29, 2015 14:25
-
-
Save bjoerntx/6ae5a1c9da161c936e94 to your computer and use it in GitHub Desktop.
DataSelector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DataSelector | |
// description: This class loops through all merge blocks in a given template to check | |
// for sort keywords. The given referenced DataSet will be sorted. | |
// | |
// Parameters: dataSet of type DataSet, template as a byte[] array in the InternalUnicodeFormat | |
public class DataSelector | |
{ | |
public byte[] Template { get; set; } | |
public DataSelector(DataSet dataSet, byte[] template) | |
{ | |
// use a temporary ServerTextControl instance to recognize blocks with | |
// the sorting keyword 'ORDERBY' | |
using (TXTextControl.ServerTextControl tx = | |
new TXTextControl.ServerTextControl()) | |
{ | |
tx.Create(); | |
// load the template | |
tx.Load(template, TXTextControl.BinaryStreamType.InternalUnicodeFormat); | |
// create a list of merge blocks | |
List<MergeBlock> lMergeBlocks = MergeBlock.GetMergeBlocks(MergeBlock.GetBlockMarkersOrdered(tx), tx); | |
// loop through all merge blocks to check whether they | |
// have a sorting parameter | |
foreach (MergeBlock mergeBlock in lMergeBlocks) | |
{ | |
string sBlockName = mergeBlock.StartMarker.TargetName; | |
// check for the unique sorting parameter | |
if (sBlockName.ToUpper().Contains("ORDERBY") == false) | |
continue; | |
// create a new SortedBlock object to store parameter | |
SortedBlock block = new SortedBlock(sBlockName); | |
// remove the sorting parameter from the block name | |
// so that MailMerge can find the matching data in the data source | |
mergeBlock.StartMarker.TargetName = block.Name; | |
mergeBlock.EndMarker.TargetName = "BlockEnd_" + mergeBlock.Name; | |
if (dataSet.Tables.Contains(mergeBlock.Name) == false) | |
continue; | |
// get all DataRows using LINQ | |
var query = from product in dataSet.Tables[mergeBlock.Name].AsEnumerable() | |
select product; | |
// create a new DataTable with the sorted DataRows | |
DataTable dtBoundTable = (block.SortType == SortType.ASC) ? | |
query.OrderBy(product => product.Field<String>(block.ColumnName)).CopyToDataTable() : | |
query.OrderByDescending(product => product.Field<String>(block.ColumnName)).CopyToDataTable(); | |
// remove original rows and replace with sorted rows | |
dataSet.Tables[mergeBlock.Name].Rows.Clear(); | |
dataSet.Tables[mergeBlock.Name].Merge(dtBoundTable); | |
dtBoundTable.Dispose(); | |
} | |
// save the template | |
byte[] data = null; | |
tx.Save(out data, TXTextControl.BinaryStreamType.InternalUnicodeFormat); | |
this.Template = data; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment