Request error with WCF Data Services - entity-framework

Its my first time setting up an OData Service and I'm of course having some problems...
The problem is that I can't get the service running, I keep getting an "Request Error".
I have researched on what the problem can be and I found that a common issue is that the access rules are incorrectly typed. So I have tried fixing this both with Singular names, Plural names and I have also tried with typeof(Post).getType().Name
Well here is my code. I hope you can help me, I've been stuck for hours.
public class ODataService : DataService<Entity>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService( DataServiceConfiguration config )
{
//config.SetEntitySetAccessRule( "Users", EntitySetRights.All );
//config.SetEntitySetAccessRule( "Posts", EntitySetRights.All );
//config.SetEntitySetAccessRule( "Albums", EntitySetRights.All );
config.SetEntitySetAccessRule( "*", EntitySetRights.AllRead );
config.SetServiceOperationAccessRule( "*", ServiceOperationRights.AllRead );
//config.SetServiceOperationAccessRule( "GetPosts", ServiceOperationRights.AllRead );
config.UseVerboseErrors = true;
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
[WebGet]
public IQueryable<Post> GetPosts()
{
return CurrentDataSource.Posts.AsQueryable();
}
}
The structure of my EntityFramework class (db first)
Methods and Members for Entity class. Here the entities are spelled in plural.
This is my Web.config:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="Entity" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=XXX;Initial Catalog=XXX;persist security info=True;user id=XXX;password=XXX;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime requestValidationMode="4.5" targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<pages controlRenderingCompatibilityVersion="4.5" />
<machineKey compatibilityMode="Framework45" />
</system.web>
<system.serviceModel>
<services>
<service name="LinkIT.Core.OData.ODataService" behaviorConfiguration ="DebugEnabled">
</service>
</services>
<behaviors>
<serviceBehaviors >
<behavior name="DebugEnabled">
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
</configuration>
A detailed error message:
The server encountered an error processing the request. The exception
message is 'Value cannot be null. Parameter name:
propertyResourceType'. See server logs for more details. The exception
stack trace is:
at System.Data.Services.WebUtil.CheckArgumentNull[T](T value, String
parameterName) at
System.Data.Services.Providers.ResourceProperty..ctor(String name,
ResourcePropertyKind kind, ResourceType propertyResourceType) at
System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMemberMetadata(ResourceType
resourceType, IProviderMetadata workspace, IDictionary2 knownTypes,
PrimitiveResourceTypeMap primitiveResourceTypeMap) at
System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(IDictionary2
knownTypes, IDictionary2 childTypes, IDictionary2 entitySets) at
System.Data.Services.Providers.BaseServiceProvider.PopulateMetadata()
at System.Data.Services.Providers.BaseServiceProvider.LoadMetadata()
at
System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider&
metadataProviderInstance, IDataServiceQueryProvider&
queryProviderInstance, BaseServiceProvider& builtInProvider, Object&
dataSourceInstance) at
System.Data.Services.DataService1.CreateProvider() at
System.Data.Services.DataService1.HandleRequest() at
System.Data.Services.DataService1.ProcessRequestForMessage(Stream
messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] ,
Object[] ) at
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs) at
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&
rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
isOperationContextSet)

WCF Data Services team confirms - this is the exact error faced when you use Enums (which is not yet supported).
Remove the Enum types (or use their suggested work-around and use a wrapper around the enum properties) and this should go away.

Related

.NetCore code with sustainsys-saml2 does nothing

