RazorEngine.Templating.TemplateCompilationException - asp.net-mvc-4

whenever I use RazorEngine in my application I get the following error:
{"FailedAt":"2014-11-12T02:51:59.9765953Z","ExceptionType":"RazorEngine.Templating.TemplateCompilationException","ExceptionMessage":"Unable to compile template. Assuming assembly reference 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' matches 'System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', you may need to supply runtime policy\n\nOther compilation errors may have occurred. Check the Errors property for more information.","ExceptionDetails":"RazorEngine.Templating.TemplateCompilationException: Unable to compile template. Assuming assembly reference 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' matches 'System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', you may need to supply runtime policy\n\nOther compilation errors may have occurred. Check the Errors property for more information.\r\n at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context) in c:\Users\abbottm\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Compilation\DirectCompilerServiceBase.cs:line 106\r\n at RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate, Type modelType) in c:\Users\abbottm\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 256\r\n at RazorEngine.Templating.TemplateService.GetTemplate[T](String razorTemplate, Object model, String cacheName) in c:\Users\abbottm\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 374\r\n at RazorEngine.Templating.TemplateService.GetTemplate(String razorTemplate, Object model, String cacheName) in c:\Users\abbottm\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 352\r\n at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, Object model, DynamicViewBag viewBag, String cacheName) in c:\Users\abbottm\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 437\r\n at RazorEngine.Razor.Parse(String razorTemplate, Object model, String cacheName) in c:\Users\abbottm\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Razor.cs:line 302\r\n at Postal.FileSystemRazorView.Render(ViewContext viewContext, TextWriter writer)\r\n at Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder)\r\n at Postal.EmailViewRenderer.Render(Email email, String viewName)\r\n at Postal.EmailService.CreateMailMessage(Email email)\r\n at NumediaTechCore.UI.Controllers.Admin.EmailsController.SendEmail(Int32 EmailTemplateID) in c:\NumediaTech\NumediaTechPortal\NumediaTechCore\UI\Controllers\Admin\EmailsController.cs:line 105"}

Related

ASP .Net Core - Inheriting from RazorPage<TModel> issue

I'm trying to define a base page by inheriting from RazorPage. If I pass anything other than TModel in my #inherit section of the page, I get the following error:
ArgumentException: Property 'ViewData' is of type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary`1[[MyProject.Models.IndexViewModel, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]', but this method requires a value of type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
Parameter name: viewContext
How can I override ViewData so I can pass my custom model instead of IndexViewModel in the following line:
#inherits MyProject.Base.BaseView
Thanks
So I have done this to get around this issue, no idea whether it is a good or bad approach but is working
instead of actually using TModel in the RazorPage, use object for the generic type in RazorPage (RazorPage) and create a property to expose your own Model of the type you requested and cast Model to that type.
like this:
public abstract class MenuViewPage<TModel> : RazorPage<object>
{
public TModel PageModel {
get
{
return (TModel)ViewData.Model;
}
}
}

TravelItineraryReadService VB error

When trying to use the TravelItineraryReadService 3.8.0 service via VB i get the following error just by doing
Private service As TravelItineraryReadService
service = New TravelItineraryReadService
the error output:
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.GetSerializersFromCache(XmlMapping[] mappings, Type type)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)
at System.Web.Services.Protocols.SoapClientType..ctor(Type type)
at System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()
at PricingContingency.TravelItineraryRQ1.TravelItineraryReadService..ctor()
i am using visual studio 2015,
added the WSDL as
it doesn't matter if i add the header info or not. it always fails.
This is due to response object issue in generated web service proxy class.
Changed the following and works well for me.
1.
Private associatedDataField()() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem
----change as below-- Private associatedDataField() As
TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem
Public Property AssociatedData() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem()()
----change as below--
Public Property AssociatedData() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem()

Why does wrapping a dictionary in a class allow it to be used by an ASMX WebMethod?

As I understand it, it is not possible to pass a Dictionary(Of String, String) to an ASMX web service because Dictionary implements IDictionary. Attempting to do so results in not only the method throwing an exception when attempting to call it, but also throws an exception when attempting to go to the web service URL in a browser:
The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.
However, I have found that if I create a class that contains a Dictionary property, and pass that to the web service method as a parameter, it works fine.
Public Class DictWrapper
Public Property oDic as Dictionary(Of String, String)
End Class
<WebMethod()>
Public function ReadDic(oDictWrapper as DictWrapper) As Boolean
Return oDictWrapper("SomeBoolean")
End Function
Why does this example work? I can call this WebMethod with AJAX, passing a varying number of keys and values in the wrapped dictionary, no problem. How is this any different than just having the dictionary as a parameter of the WebMethod?

wcf netdatacontractserializer exception serialising idictionary with enumeration as key

I am using the NetDataContractSerialiser with WCF. This is working well with all our types being serialised. However, a service I am calling is generating the following exception
The formatter threw an exception while trying to deserialize the message:
There was an error while trying to deserialize parameter http://tempuri.org/:xmlServiceObjIN. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'System.Collections.Generic.EnumEqualityComparer`1[[GrantEd.Common.DomainModel.Code.Enums.enumFundingParameterContextKey, GrantEd.Common.DomainModel.Code, Version=14.0.71.0, Culture=neutral, PublicKeyToken=null]]' could not be found in assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'. Please see InnerException for more details.
The class being serialised has a property defined as
public IDictionary<enumFundingParameterContextKey, string> Context { get; set; }
the declaration of the enum is
[Serializable]
public enum enumFundingParameterContextKey
{
[EnumMemberAttribute()]
ClientId = 0,
[EnumMemberAttribute()]
EntitlementDefinitionId = 1
}
which is defined in another assmebly.
When I replace the enumeration with int the class deserialises with no problems. Any ideas why using the enum would result the exception?
The reason for using NetDataContractSerializer was to for type information to be available and avoid having to use KnownType
Make the base type as non integer for your enum. e.g. a byte.
Example:
[Serializable] public enum enumFundingParameterContextKey : byte
{
[EnumMemberAttribute()]
ClientId = 0,
[EnumMemberAttribute()]
EntitlementDefinitionId = 1
}
Details are in my following blog post: dotnet-35-to-dotnet-40-enum
Try to mark enum with [DataContract] instead of [Serializable]. But it looks like the enum type is unknown at all on the client.

