├── README.md
├── LinqExpander
├── ExpandQueryableAttribute.cs
├── LinqExpander.nuspec
├── ReplaceWithExpressionAttribute.cs
├── AsExpandableExtension.cs
├── ExpandableQuery.cs
├── Properties
│ └── AssemblyInfo.cs
├── ExpandableQueryProvider.cs
├── ExpandableVisitor.cs
└── LinqExpander.csproj
├── LinqExpander.sln
├── LICENSE
└── .gitignore
/README.md:
--------------------------------------------------------------------------------
1 | # LinqExpander
2 | A way of expanding extension methods in your LINQ expressions so that it can be interperated by a third party who doesn't understand your extensions.
3 |
4 |
5 | [](https://ci.appveyor.com/project/lukemcgregor/linqexpander/branch/master)
6 |
7 |
--------------------------------------------------------------------------------
/LinqExpander/ExpandQueryableAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LinqExpander
4 | {
5 |
6 | ///
7 | /// Used in conjunction with the .AsExpandable() extention on a queryable this will take the extension method
8 | /// tagged and evaluate the queryable as an expression, appending it to the actual query.
9 | ///
10 | public class ExpandQueryableAttribute : Attribute { }
11 | }
12 |
--------------------------------------------------------------------------------
/LinqExpander/LinqExpander.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $id$
5 | $version$
6 | Luke McGregor
7 | A way of expanding extension methods in your LINQ expressions so that it can be interperated by a third party who doesn't understand your extensions
8 | https://github.com/lukemcgregor/LinqExpander
9 | https://raw.githubusercontent.com/lukemcgregor/LinqExpander/master/LICENSE
10 |
11 |
--------------------------------------------------------------------------------
/LinqExpander/ReplaceWithExpressionAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LinqExpander
4 | {
5 | ///
6 | /// Used in conjunction with the .AsExpandable() extention, this will replace the extension method tagged
7 | /// with an expression defined by the linked Method.
8 | /// Usage: [ReplaceInExpressionTree(MethodName = nameof(YourExpression))]
9 | ///
10 | public class ReplaceWithExpressionAttribute : Attribute
11 | {
12 | ///
13 | /// the name of the method returning an expression which you want to replace this extension with.
14 | ///
15 | public string MethodName { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/LinqExpander.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25420.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqExpander", "LinqExpander\LinqExpander.csproj", "{629A0BE0-E5C5-4386-8DE9-39313503CE3F}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {629A0BE0-E5C5-4386-8DE9-39313503CE3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {629A0BE0-E5C5-4386-8DE9-39313503CE3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {629A0BE0-E5C5-4386-8DE9-39313503CE3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {629A0BE0-E5C5-4386-8DE9-39313503CE3F}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/LinqExpander/AsExpandableExtension.cs:
--------------------------------------------------------------------------------
1 | using System.Linq;
2 |
3 | namespace LinqExpander
4 | {
5 | ///
6 | /// Extensions for AsExpandable
7 | ///
8 | public static class AsExpandableExtension
9 | {
10 | ///
11 | /// Transforms your expression by replacing any [ExpandQuery] or [ReplaceWithExpression(MethodName = ...)]
12 | /// extension methods with the expressionised versions of those methods. This allows the extensions to be used
13 | /// by another visitor such as EntityFramework. Should be used at the start of a query.
14 | ///
15 | /// the type of the queryable
16 | /// The input queryable
17 | /// A queryable which has any of the tagged extension methods replaced.
18 | public static IQueryable AsExpandable(this IQueryable source)
19 | {
20 |
21 | if (source is ExpandableQuery)
22 | {
23 | return (ExpandableQuery)source;
24 | }
25 |
26 | return new ExtendableQueryProvider(source.Provider).CreateQuery(source.Expression);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 Luke McGregor
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LinqExpander/ExpandableQuery.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 |
6 | namespace LinqExpander
7 | {
8 | internal class ExpandableQuery : IQueryable, IOrderedQueryable
9 | {
10 | ExtendableQueryProvider _provider;
11 | Expression _expression;
12 |
13 | public ExpandableQuery(ExtendableQueryProvider provider, Expression expression)
14 | {
15 | _provider = provider;
16 | _expression = expression;
17 | }
18 |
19 | public IEnumerator GetEnumerator()
20 | {
21 | return _provider.ExecuteQuery(_expression).GetEnumerator();
22 | }
23 |
24 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
25 | {
26 | return GetEnumerator();
27 | }
28 |
29 | public Type ElementType
30 | {
31 | get
32 | {
33 | return typeof(T);
34 | }
35 | }
36 |
37 | public Expression Expression
38 | {
39 | get
40 | {
41 | return _expression;
42 | }
43 | }
44 |
45 | public IQueryProvider Provider
46 | {
47 | get
48 | {
49 | return _provider;
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/LinqExpander/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("LinqExpander")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("LinqExpander")]
13 | [assembly: AssemblyCopyright("Copyright © 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("629a0be0-e5c5-4386-8de9-39313503ce3f")]
24 |
25 | [assembly: AssemblyVersion(AssemblyMeta.Version)]
26 | [assembly: AssemblyFileVersion(AssemblyMeta.Version)]
27 | [assembly: AssemblyInformationalVersion(AssemblyMeta.Version)]
28 |
29 | internal static class AssemblyMeta
30 | {
31 | public const string Version = "1.0.1";
32 | }
33 |
--------------------------------------------------------------------------------
/LinqExpander/ExpandableQueryProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 |
6 | namespace LinqExpander
7 | {
8 | internal class ExtendableQueryProvider : IQueryProvider
9 | {
10 | IQueryProvider _underlyingQueryProvider;
11 |
12 | private ExtendableQueryProvider()
13 | {
14 | }
15 |
16 | internal ExtendableQueryProvider(IQueryProvider underlyingQueryProvider)
17 | {
18 | _underlyingQueryProvider = underlyingQueryProvider;
19 | }
20 |
21 | public IQueryable CreateQuery(Expression expression)
22 | {
23 | return new ExpandableQuery(this, expression);
24 | }
25 |
26 | public IQueryable CreateQuery(Expression expression)
27 | {
28 | Type elementType = expression.Type.GetElementType();
29 | try
30 | {
31 | return (IQueryable)Activator.CreateInstance(typeof(ExpandableQuery<>).MakeGenericType(elementType), new object[] { this, expression });
32 | }
33 | catch (System.Reflection.TargetInvocationException tie)
34 | {
35 | throw tie.InnerException;
36 | }
37 | }
38 |
39 | internal IEnumerable ExecuteQuery(Expression expression)
40 | {
41 | return _underlyingQueryProvider.CreateQuery(Visit(expression)).AsEnumerable();
42 | }
43 |
44 | public TResult Execute(Expression expression)
45 | {
46 | return _underlyingQueryProvider.Execute(Visit(expression));
47 | }
48 |
49 | public object Execute(Expression expression)
50 | {
51 | return _underlyingQueryProvider.Execute(Visit(expression));
52 | }
53 |
54 | private Expression Visit(Expression exp)
55 | {
56 | ExpandableVisitor vstr = new ExpandableVisitor(_underlyingQueryProvider);
57 | Expression visitedExp = vstr.Visit(exp);
58 |
59 | return visitedExp;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/LinqExpander/ExpandableVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 |
6 | namespace LinqExpander
7 | {
8 | internal class ExpandableVisitor : ExpressionVisitor
9 | {
10 | private readonly IQueryProvider _provider;
11 | private readonly Dictionary _replacements = new Dictionary();
12 |
13 | internal ExpandableVisitor(IQueryProvider provider)
14 | {
15 | _provider = provider;
16 | }
17 |
18 | protected override Expression VisitMethodCall(MethodCallExpression node)
19 | {
20 | bool expandNode = node.Method.GetCustomAttributes(typeof(ExpandQueryableAttribute), false).Any();
21 | if (expandNode && node.Method.IsStatic)
22 | {
23 | object[] args = new object[node.Arguments.Count];
24 | args[0] = _provider.CreateQuery(node.Arguments[0]);
25 |
26 | for (int i = 1; i < node.Arguments.Count; i++)
27 | {
28 | Expression arg = node.Arguments[i];
29 | args[i] = (arg.NodeType == ExpressionType.Constant) ? ((ConstantExpression)arg).Value : arg;
30 | }
31 | return Visit(((IQueryable)node.Method.Invoke(null, args)).Expression);
32 | }
33 | var replaceNodeAttributes = node.Method.GetCustomAttributes(typeof(ReplaceWithExpressionAttribute), false).Cast();
34 | if (replaceNodeAttributes.Any() && node.Method.IsStatic)
35 | {
36 | var replaceWith = node.Method.DeclaringType.GetMethod(replaceNodeAttributes.First().MethodName).Invoke(null, null);
37 | if (replaceWith is LambdaExpression)
38 | {
39 | RegisterReplacementParameters(node.Arguments.ToArray(), replaceWith as LambdaExpression);
40 | return Visit((replaceWith as LambdaExpression).Body);
41 | }
42 | }
43 | return base.VisitMethodCall(node);
44 | }
45 | protected override Expression VisitParameter(ParameterExpression node)
46 | {
47 | Expression replacement;
48 | if (_replacements.TryGetValue(node, out replacement))
49 | return Visit(replacement);
50 | return base.VisitParameter(node);
51 | }
52 | private void RegisterReplacementParameters(Expression[] parameterValues, LambdaExpression expressionToVisit)
53 | {
54 | if (parameterValues.Length != expressionToVisit.Parameters.Count)
55 | throw new ArgumentException(string.Format("The parameter values count ({0}) does not match the expression parameter count ({1})", parameterValues.Length, expressionToVisit.Parameters.Count));
56 | foreach (var x in expressionToVisit.Parameters.Select((p, idx) => new { Index = idx, Parameter = p }))
57 | {
58 | if (_replacements.ContainsKey(x.Parameter))
59 | {
60 | throw new Exception("Parameter already registered, this shouldn't happen.");
61 | }
62 | _replacements.Add(x.Parameter, parameterValues[x.Index]);
63 | }
64 | }
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/LinqExpander/LinqExpander.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {629A0BE0-E5C5-4386-8DE9-39313503CE3F}
8 | Library
9 | Properties
10 | LinqExpander
11 | LinqExpander
12 | v4.5
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 | bin\Debug\LinqExpander.xml
24 |
25 |
26 | pdbonly
27 | true
28 | bin\Release\
29 | TRACE
30 | prompt
31 | 4
32 | bin\Release\LinqExpander.xml
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
--------------------------------------------------------------------------------