I have an .Net MVC project with SSO working. The SSO config looks like this:
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
<caches>
<sessionSecurityTokenCache type="Vixion.IdentityModel.Cache.SharedSessionSecurityTokenCache, Vixion.IdentityModel.Cache">
<cacheServiceAddress url="http://tvwapps35434d.kpnis.nl:1008/SessionSecurityTokenCacheService.svc" />
</sessionSecurityTokenCache>
</caches>
<audienceUris>
<add value="http://localhost:24442/" />
</audienceUris>
<securityTokenHandlers>
<remove type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.IdentityModel.Tokens.Saml2SecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
<certificateValidation certificateValidationMode="None" />
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://vix-make-o:8080">
<keys>
<add thumbprint="5137c779a1e77a0f4a78abd356b0238912637469" />
</keys>
<validIssuers>
<add name="http://vix-make-o:8080" />
</validIssuers>
</authority>
</issuerNameRegistry>
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" path="/" />
<wsFederation passiveRedirectEnabled="true" issuer="http://vix-make-o:8080" realm="http://localhost:24442/" requireHttps="false" reply="http://localhost:24442/" />
</federationConfiguration>
</system.identityModel.services>
According to the example here:
https://github.com/Sustainsys/Saml2/tree/master/Sustainsys.Saml2.AspNetCore2
I write this code in a new .NetCore app:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
});
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddAuthentication()
.AddSaml2(options =>
{
options.SPOptions.EntityId = new EntityId("http://vix-make-o:8080");
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId("http://vix-make-o:8080/ws_saml_metadata"), options.SPOptions)
{
//LoadMetadata = true
});
});
app.UseAuthentication();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
When I start the app, the browser goes straight to the index page. No error, no nothing. When I check with SAML Chrome Panel it shows no traffic at all.
I do not expect my code working, but it should at least do something to give me a hint to how to go further.
Any suggestions are welcome.
Thank you.
S.
Remove the web.config content. It is not used with the ASP.NET Core module.
Set back the LoadMetadata flag, or add the necessary config manually.
Set Saml2 as the default challenge protocol for authentication.
Finally, add an [Authorize] attribute to your controllers that should require authentication to initiate the authentication process.

Cannot access identity claims in custom authorize attribute in MVC application

