Skip to content

Commit

Permalink
Added option to convert FetchXML to SQL using native conversion message
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkMpn committed Dec 11, 2021
1 parent 5caaff3 commit 285d3d1
Show file tree
Hide file tree
Showing 7 changed files with 205 additions and 17 deletions.
28 changes: 23 additions & 5 deletions MarkMpn.Sql4Cds.SSMS/FetchXml2SqlCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.SqlServer.Management.UI.VSIntegration.Editors;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;
using Microsoft.VisualStudio.Shell;
using Microsoft.Xrm.Sdk;
using Task = System.Threading.Tasks.Task;

namespace MarkMpn.Sql4Cds.SSMS
Expand Down Expand Up @@ -132,12 +133,29 @@ private void Execute(object sender, EventArgs e)

_ai.TrackEvent("Convert", new Dictionary<string, string> { ["QueryType"] = "FetchXML", ["Source"] = "SSMS" });

var sql = FetchXml2Sql.Convert(ConnectCDS(conStr), GetMetadataCache(conStr), fetch, new FetchXml2SqlOptions
string sql;
IDictionary<string, object> paramValues;

if (Package.Settings.UseNativeSqlConversion)
{
var convertReq = new OrganizationRequest("FetchXMLToSQL")
{
["FetchXml"] = fetch,
["SubqueryCompatible"] = true
};
var convertResp = ConnectCDS(conStr).Execute(convertReq);
sql = (string)convertResp["Response"];
paramValues = new Dictionary<string, object>();
}
else
{
ConvertFetchXmlOperatorsTo = FetchXmlOperatorConversion.SqlCalculations,
UseParametersForLiterals = true,
ConvertDateTimeToUtc = true
}, out var paramValues);
sql = FetchXml2Sql.Convert(ConnectCDS(conStr), GetMetadataCache(conStr), fetch, new FetchXml2SqlOptions
{
ConvertFetchXmlOperatorsTo = FetchXmlOperatorConversion.SqlCalculations,
UseParametersForLiterals = true,
ConvertDateTimeToUtc = true
}, out paramValues);
}

ServiceCache.ScriptFactory.CreateNewBlankScript(ScriptType.Sql, ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo, null);

Expand Down
6 changes: 6 additions & 0 deletions MarkMpn.Sql4Cds.SSMS/OptionsPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ public class OptionsPage : DialogPage
[DefaultValue(false)]
public bool BypassCustomPlugins { get; set; }

[Category("Behavior")]
[DisplayName("Use native FetchXML to SQL Conversion")]
[Description("Converts FetchXML to SQL using the same conversion logic as the Dynamics server. Generates more complex queries.")]
[DefaultValue(false)]
public bool UseNativeSqlConversion { get; set; }

[Category("Version")]
[DisplayName("Installed")]
[Description("Installed version of SQL 4 CDS - SSMS Edition")]
Expand Down
24 changes: 23 additions & 1 deletion MarkMpn.Sql4Cds/PluginControl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,29 @@ public void OnIncomingMessage(MessageBusEventArgs message)

_ai.TrackEvent("Convert", new Dictionary<string, string> { ["QueryType"] = "FetchXML", ["Source"] = "XrmToolBox" });

var sql = FetchXml2Sql.Convert(con.ServiceClient, metadata, fetch, options, out _);
string sql;

if (Settings.Instance.UseNativeSqlConversion)
{
try
{
var convertReq = new OrganizationRequest("FetchXMLToSQL")
{
["FetchXml"] = xmlStr,
["SubqueryCompatible"] = true
};
var convertResp = con.ServiceClient.Execute(convertReq);
sql = (string) convertResp["Response"];
}
catch
{
sql = FetchXml2Sql.Convert(con.ServiceClient, metadata, fetch, options, out _);
}
}
else
{
sql = FetchXml2Sql.Convert(con.ServiceClient, metadata, fetch, options, out _);
}

if ((bool)param["ConvertOnly"])
{
Expand Down
2 changes: 2 additions & 0 deletions MarkMpn.Sql4Cds/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public class Settings
public TabContent[] Session { get; set; }

public bool LocalFormatDates { get; set; }

public bool UseNativeSqlConversion { get; set; }
}

public class TabContent
Expand Down
107 changes: 96 additions & 11 deletions MarkMpn.Sql4Cds/SettingsForm.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 44 additions & 0 deletions MarkMpn.Sql4Cds/SettingsForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ScintillaNET;