WCF Known Type error

I get this error when calling my service:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: There was an error while trying to serialize parameter http://DSD.myCompany.net/DsdWebServices/2011/05/:config. The InnerException message was 'Type 'System.OrdinalComparer' with data contract name 'OrdinalComparer:http://schemas.datacontract.org/2004/07/System' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
Source Error:
Line 130: passwordAttemptWindow="10"
Line 131: passwordStrengthRegularExpression=""
Line 132: type="DsdWebsite.Providers.DsdMembershipProvider, DsdWebsite.Providers" />
Line 133: </providers>
Line 134: </membership>
Source File: C:\Development\DSD Website\WebUI\web.config Line: 132
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.5444; ASP.NET Version:2.0.50727.5420
The service is a data service for a membership provider. I created a MembershipUser DTO to move data back and forth across the service. It uses only standard classes: string, int, DateTime. I use Guid instead of object for the providerUserKey.
The interface for the service looks like this:
[ServiceContract(Namespace = "http://DSD.myCompany.net/DsdWebServices/2011/05/")]
[ServiceKnownType(typeof(MembershipUserDTO))]
[ServiceKnownType(typeof(NameValueCollection))]
[ServiceKnownType(typeof(Guid))]
[ServiceKnownType(typeof(DateTime))]
public interface IDsdMembershipProviderService
{
[OperationContract]
void Initialize(string name, NameValueCollection config);
[OperationContract]
MembershipUserDTO CreateUser(string username,
string salt,
string encodedPassword,
...
The DTO looks like this
namespace DsdWebsite.Services.Providers
{
[Serializable]
[DataContract]
[KnownType(typeof(Guid))]
[KnownType(typeof(DateTime))]
public class MembershipUserDTO
{
public MembershipUserDTO(string providerName, string userName, Guid providerUserKey, string email,
string passwordQuestion, string comment, bool isApproved, bool isLockedOut,
DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate,
DateTime lastPasswordChangedDate, DateTime lastLockoutDate,
string firstName, string lastName, string cellPhone, string officePhone,
string brokerId, bool isAdmin, bool mustChangePassword)
{
ProviderName= providerName;
UserName = userName;
ProviderUserKey= providerUserKey;
Email= email;
PasswordQuestion= passwordQuestion;
Comment= comment;
IsApproved=isApproved;
IsLockedOut= isLockedOut;
CreationDate= creationDate;
LastLoginDate= lastLoginDate;
LastActivityDate= lastActivityDate;
LastPasswordChangedDate = lastPasswordChangedDate;
LastLockoutDate=lastLockoutDate;
...
Finally, my web.config looks like this:
<membership
defaultProvider="DsdMembershipProvider"
userIsOnlineTimeWindow="15"
hashAlgorithmType=""> <providers>
<clear/>
<add
name="DsdMembershipProvider"
connectionStringName="DsdMembershipConnectionString"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/DsdWebsite/"
requiresUniqueEmail="true"
passwordFormat="Encrypted"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
type="DsdWebsite.Providers.DsdMembershipProvider,
DsdWebsite.Providers" />
</providers> </membership>
How can I determine what type or object is causing the error?
Thanks
Use following ServiceKnownTypeAttribute constructor to specify type of class (declaringType) containing the static method methodName that will return service known types:
public ServiceKnownTypeAttribute(
string methodName,
Type declaringType
)
Inside the aforementioned static method add all service known types that are already added (although I think you would do good without DateTime and Guid), and add System.OrdinalComparer as well.
The catch is that System.OrdinalComparer is internal class so you will have to get the type via reflection.
EDIT:
System.OrdinalComparer is part of mscorlib assembly. Basically you can get its type in a following manner:
Type[] types = typeof( string ).Assembly.GetTypes();
and then you can retrieve the wanted type by name (using Linq, add necessary using statements).
Type type = types.Where( x => x.FullName == "System.OrdinalComparer" );
Previous two line can be combined in one, for simplicity done using two lines.
If you need more details, just say.