I am new to this T4 Templates.
All i know is these templates will generate entity classes from a LINQ to SQL class model (.dbml file)
We have this system which runs on Visual Studio 2010.
The problem starts, when we migrate to Visual Studio 2015.
I want to add new column to the entity/table.
When i Run Custom Tool, this error pops
A processor named 'T4Toolbox.XsdProcessor' could not be found for the
directive named 'xsd'. The transformation will not be run. The
following Exception was thrown:
System.IO.FileNotFoundException: Failed to resolve type for directive processor T4Toolbox.XsdProcessor.
Below is the template.
<## template hostspecific="True" debug="true" #>
<## xsd processor="T4Toolbox.XsdProcessor" file="%VS100COMNTOOLS%\..\..\Xml\Schemas\DbmlSchema.xsd" #>
<## output extension="log" #>
<## import namespace="System.Collections.Generic" #>
<## include file="T4Toolbox.tt" #>
<#
# include file="..\..\..\Framework\Templates\LinqToSql.tt" #>
// <copyright file="Script1.tt" company="">
// Copyright © . All Rights Reserved.
// </copyright>
// Generate entity classes from a LINQ to SQL class model (.dbml file)
NXpertGenerator generator = new NXpertGenerator();
generator.DbmlFile = "..\\..\\NXpert.Accounting.DataAccess\\Accounting.dbml";
generator.ConnectionStringKey = "AccountingDB2";
generator.DbmlNamespace = "NXpert.Accounting.DataAccess";
generator.UsingStatements = new List<string>{"NXpert.Core", "NXpert.Accounting", "NXpert.Accounting.DataAccess", "System.Data.Linq"};
generator.ClassMappings = new List<ObjectDescriptor>{
new ObjectDescriptor{
Name = "BalanceSheet",
NamePlural = "BalanceSheets",
EntityName = "BalanceSheetEntity",
Properties = new List<PropertyDescriptor>{
new PropertyDescriptor{ Name = "Status", ConvertType = "CommonStatus" },
new PropertyDescriptor{ Name = "CreatedDate", ConvertType = "DateTime" },
new PropertyDescriptor{ Name = "UpdatedDate", ConvertType = "DateTime" }
}
}
};
generator.Run();
#>
I did try to remove the line
<## xsd processor="T4Toolbox.XsdProcessor" file="%VS100COMNTOOLS%\..\..\Xml\Schemas\DbmlSchema.xsd" #>
This error shows
Compiling transformation: The type or namespace name 'Association'
could not be found (are you missing a using directive or an assembly
reference?)
Compiling transformation: The type or namespace name 'Database' could not be found (are you missing a using directive or an assembly
reference?)
Somewhat this kind of error tells me that it is just a namespace that i forgot to add.
But again this template is running perfectly in Visual Studio 2010.
There must be some settings/ steps to be done in order for these templates to run in VS2015. Please let me know.
I would gladly appreciate any solution or idea you can share to this problem of mine.
Related
I wanna Render View To Stream.
this is my code:
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new
RouteData(), new ActionDescriptor());
var viewEngineResult = _viewEngine.FindView(actionContext,
viewName, false);
this code worked before. but after update to core6 doesn't work.
net core 6 does not create view.dll
my razor view is in Views/Shared location. and i set it as content
Compiler no longer produces a Views assembly
The Razor compiler no longer produces a separate Views.dll file that
contains the CSHTML views defined in an application.
Both views and application types are included in a single
AppName.dll assembly. View types have the accessibility modifiers
internal and sealed, by default, and are included under the
AspNetCoreGeneratedDocument namespace.
So, If your method is doing something by View.dll, It is not work in .Net 6
Refer to this doc to learn more.
I'm working at a middleware for aspnetcore2.0 where I want to execute some razor view.
Actually I need a error handling middleware which would show nice pages from razor views. I know that it's possible to do with UseStatusCodePagesWithReExecute based on status codes. But I need a more general approach - handle an exception in my middleware to delegate (in some cases) it to an error view.
I realized that DeveloperExceptionPageMiddleware does something similar to what I need. But I can't understand how it works even after digging into its sources.
Here is the place where that middleware returns a view - https://github.com/aspnet/Diagnostics/blob/dev/src/Microsoft.AspNetCore.Diagnostics/DeveloperExceptionPage/DeveloperExceptionPageMiddleware.cs#L206
But I can't understand what kind of view it is. It's nor a razor page (as it has no #page directive) neither an mvc view (but i'm not sure).
In the project there're two files for that view: ErrorPage.cshtml and ErrorPage.Designer.cs. How that Designer.cs was created? It looks like a generated file. But thanks to it there's a normal class in the project (ErrorPage) which can be used explicitly. It inherits Microsoft.Extensions.RazorViews.BaseView class from Microsoft.Extensions.RazorViews.Sources package.
So the middleware just execute that view:
var errorPage = new ErrorPage(model);
return errorPage.ExecuteAsync(context);
How can it be achieved in my project?
UPDATE [2018.06]: Please note that the post was written for .NET Core 2.0 times, there're breaking changes for RazorEngine in .NET Core 2.1.
It turned out that it's pretty easy to do.
Aspnet prjoect has an internal tool called RazorPageGenerator (see https://github.com/aspnet/Razor/tree/dev/src/RazorPageGenerator) which can be used to compile views. After compilation with this tool we'll get normal classes which can be used in middlewares.
But before we need to get RazorPageGenerator and slightly customize it.
1.Create a new console project
dotnet new console -o MyRazorGenerator
2.put NuGet.config inside this folder
<configuration>
<config>
<add key="globalPackagesFolder" value="./packages" />
</config>
<packageSources>
<add key="aspnetcore-dev" value="https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json " />
</packageSources>
</configuration>
3.Add the following in csprj (as dotnet add package doesn't support installing pre-prelease packages)
<ItemGroup>
<PackageReference Include="RazorPageGenerator" Version="2.1.0-*" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.Extensions" Version="2.1.0-*" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Language" Version="2.1.0-*" />
</ItemGroup>
4.restore dotnet restore to check you got RazorPageGenerator
5.add into Program.cs:
public static int Main(string[] args)
{
if (args == null || args.Length < 1)
{
Console.WriteLine("Invalid argument(s).");
return 1;
}
var rootNamespace = args[0];
var targetProjectDirectory = args.Length > 1 ? args[1] : Directory.GetCurrentDirectory();
var razorEngine = RazorPageGenerator.Program.CreateRazorEngine(rootNamespace, builder => {
FunctionsDirective.Register(builder);
InheritsDirective.Register(builder);
SectionDirective.Register(builder);
});
var results = RazorPageGenerator.Program.MainCore(razorEngine, targetProjectDirectory);
foreach (var result in results)
{
File.WriteAllText(result.FilePath, result.GeneratedCode);
}
Console.WriteLine();
Console.WriteLine($"{results.Count} files successfully generated.");
Console.WriteLine();
return 0;
}
6.Now we have our own generator and can compile views
7.Create a Razor View (.cshtml)
8.run our generator to compile view:
dotnet run --project .\MyRazorPageGenerator\MyRazorPageGenerator.csproj Croc.XFW3.Web .\Middleware
here I assume that the view is inside Middleware\Views folder.
9.Generator creates a file like ErrorPage.Designer.cs (if view was ErrorPage.cshtml) which we can use:
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
if (context.Response.StatusCode == StatusCodes.Status404NotFound)
{
var statusCodeFeature = context.Features.Get<IStatusCodePagesFeature>();
if (statusCodeFeature == null || !statusCodeFeature.Enabled)
{
if (!context.Response.HasStarted)
{
var view = new ErrorPage(new ErrorPageModel());
await view.ExecuteAsync(context);
}
}
}
}
}
Here we're returning our view in case of 404 error and absense of StatusCodePagesMiddleware. Can be useful for embedded UI in libs.
The generated code uses staff which should be added into your project. To get it we need to acquire nuget package Microsoft.Extensions.RazorViews.Sources. Again it’s not on nuget.org so we need to install it from https://dotnet.myget.org/feed/aspnetcore-dev/package/nuget/Microsoft.Extensions.RazorViews.Sources.
i want to retrieve tweets from twitter using specific hashtags.
i am using tweetinvi for this purpose.but i am getting an error
outer exception:
The type initializer for 'Tweetinvi.TwitterCredentials' threw an exception.
Inner exception:
{"Could not load file or assembly 'System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)":"System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes"}
i am using autofac 3.4.
kindly point out what am i doing wrong?
TwitterCredentials.SetCredentials("useraccesstoken",
"useraccessecret",
"consumerKey",
"consumerSecret");
var searchParameterSearch.GenerateTweetSearchParameter("#pakvsSA");
searchParameter.SetGeoCode(-122.398720, 37.781157, 1,DistanceMeasure.Miles);
searchParameter.Lang = Language.English;
searchParameter.SearchType = SearchResultType.Popular;
searchParameter.MaximumNumberOfResults = 100;
searchParameter.Until = new DateTime(2015, 12, 3);
searchParameter.SinceId = 399616835892781056;
searchParameter.MaxId = 405001488843284480;
var tweets = Search.SearchTweets(searchParameter);
So it looks like there are some .dll required by Tweetinvi (Sytem.Core) that are missing.
I would strongly advise using nuget to install Tweetinvi as a package as it will automatically install and reference all required dll.
https://www.nuget.org/packages/TweetinviAPI/
I am using to get the assembly for following
Assembly assembly = Application.Current.GetType().GetTypeInfo().Assembly;
and i get the ResourceNames form that assembly for using
var resources=assembly.GetManifestResourceNames()
but it gives no resource names in assembly.
Please help me how to achieve it?
In VB.NET, I do that:
Public Function LoadResourceStr(sResID As String) As String
Dim ctx As Windows.ApplicationModel.Resources.Core.ResourceContext = New Windows.ApplicationModel.Resources.Core.ResourceContext()
ctx.Languages = {Globalization.CultureInfo.CurrentUICulture.Name}
Dim rmap As Windows.ApplicationModel.Resources.Core.ResourceMap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap.GetSubtree("Resources")
Return rmap.GetValue(sResID, ctx).ValueAsString
End Function
The MainResourceMap is a collection of all resources of application. Important: the files into directories of app (embedded compiled) need is configured to "Content", not "embedded resource". In this case, you can change string ID from "Resources" to "Files".
The sample above show the resource strings into xml files, to translate your app.
I am using the RazerEngine at https://github.com/Antaris/RazorEngine
I am wondering how and if it is possible to pass an assembly reference to the engine?
Say I have some logic in an external DLL - how can I call a method in a custom DLL?
string template = "#using ClassLibrary1 #ClassLibrary1.Class1.SomethingFromADLL() ";
string result = Razor.Parse(template, m);
This results in an exception
Unable to compile template. The type or namespace name 'ClassLibrary1' could not be found (are you missing a using directive or an assembly reference?)
you have to find your necessary method and just write its name. For example:
String.Trim();
and
string template="String.Trim()";
I found that if I add the following line prior to the Razor.Parse method it now has access to the ClassLibrary1
Assembly a = Assembly.LoadWithPartialName("ClassLibrary1");
string template = "#using ClassLibrary1 #ClassLibrary1.Class1.SomethingFromADLL() ";
string result = Razor.Parse(template, m);