namespace MarkMpn.Sql4Cds
{
Expand Down Expand Up @@ -37,10 +38,52 @@ public SettingsForm(Settings settings)
autoSizeColumnsCheckBox.Checked = settings.AutoSizeColumns;
rememberSessionCheckbox.Checked = settings.RememberSession;
localDateFormatCheckbox.Checked = settings.LocalFormatDates;
simpleSqlRadioButton.Checked = !settings.UseNativeSqlConversion;
nativeSqlRadioButton.Checked = settings.UseNativeSqlConversion;

SetSqlStyle(simpleSqlScintilla);
SetSqlStyle(nativeSqlScintilla);

_settings = settings;
}

private void SetSqlStyle(Scintilla scintilla)
{
scintilla.StyleResetDefault();
scintilla.Styles[Style.Default].Font = "Courier New";
scintilla.Styles[Style.Default].Size = 10;
scintilla.StyleClearAll();

scintilla.Lexer = Lexer.Sql;

// Set the Styles
scintilla.Styles[Style.LineNumber].ForeColor = Color.FromArgb(255, 128, 128, 128); //Dark Gray
scintilla.Styles[Style.LineNumber].BackColor = Color.FromArgb(255, 228, 228, 228); //Light Gray
scintilla.Styles[Style.Sql.Comment].ForeColor = Color.Green;
scintilla.Styles[Style.Sql.CommentLine].ForeColor = Color.Green;
scintilla.Styles[Style.Sql.CommentLineDoc].ForeColor = Color.Green;
scintilla.Styles[Style.Sql.Number].ForeColor = Color.Maroon;
scintilla.Styles[Style.Sql.Word].ForeColor = Color.Blue;
scintilla.Styles[Style.Sql.Word2].ForeColor = Color.Fuchsia;
scintilla.Styles[Style.Sql.User1].ForeColor = Color.Gray;
scintilla.Styles[Style.Sql.User2].ForeColor = Color.FromArgb(255, 00, 128, 192); //Medium Blue-Green
scintilla.Styles[Style.Sql.String].ForeColor = Color.Red;
scintilla.Styles[Style.Sql.Character].ForeColor = Color.Red;
scintilla.Styles[Style.Sql.Operator].ForeColor = Color.Black;

// Set keyword lists
// Word = 0
scintilla.SetKeywords(0, @"add alter as authorization backup begin bigint binary bit break browse bulk by cascade case catch check checkpoint close clustered column commit compute constraint containstable continue create current cursor cursor database date datetime datetime2 datetimeoffset dbcc deallocate decimal declare default delete deny desc disk distinct distributed double drop dump else end errlvl escape except exec execute exit external fetch file fillfactor float for foreign freetext freetexttable from full function goto grant group having hierarchyid holdlock identity identity_insert identitycol if image index insert int intersect into key kill lineno load merge money national nchar nocheck nocount nolock nonclustered ntext numeric nvarchar of off offsets on open opendatasource openquery openrowset openxml option order over percent plan precision primary print proc procedure public raiserror read readtext real reconfigure references replication restore restrict return revert revoke rollback rowcount rowguidcol rule save schema securityaudit select set setuser shutdown smalldatetime smallint smallmoney sql_variant statistics table table tablesample text textsize then time timestamp tinyint to top tran transaction trigger truncate try union unique uniqueidentifier update updatetext use user values varbinary varchar varying view waitfor when where while with writetext xml go ");
// Word2 = 1
scintilla.SetKeywords(1, @"ascii cast char charindex ceiling coalesce collate contains convert current_date current_time current_timestamp current_user floor isnull max min nullif object_id session_user substring system_user tsequal ");
// User1 = 4
scintilla.SetKeywords(4, @"all and any between cross exists in inner is join left like not null or outer pivot right some unpivot ( ) * ");
// User2 = 5
scintilla.SetKeywords(5, @"sys objects sysobjects ");

scintilla.ReadOnly = true;
}

protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
Expand All @@ -66,6 +109,7 @@ protected override void OnClosing(CancelEventArgs e)
_settings.AutoSizeColumns = autoSizeColumnsCheckBox.Checked;
_settings.RememberSession = rememberSessionCheckbox.Checked;
_settings.LocalFormatDates = localDateFormatCheckbox.Checked;
_settings.UseNativeSqlConversion = nativeSqlRadioButton.Checked;
}
}

Expand Down
11 changes: 11 additions & 0 deletions MarkMpn.Sql4Cds/SettingsForm.resx
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,15 @@
/w/8fxutOvwPHAnkbuvmv/8AAAAASUVORK5CYII=
</value>
</data>
<data name="nativeSqlScintilla.Text" xml:space="preserve">
<value>select
"account0".Name as "name"
, "account0".Telephone1 as "telephone1"
, "account0".OwnerIdName as "owneridname"
, "account0".OwnerId as "ownerid"
, "account0".OwnerIdType as "owneridtype"
, "account0".OwnerIdYomiName as "owneridyominame"
from
Account as "account0"</value>
</data>
</root>

0 comments on commit 285d3d1

Please sign in to comment.