VS 2012 SSDT build CLR with IEnumerable failing on generated syntax - sql-server

I'm attempting to reuse some code found here. After adding a new using the c# (shown below) seems to be fine.
When I go to publish the database, however, the code generator does not seem to recognize the IEnumerable type and ends up producing an error. The actual error (Incorrect Syntax near AS) from the generated code below is obvious, so my question is how can I get SSDT to generate the correct code and avoid the cause of the error? (I assume that I can add the CLR manually, however, I would prefer to do everything from SSDT)
Currently Generates:
CREATE FUNCTION [dbo].[RegExMatches] (#sourceString [nvarchar](4000), #pattern [nvarchar](4000))
RETURNS /* Error: Unsupported type. */
AS EXTERNAL NAME [CampaignStrategyStaging].[SQLRegEx].[RegExMatches];
Should Generate something like:
CREATE FUNCTION [dbo].[RegExMatches] (#sourceString [nvarchar](4000), #pattern [nvarchar](4000))
RETURNS TABLE (
[rowId] int, --RowId each row as it`s ID
[matchId] int, --ID of particular match (starts from 1)
[groupId] int, --ID of particular group in RegEx match (GroupID = 0) represents a complete match
[value] nvarchar(4000) --value of the group
) WITH EXECUTE AS CALLER
AS EXTERNAL NAME [CampaignStrategyStaging].[SQLRegEx].[RegExMatches];
The C# for the CLR:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;
using System.Collections;
public class SQLRegEx
{
private class RegExRow
{
/// <summary>
/// Private class for passing matches of the RegExMatches to the FillRow method
/// </summary>
/// <param name=”rowId”>ID of the Row</param>
/// <param name=”matchId”>ID of the Match</param>
/// <param name=”groupID”>ID of the Group within the Match</param>
/// <param name=”value”>Value of the particular group</param>
public RegExRow(int rowId, int matchId, int groupID, string value)
{
RowId = rowId;
MatchId = matchId;
GroupID = groupID;
Value = value;
}
public int RowId;
public int MatchId;
public int GroupID;
public string Value;
}
/// <summary>
/// Applies Regular Expression on the Source string and returns value of particular group from withing a specified match
/// </summary>
/// <param name=”sourceString”>Source string on which the regular expression should be applied</param>
/// <param name=”pattern”>Regular Expression pattern</param>
/// <param name=”matchId”>ID of the Match to be returned 1 inex-based</param>
/// <param name=”groupId”>ID of the group from within a match to return. GroupID 0 returns complete match</param>
/// <returns>Value of the Group from within a Match</returns>
[SqlFunction(IsDeterministic=true)]
public static SqlChars RegExMatch(string sourceString, string pattern, int matchId, int groupId)
{
Match m = null;
Regex r = new Regex(pattern, RegexOptions.Compiled);
if (matchId == 1)
{
m = r.Match(sourceString);
}
else if (matchId > 1)
{
MatchCollection mc = r.Matches(sourceString);
if (mc!=null && mc.Count > matchId-1)
{
m = mc[matchId-1];
}
else
{
m= null;
}
///m = mc != null && mc.Count > matchId – 1 ? mc[matchId - 1] : null;
}
return m != null && m.Groups.Count > groupId ? new SqlChars(m.Groups[groupId].Value) : SqlChars.Null;
}
/// <summary>
/// Applies Regular Expression o the Source strings and return all matches and groups
/// </summary>
/// <param name=”sourceString”>Source string on which the regular expression should be applied</param>
/// <param name=”pattern”>Regular Expression pattern</param>
/// <returns>Returns list of RegExRows representing the group value</returns>
[SqlFunction(FillRowMethodName = "FillRegExRow")]
public static IEnumerable RegExMatches(string sourceString, string pattern)
{
Regex r = new Regex(pattern, RegexOptions.Compiled);
int rowId = 0;
int matchId = 0;
foreach (Match m in r.Matches(sourceString))
{
matchId++;
for (int i = 0; i < m.Groups.Count; i++)
{
yield return new RegExRow(++rowId, matchId, i, m.Groups[i].Value);
}
}
}
/// <summary>
/// FillRow method to populate the output table
/// </summary>
/// <param name=”obj”>RegExRow passed as object</param>
/// <param name=”rowId”>ID or the returned row</param>
/// <param name=”matchId”>ID of returned Match</param>
/// <param name=”groupID”>ID of group in the Match</param>
/// <param name=”value”>Value of the Group</param>
public static void FillRegExRow(Object obj, out int rowId, out int matchId, out int groupID, out SqlChars value)
{
RegExRow r = (RegExRow)obj;
rowId = r.RowId;
matchId = r.MatchId;
groupID = r.GroupID;
value = new SqlChars(r.Value);
}
}

After some help from a co-worker I discovered that two changes were needed in the CLR:
the SQLFunction[] declaration needed to include a TableDefinition
argument as shown in the example on here. (code is shown below)
[SqlFunction(FillRowMethodName = "FillRegExRow",
TableDefinition = "[rowId] int,[matchId] int,[groupId] int, [value] nvarchar(4000)")]
public static IEnumerable RegExMatches(string sourceString, string pattern)
int data types in RegExRow.RegExRow were changed to SqlInt32. (This might not have been necessary to resolve the issue in my original question).
So the overall code changed to:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;
using System.Collections;
public class SQLRegEx
{
private class RegExRow
{
/// <summary>
/// Private class for passing matches of the RegExMatches to the FillRow method
/// </summary>
/// <param name=”rowId”>ID of the Row</param>
/// <param name=”matchId”>ID of the Match</param>
/// <param name=”groupID”>ID of the Group within the Match</param>
/// <param name=”value”>Value of the particular group</param>
public RegExRow(SqlInt32 rowId, SqlInt32 matchId, SqlInt32 groupID, string value)
{
RowId = rowId;
MatchId = matchId;
GroupID = groupID;
Value = value;
}
public SqlInt32 RowId;
public SqlInt32 MatchId;
public SqlInt32 GroupID;
public string Value;
}
/// <summary>
/// Applies Regular Expression on the Source string and returns value of particular group from withing a specified match
/// </summary>
/// <param name=”sourceString”>Source string on which the regular expression should be applied</param>
/// <param name=”pattern”>Regular Expression pattern</param>
/// <param name=”matchId”>ID of the Match to be returned 1 inex-based</param>
/// <param name=”groupId”>ID of the group from within a match to return. GroupID 0 returns complete match</param>
/// <returns>Value of the Group from within a Match</returns>
[SqlFunction(IsDeterministic=true)]
public static SqlChars RegExMatch(string sourceString, string pattern, int matchId, int groupId)
{
Match m = null;
Regex r = new Regex(pattern, RegexOptions.Compiled);
if (matchId == 1)
{
m = r.Match(sourceString);
}
else if (matchId > 1)
{
MatchCollection mc = r.Matches(sourceString);
if (mc!=null && mc.Count > matchId-1)
{
m = mc[matchId-1];
}
else
{
m= null;
}
///m = mc != null && mc.Count > matchId – 1 ? mc[matchId - 1] : null;
}
return m != null && m.Groups.Count > groupId ? new SqlChars(m.Groups[groupId].Value) : SqlChars.Null;
}
/// <summary>
/// Applies Regular Expression o the Source strings and return all matches and groups
/// </summary>
/// <param name=”sourceString”>Source string on which the regular expression should be applied</param>
/// <param name=”pattern”>Regular Expression pattern</param>
/// <returns>Returns list of RegExRows representing the group value</returns>
///
[SqlFunction(FillRowMethodName = "FillRegExRow",
TableDefinition = "rowId int,[matchId] int,[groupId] int, [value] nvarchar(4000)")]
public static IEnumerable RegExMatches(string sourceString, string pattern)
{
Regex r = new Regex(pattern, RegexOptions.Compiled);
int rowId = 0;
int matchId = 0;
foreach (Match m in r.Matches(sourceString))
{
matchId++;
for (int i = 0; i < m.Groups.Count; i++)
{
++rowId;
yield return new RegExRow(rowId, matchId, i, m.Groups[i].Value);
}
}
}
/// <summary>
/// FillRow method to populate the output table
/// </summary>
/// <param name=”obj”>RegExRow passed as object</param>
/// <param name=”rowId”>ID or the returned row</param>
/// <param name=”matchId”>ID of returned Match</param>
/// <param name=”groupID”>ID of group in the Match</param>
/// <param name=”value”>Value of the Group</param>
public static void FillRegExRow(Object obj, out SqlInt32 rowId, out SqlInt32 matchId, out SqlInt32 groupID, out SqlChars value)
{
RegExRow r = (RegExRow)obj;
rowId = r.RowId;
matchId = r.MatchId;
groupID = r.GroupID;
value = new SqlChars(r.Value);
}
}

Related

How to use Predicate with Generic Repository

I am following this tutorial
https://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application?msg=5635950#xx5635950xx
He explains simple thing very well but as a beginner difficult for me to understand the implementation of the advanced function of Generic Repository
public virtual IEnumerable<TEntity> GetMany(Func<TEntity, bool>
where)
{
return DbSet.Where(where).ToList();
}
/// <summary>
/// generic method to get many record on the basis of a condition but
query able.
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual IQueryable<TEntity> GetManyQueryable(Func<TEntity,
bool> where)
{
return DbSet.Where(where).AsQueryable();
}
/// <summary>
/// generic get method , fetches data for the entities on the basis of
condition.
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public TEntity Get(Func<TEntity, Boolean> where)
{
return DbSet.Where(where).FirstOrDefault<TEntity>();
}
I implement like this in my Service file
public GEN_TransactionTypeSetup GetTransactionIdByTableName(string
tableName)
{
IEnumerable<GEN_TransactionTypeSetup> list =
_unitOfWorks.TransactionType_Repository.GetMany(p =>
p.Master_TableName = tableName);
return list.ToList();
}
and i get the following error
Cannot implicitly convert type 'string' to 'bool'
Cannot convert lambda expression to delegate type
'System.Func' because some
of the return types in the block are not implicitly convertible to
the delegate return type
Cannot implicitly convert type
'System.Collections.Generic.List'
to 'DataModels.GEN_TransactionTypeSetup'
You'll be able to use the predicate in function of the TEntity type in your implementation.
Let's say your TEntity is Person (GenericRepository<Person>) and your Person has a property Age, which is an int.
You'll then be able to say:
IEnumerable<Person> result = repository.GetMany(p => p.Age > 18);
As you see, this (generic) method returns an IEnumerable<TEntity>, meaning you can apply (and chain) other Linq methods to your result.
Also note that the ToList() in
return DbSet.Where(where).ToList();
is superfluous and, in large resultsets, might create significant overhead because the method returns an IEnumerable<TEntity> and so already does a Linq .Where().

What is Equal SQL Function or StoredProcedure for my C# Method

I have this C# Method that Determine that a point is inside a polygon or not
C# Method is this:
/// <summary>
/// Determine that a point in inside a polygon or not
/// </summary>
/// <param name="points">Points of Polygon</param>
/// <param name="point">Test Point</param>
/// <returns></returns>
Public bool IsInside(List<PointF> points,PointF point )
{
int i, j,n=points.Count;
bool c = false;
for (i = 0, j = n - 1; i < n; j = i++)
{
if (((points[i].Y > point.Y) != (points[j].Y > point.Y)) &&
(point.X <
(points[j].X - points[i].X)*(point.Y - points[i].Y)/(points[j].Y - points[i].Y) + points[i].X))
c = !c;
}
return c;
}
How can i convert this to a SQL Function or StoredProcedure?
If you have all your polygons stored in your SQL Server database as spatial geometry data types, you can use the spatial functions available in SQL Server 2008R2+ of which there are many (Google is your friend here):
declare #g geometry
set #g = geometry::STGeomFromText('POLYGON((-33.229869 -70.891988
,-33.251124 -70.476616
,-33.703094 -70.508045
,-33.693931 -70.891052
,-33.229869 -70.891988
))'
,0)
DECLARE #h geometry;
SET #h = geometry::STGeomFromText('POINT(-33.3906300 -70.5725020)', 0);
SELECT #g.STContains(#h);

Can i serialize and deserialize a DataRowView from a WPF ComboBox?

I'm filling the itemssource of a WPF combobox in code-behind with a datatable containing the columns "Listkey" and "Listvalue" like that:
SetElementProperty(element, "ItemsSource", (new ListtablesRead()).ReadListtable(changeTextProperties.SelectedListTable).DefaultView);
SetElementProperty(element, "DisplayMemberPath", "Listvalue");
SetElementProperty(element, "SelectedValuePath", "Listkey");
SetElementProperty is a method which checks by reflection, if the frameworkelement (in that case the combobox) has the given property and sets it.
Then i want to serialize the control with XmlWriter.
So i wrote a converter class for the type DataRowView:
using System;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Markup;
namespace WPFDesignerConverterLibrary
{
public class DataRowViewConverter : ExpressionConverter
{
/// <summary>
/// Finds out if the converter can convert an expression-object to the given destinationtype.
/// </summary>
/// <param name="context">An ITypeDescriptorContext-interface which provides a context for formatting.</param>
/// <param name="destinationType">A type-class which represents the target-type of the conversion.</param>
/// <returns>Returns an object of type bool. True = the destinationtype can be converted.</returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(MarkupExtension))
return true;
return false;
}
/// <summary>
/// Converts the expression to the given destinationtype.
/// </summary>
/// <param name="context">An ITypeDescriptorContext-interface which provides a context for formatting.</param>
/// <param name="culture">The System.Globalization.CultureInfo which is actually used as culture.</param>
/// <param name="value">The object to convert.</param>
/// <param name="destinationType">A type-class which represents the target-type of the conversion.</param>
/// <returns></returns>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value,
Type destinationType)
{
if (destinationType == typeof(MarkupExtension))
{
DataRowView datarowview = value as DataRowView;
if (datarowview == null)
throw new Exception();
return datarowview.Row;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
This converter works and produces the following lines in the serialized XML:
<sd:DataRow RowError="">
<sd:DataRow.ItemArray>
<x:Array Type="s:Object" xml:space="preserve"><s:String>01</s:String><s:String>Ersttest </s:String></x:Array>
</sd:DataRow.ItemArray>
</sd:DataRow>
<sd:DataRow RowError="">
<sd:DataRow.ItemArray>
<x:Array Type="s:Object" xml:space="preserve"><s:String>02</s:String><s:String>Wiederholungstest </s:String></x:Array>
</sd:DataRow.ItemArray>
</sd:DataRow>
<sd:DataRow RowError="">
<sd:DataRow.ItemArray>
<x:Array Type="s:Object" xml:space="preserve"><s:String>03</s:String><s:String>Konstanzprüfung </s:String></x:Array>
</sd:DataRow.ItemArray>
</sd:DataRow>
But when i try to reload the serialized XML i get an error message, which says, that no standard constructor for the type DataRow was found.
What's going wrong?
And further: To set the itemssource of the combobox with a datatable's defaultview is the simplest way to do this, but can it be that i have to go another way?
InnerException:
=-2146233069 HResult
Message=For the type "System. Data. DataRow" no standard constructor was found. The type can be provided with the argument or the FactoryMethod directive.
Source=System. Xaml
StackTrace:
at system. Xaml. Pattern. XamlTypeInvoker. DefaultCtorXamlActivator. EnsureConstructorDelegate (XamlTypeInvoker type)
at system. Xaml. Pattern. XamlTypeInvoker. CreateInstance (Object [] of argument)
at MS.Internal. Xaml. Run time. ClrObjectRuntime. CreateInstanceWithCtor (XamlType xamlType, Object [] args)
at MS.Internal. Xaml. Run time. ClrObjectRuntime. CreateInstance (XamlType xamlType, Object [] args)
Meanwhile i have found another way.
I'm using a dummy-class called KeyAndValue:
/// <summary>
/// Dummy class with key and value properties for construction of comboboxitems.
/// </summary>
public class KeyAndValue
{
/// <summary>
/// Gets or sets the key.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets or sets the value.
/// </summary>
public string Value { get; set; }
}
That class helps to fill the items-collection of the combobox:
foreach (System.Data.DataRow row in table.Rows)
{
// Add new pairs with Listkey and Listvalue as content to the Items-collection.
customComboBox.Items.Add(new KeyAndValue() { Key = row["Listkey"].ToString(), Value = row["Listvalue"].ToString() });
}
That's a little bit like using KeyValuePair with one diffenrence: A generic list like KeyValuePair cannot be serialized.
But my dummy-class does it.
What you need is to have a class with parameterless contrsuctor aka Default Constructor that will allow Serialization.
Step 1.
Create a class to hold your database results.
You can do this through manual code or you could use DataSet.
Step 2.
After you created the class or used the dataset serialize it.
FileStream fs = new FileStream(savePath + "\\" + a.Location + ".bin", FileMode.Create);
BinaryFormatter serializer = new BinaryFormatter();
try
{
serializer.Serialize(fs, a);
}
catch (Exception e)
{
//handle your fail;
}
finally
{
fs.Close();
}
or deserialize it:
List<Model.YOURCLASS> _l = new List<Model.YOURCLASS>();
string[] files = Directory.GetFiles(pathToSearch);
FileStream fs;
BinaryFormatter deserializer = new BinaryFormatter();
foreach (var a in files)
{
if(Path.GetExtension(a) == ".bin")
{
fs = new FileStream(a, FileMode.Open);
_l.Add((Model.YOURCLASS)deserializer.Deserialize(fs));
}
}
return _l;
The type that your routine returns doesn't have to be a DataTable your ListView will automatically use any collection you pass it, even an array[]

Extracting a subset of DataTable columns in C# and then sending them to browser client as a JSON string

Here's the scenario: C# middle tier webservice has the data sent from SQL Server in a System.Data.DataTable object. There are dozens of columns in the DataTable's columns collection. The browser client only needs to see about six of them. The stored proc on the server is general purpose, not designed for this specific task. Assume we have to use it, rather than writing a new SP.
Is there a simple way, perhaps using generics, to extract the desired subset of columns from that DataTable into a List or a Collection, and then convert the resulting list or collection to JSON using JSON.NET?
Is it possible to create a skeletal C# class definition foo with the relevant field names (and datatypes) and then match on those field names "automagically" and thereby generate a List<foo> from the DataTable's rows collection?
Ideally, during the JSON conversion, any SQL Server datetime values (e.g. 2014-06-24T18:45:00) would be converted to a value that would make it easy to instantiate a javascript Date in the client without having to do string manipulation of the date representation.
Full working Console App code pasted below. But the 2 main methods you need are as follows.
For this code to work, you will have to do the following in your Project.
Add the JSON.Net Nuget Package to the Project.
Add a reference to System.Web.Extensions (if you get a compile error in the line where System.Web.Script.Serialization.JavaScriptSerializer is being referenced in the GetJson method.
/// <summary>
/// Returns Json representation of Generic class with only matching properties from the DataTable (passed as parameter)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJsonFromDataTable<T>(DataTable dt) where T : new()
{
string json = GetJson(dt);
return JsonConvert.SerializeObject(JsonConvert.DeserializeObject<List<T>>(json));
}
/// <summary>
/// Returns a JSON string for entire DataTable (passed as parameter)
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = (from DataRow dr in dt.Rows select dt.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName.Trim(), col => dr[col])).ToList();
return serializer.Serialize(rows);
}
Fully working Console App code.
Create a new console App, and replace everything in the Program.cs with this code. Also add JSON.Net to the Console App Project and add the references to System.Web.Extensions.
namespace DataTable2Json
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
public class Patient
{
public string FullName { get; set; }
public string PatientID { get; set; }
public int NumberOfIllnesses { get; set; }
public DateTime DateAdmitted { get; set; }
}
public class PatientDrug
{
public string Patient { get; set; }
public string Drug { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
DataTable patientDrugDataTable = GetPatientDrugTable();
DataTable patientDataTable = GetPatientTable();
string patientDrugJson = GetJsonFromDataTable<PatientDrug>(patientDrugDataTable);
Console.WriteLine("Json for PatientDrug:\n{0}",patientDrugJson);
string patientJson = GetJsonFromDataTable<Patient>(patientDataTable);
Console.WriteLine("\nJson for Patient:\n{0}", patientJson);
Console.WriteLine("\n\nPress a key to Exit...");
Console.ReadKey();
}
private static DataTable GetPatientDrugTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
private static DataTable GetPatientTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("NumberOfIllnesses", typeof(int));
table.Columns.Add("PatientID", typeof(string));
table.Columns.Add("FullName", typeof(string));
table.Columns.Add("DateAdmitted", typeof(DateTime));
table.Columns.Add("StreetAddress1", typeof(string));
table.Columns.Add("City", typeof(string));
table.Columns.Add("State", typeof(string));
//
// Here we add five DataRows.
//
table.Rows.Add(2, "PAT-00001", "David", DateTime.Now, "1 Mill Ln", "Schenectady", "NY");
table.Rows.Add(1, "PAT-00002", "Sam", DateTime.Now, "1915 Boylston Steet", "Boston", "MA");
table.Rows.Add(3, "PAT-00003", "Christoff", DateTime.Now, "15 Polk Steet", "San Francisco", "CA");
table.Rows.Add(4, "PAT-00004", "Janet", DateTime.Now, "10 Waverly St", "Los Angeles", "CA");
table.Rows.Add(5, "PAT-00005", "Melanie", DateTime.Now, "50 Kapaa St", "Kailua", "HI");
return table;
}
/// <summary>
/// Returns Json representation of Generic class with only matching properties from the DataTable (passed as parameter)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJsonFromDataTable<T>(DataTable dt) where T : new()
{
string json = GetJson(dt);
return JsonConvert.SerializeObject(JsonConvert.DeserializeObject<List<T>>(json));
}
/// <summary>
/// Returns a JSON string for entire DataTable (passed as parameter)
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = (from DataRow dr in dt.Rows select dt.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName.Trim(), col => dr[col])).ToList();
return serializer.Serialize(rows);
}
}
}
Explanation of Code:
Notice I have 2 classes, Patient and PatientDrug.
I wrote helper methods to return data tables for both classes, that have additional columns.
Then the following 2 lines get the JSON for the class representation for Patient and PatientDrug respectively, while ignoring the additional data columns in DataTable that don't match names.
string patientDrugJson = GetJsonFromDataTable<PatientDrug>(patientDrugDataTable);
string patientJson = GetJsonFromDataTable<Patient>(patientDataTable);
Output in Console Windows (the json strings)

Excessive XAML markup size in Silverlight RichTextBox

I have a very simple RichTextBox control in a silverlight 5 application.
<RichTextBox x:Name="rtbControl"
Height="Auto"
ContentChanged="rtbControl_ContentChanged" />
As the data is changed, i capture it in a local variable as so:
private void rtbControl_ContentChanged(object sender, ContentChangedEventArgs e)
{
RichTextContent = rtbControl.Xaml;
}
All works. However, if I type in just a few words and examine the <Paragraph> markup, it is HUGE! A snippet is below. Is there a way to not have all the Typography stuff in the markup? Why is it there and is it needed? Is there a way to remove it?
<Section xml:space="preserve" HasTrailingParagraphBreakOnPaste="False" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Paragraph FontSize="11" FontFamily="Segoe UI" Foreground="#FF000000" FontWeight="Normal" FontStyle="Normal" FontStretch="Normal"
CharacterSpacing="0" Typography.AnnotationAlternates="0" Typography.EastAsianExpertForms="False" Typography.EastAsianLanguage="Normal"
Typography.EastAsianWidths="Normal" Typography.StandardLigatures="True" Typography.ContextualLigatures="True"
Typography.DiscretionaryLigatures="False" Typography.HistoricalLigatures="False" Typography.StandardSwashes="0" Typography.ContextualSwashes="0"
Typography.ContextualAlternates="True" Typography.StylisticAlternates="0" Typography.StylisticSet1="False" Typography.StylisticSet2="False"
Typography.StylisticSet3="False" Typography.StylisticSet4="False" Typography.StylisticSet5="False" Typography.StylisticSet6="False" Typography.StylisticSet7="False"
Typography.StylisticSet8="False" Typography.StylisticSet9="False" Typography.StylisticSet10="False" Typography.StylisticSet11="False"
Typography.StylisticSet12="False" Typography.StylisticSet13="False" Typography.StylisticSet14="False" Typography.StylisticSet15="False"
Typography.StylisticSet16="False" Typography.StylisticSet17="False" Typography.StylisticSet18="False" Typography.StylisticSet19="False"
Typography.StylisticSet20="False" Typography.Capitals="Normal" Typography.CapitalSpacing="False" Typography.Kerning="True" Typography.CaseSensitiveForms="False"
Typography.HistoricalForms="False" Typography.Fraction="Normal" Typography.NumeralStyle="Normal" Typography.NumeralAlignment="Normal" Typography.SlashedZero="False"
Typography.MathematicalGreek="False" Typography.Variants="Normal" TextOptions.TextHintingMode="Fixed" TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto" TextAlignment="Left" LineHeight="0" LineStackingStrategy="MaxHeight"><Run>was it a </Run><Run TextDecorations="Underline">bad
</Run><Run>blah? or </Run></Paragraph></section>
I thought I would share my solution to help others... its been in place for several months and I havent seen any bad side effects.
I created some extention methods to assist in removing the Typography attributes.
public static class RichTextBoxExtensions {
// <summary>
/// Removes any xml tag with the prefix given from a string
/// </summary>
/// <param name="XMLString"></param>
/// <param name="TagPrefix"></param>
/// <returns></returns>
public static string RemoveXMLAttributesFromNode(this string XMLString, string prefix)
{
//Match [Prefix][any number of Not =][=]["][any number of Not "]["][ ] <-must have space!!!
string replace = prefix + "[^\\=]*=\"[^\"]*\" ";
return Regex.Replace(XMLString, replace, string.Empty);
}
/// <summary>
/// Removes any xml tag with prefixed by an element in unWanted
/// </summary>
/// <param name="XMLString"></param>
/// <param name="TagPrefix"></param>
/// <returns></returns>
public static string RemoveXMLAttributesFromNode(this string XMLString, List<string> unWanted)
{
foreach (string prefix in unWanted)
{
//Match [Prefix][any number of Not =][=]["][any number of Not "]["][ ] <-must have space!!!
string replace = prefix + "[^\\=]*=\"[^\"]*\" ";
XMLString = Regex.Replace(XMLString, replace, string.Empty);
}
return XMLString;
}
Next, right before I save my string to the database, I remove the bad attributes as so:
List<string> badAttributes = new List<string>();
badAttributes.Add("Typography");
var ffText = ffi.FreeFormText == null ? null : ffi.FreeFormText.RemoveXMLAttributesFromNode(badAttributes);
I have not seen any issues when re-rendering the RTF after removing these attributes. Hope this solution helps someone!

Resources