I am trying to do POC of switching from forms authentication in existing MVC 4 application to claims-based one, but cannot get custom authorize attribute working - have infinite redirect loop ending with known 'bad request' issue because of total cookie size...
And the reason - there is no authenticated identity (and correct Claims collection) in attribute context as I see it in debug despite I see successfully created identity with expected claims collection in SecurityTokenValidated handler.
So, it seems like it is somehow lost after OIDC middleware process it, and not unavailable in attribute context, therefore I cannot further check for 'role' claim.
Maybe I am missing something?
My OWIN Startup:
AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
//AuthenticationMode = AuthenticationMode.Active, // ? https://github.com/IdentityServer/IdentityServer3/issues/1963
Authority = OAuthServerUrl,
ClientId = "my_app",
RedirectUri = MyAppUrl,
ResponseType = "id_token token", //notice, if response type 'token' is requested, IdentityServer stops including the claims in the identity token, though we could set alwaysInclude=true for some scope claims (ex. for role)
Scope = "openid profile roles",
SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
PostLogoutRedirectUri = MyAppUrl,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
var id = n.AuthenticationTicket.Identity;
//n.OwinContext.Authentication.SignIn(id);
//tried SignIn() explicitly, and even setting HttpContext.Current.User and Thread.CurrentPrincipal to n.AuthenticationTicket.Identity, but without luck
return Task.FromResult(0);
},
RedirectToIdentityProvider = async n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var result =
await n.OwinContext.Authentication.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);
var idToken = result?.Identity.Claims.GetValue("id_token");
if (idToken != null)
{
n.ProtocolMessage.IdTokenHint = idToken;
}
}
await Task.FromResult(0);
}
}
});
My custom attribute inherited from System.Web.Mvc.AuthorizeAttribute:
public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//var owinContext = HttpContext.Current.GetOwinContext();
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// 403 we know who you are, but you haven't been granted access
filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
}
else
{
// 401 who are you? go login and then try again
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
where filterContext.HttpContext.User.Identity (also tried HttpContext.Current.User and Thread.CurrentPrincipal) has Claims collection with single 'name' claim from LOCAL AUTHORITY issuer (default one?).
I also modified Web.config to disable forms auth:
<authentication mode="None">
...
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="999" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="3" passwordStrengthRegularExpression="" applicationName="Audit" />
<!--<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="999" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="3" passwordStrengthRegularExpression="" applicationName="Audit" />-->
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="Audit" />
<!--<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="Audit" />-->
</providers>
</profile>
<roleManager enabled="true">
<roleManager enabled="false">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="Audit" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add applicationName="Audit" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--<add connectionStringName="ApplicationServices" applicationName="Audit" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />-->
<!--<add applicationName="MyApp" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />-->
</providers>
</roleManager>
...
<handlers>
<remove name="FormsAuthentication" />
<remove name="RoleManager" />
UPDATE 1: I've migrated app from MVC 4 to the latest MVC 5 hoping it is MVC 4 related issue, but, unfortunately, no difference. Apparently, something wrong with my client application/configuration.

Npgsql nhibernate 57014 canceling statement due to statement timeout

I'm getting random errors in some queries using Npgsql.
Here is the stack trace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1597
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1497
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1487
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 1955
at NHibernate.Impl.CriteriaImpl.List(IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 265
at NHibernate.Impl.CriteriaImpl.List[T]() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 276
at LAVASPORT.DAO.MigrarCadeteDAO.findByCompania(Compania compania, String conexion, DateTime fechainicial, DateTime fechafinal) in D:\Aplicaciones\LavaSport\LAVASPORT\DAO\MigrarCadeteDAO.cs:line 125
And here is the message
InnerException = {"57014: canceling statement due to statement timeout"}
I'm not getting this exceptions all the time, just 1 or 2 times at day. The query in special that most send the exception is a high volume query.
Here is the query:
public IList<Cadete> findByCompania(Compania compania, String conexion,DateTime fechainicial,DateTime fechafinal)
{
try
{
DateTime fechaini = new DateTime(fechainicial.Year, fechainicial.Month, fechainicial.Day);
DateTime fechafin = new DateTime(fechafinal.Year, fechafinal.Month, fechafinal.Day);
var nhConfig = new Configuration().Configure(conexion);
var sessionFactory = nhConfig.BuildSessionFactory();
var session = sessionFactory.OpenSession();
session.BeginTransaction();
var query = session.CreateCriteria<Cadete>();
query.CreateAlias("compania", "compania");
query.Add(Restrictions.Eq("compania.id", compania.id))
.Add(Restrictions.Lt("fechaIngreso", fechafin))
.Add(Restrictions.Ge("fechaIngreso",fechaini));
IList<Cadete> cadetes = query.List<Cadete>();
return cadetes;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return null;
}
This are my NHibernate configuration and my web config file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="LAVASPORT">
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="connection.connection_string">
Server=localhost;database=LAVASPORT;user id=postgres;password=admin;MaxPoolSize=500;TimeOut=1000;
</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="LAVASPORT"/>
</session-factory>
</hibernate-configuration>
If I increase the timeout to more than 1000, I get errors on connections every time.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"></section>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
<system.transactions>
<defaultSettings timeout="10:00:00" />
</system.transactions>
</configuration>
I would really appreciate any help.
First, note that the Timeout connection string parameter manages connection timeouts (i.e. NpgsqlConnection.Open()) rather than command execution timeout. Defaul command execution timeout is managed via the Command Timeout connection string parameter.
Beyond that, it seems like your commands are simply timing out. Since the default command timeout is 30 seconds, it would seem you have some serious performance issue with your queries, your database index, or something else. You need to carefully analyze the SQL being created by NHibernate and how it's executed by PostgreSQL.

ASP.NET Routing in rest service not working in IIS

I created a simple rest service with routing enabled. The routing is properly working when i run it locally i.e using asp.net development server. But when I deploy the application in IIS (IIS 7.5) then it and try to access the method in the service i get the error HTTP 404.0 Not found. Here is my code :
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class HelloWorldService
{
[WebGet(UriTemplate = "Date")]
public DateTime Date()
{
return System.DateTime.Now;
}
}
Global.asax:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("ServiceData", new WebServiceHostFactory(), typeof(HelloWorldService)));
}
Web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
I also Enabled HTTP Redirection Feature under
Windows Features -> Internet Information Services -> Word Wide Web services -> Common HTTP Features
I also tried Adding handlers like
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
Also i have tried all the other solutions that were suggested on the web but nothing works. Thanks in advance for any help.
Something is wrong with your RegisterRoutes(). It should be:
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("HelloWorldService", new WebServiceHostFactory(), typeof(HelloWorldService)));
}

SSRS 2008 Execution Service LoadReport Error

I'm using SSRS 2008 (NOT R2)
I have a report deployed to a dev server, I'm trying to render the report as a pdf by calling the execution service.
The error I am getting is
This operation is not supported on a report server that runs in native mode. ---> Microsoft.ReportingServices.Diagnostics.Utilities.OperationNotSupportedNativeModeException: This operation is not supported on a report server that runs in native mode.
Two things I notice: one is that web service wsdl shows LoadReport having two parameters - report path and history id, but when I generate a service reference for the ReportExecution2005.asmx, the LoadReport method has 5 parameters: trusteduserheader, reportPath, historyid, serviceinfoheader, and executionheader
I have tried adding the service reference with and without ?wsdl at the end of the url but the result is the same
Here's the code I'm using:
ReportExecutionServiceSoapClient rs = new ReportExecutionServiceSoapClient("ReportExecutionServiceSoap", "http://xxx:80/ReportServer/ReportExecution2005.asmx");
rs.ClientCredentials.Windows.ClientCredential = new NetworkCredential("aaa", "aaa", "aaa");
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
// Render arguments
byte[] result = null;
string reportPath = "/Invoices/InvoiceStandard";
string format = "PDF";
string historyID = null;
string devInfo = "";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[3];
parameters[0] = new ParameterValue();
parameters[0].Name = "PartyID";
parameters[0].Value = "19758";
parameters[1] = new ParameterValue();
parameters[1].Name = "Contract";
parameters[1].Value = "17703"; // June
parameters[2] = new ParameterValue();
parameters[2].Name = "FinancialPeriod";
parameters[2].Value = "MAR-2012";
string encoding="";
string mimeType="";
string extension="";
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
TrustedUserHeader trusteduserHeader = new TrustedUserHeader();
ExecutionHeader execHeader = new ExecutionHeader();
ServerInfoHeader serviceInfo = new ServerInfoHeader();
execHeader = rs.LoadReport(trusteduserHeader, reportPath, historyID, out serviceInfo, out execInfo);
rs.SetExecutionParameters(execHeader, trusteduserHeader, parameters, "en-us", out execInfo);
try
{
rs.Render(execHeader,
trusteduserHeader,
format,
devInfo,
out result,
out extension,
out encoding,
out mimeType,
out warnings,
out streamIDs);
}
Here's my web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="ReportExecutionServiceSoap" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://xxx:80/ReportServer/ReportExecution2005.asmx"
binding="basicHttpBinding" bindingConfiguration="ReportExecutionServiceSoap"
contract="SSRS.ReportExecutionServiceSoap" name="ReportExecutionServiceSoap" />
</client>
</system.serviceModel>
</configuration>
I had the same problem with SSRS 2008 R2, but I did not want to resort to calling the report viewer control.
Above, Rick Hodder was using the following statement:
TrustedUserHeader trusteduserHeader = new TrustedUserHeader();
This statement will cause the OperationNotSupportedNativeModeException error he encountered if the SSRS installation is not configured with a certificate for SSL connections. Check the SSRS Logs for an error entry that contains:
ERROR: TrustedHeader Not Supported in Native Mode.
If this is the case, you need to either configure the server to work with SSL, or use null for the trusted header.
TrustedUserHeader trusteduserHeader = null;
Is this report loaded from some front end or is it loaded from DLL? To me it looks like you are using ASP.net Application. In this case you could use reportViewer object to pull the report for you all the heavy lifting can be done by the ReportViewer and you can then just save the file as PDF
using something like this
reportViewer.ServerReport.ReportServerUrl = new Uri(Config.ReportServerURL);
reportViewer.ServerReport.ReportPath = String.Format("{0}/{1}", Config.ReportServerEnvironment, reportName);
reportViewer.ServerReport.ReportServerCredentials = new ReportsCredentials(Config.ReportServerUser, Config.ReportServerPassword, Config.ReportServerDomain);
reportViewer.GetDocumentStream(SSRSFormatType.Pdf, documentName);
Here reportViewer is the reference to ReportViewer object on the screen.