Web.config jsonSerialization maxJsonLength ignored - vb.net

I have an MVC3 application running under .NET 4.0 and when I use JavascriptSerializer.Deserialize I'm getting an error.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Reading Can I set an unlimited length for maxJsonLength in web.config I put the jsonSerialization maxJsonLength key in my web.config but it gets ignored. Though I can set the JavaScriptSerializer.MaxJsonLength property in code and it works fine.
I would like to have the value in the Web.config rather than code. Here is how I am using JavaScriptSerializer.
Dim client As New WebClient
...
Dim result = _client.DownloadString("Test")
Dim serializer = New JavaScriptSerializer
Return serializer.Deserialize(Of Foo)(result)
Here is my Web.config
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/Http404"/>
<error statusCode="403" redirect="/Http403"/>
<error statusCode="550" redirect="/Http550"/>
</customErrors>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.webServer>
....
</system.webServer>
</configuration>

According to the link you provided (the 2nd most voted answer), your web.config setting will be ignored because you're using an internal instance of the JavaScriptSerializer.
If you need the value to be stored in the web.config, you could add a key in the <appSettings> section called maxJsonLength with a value of 50000000 and then in your code, you could use it like:
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = ConfigurationManager.AppSettings['maxJsonLength'];

Related

How can read config file in Net5?

I using Vb.net , FW: Net5
This is my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectString" value="DB/Sample.db3" />
</appSettings>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
I install "System.Configuration.ConfigurationManager" from Nuget
I had try get config as:
Dim str = System.Configuration.ConfigurationManager.AppSettings("ConnectString")
But it occur exception error:
Configuration system failed to initialize
How can read app.config in VB Net5?
I tried using an app.config file in a .NET 5.0 app and I got the same exception. Unlike you, I looked a bit further and saw that it also said that it encountered an unknown section, i.e. system.diagnostics. I then commented out the <system.diagnostics> element in my config file and it worked as expected. I'm not sure what you would do if you actually needed to use that section but it doesn't look like you do so it shouldn't be a problem to comment it out or delete it.

Configuration Manager app settings return nothing from the app.config

I have a windows app in which there are few keys configured as follows.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="Mode" value ="Interval"/>
<!-- <add key ="Mode" value ="Interval"/>-->
<add key ="IntervalMinutes" value ="1"/>
<add key ="ScheduledTime" value ="18:41"/>
<add key ="mainConnection" value ="hidden"/>
<add key ="tbl_ref_date" value ="2017-01-11 11:46:38.833"/>
<add key ="trg_ref_date" value ="2017-01-09 19:03:08.840"/>
<add key ="ScheduledTime" value ="18:41"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
</configuration>
But in my code behind I tried to access a value, but it returns nothing.
Also I tried this which returns 0
System.Configuration.ConfigurationManager.AppSettings.AllKeys.Length
Why this happening..
This is my project structure

Connection string error between projects with EF

My solution exits out of 3 Projects:
SP_Class_Library contains my EF model
SP_Control_Library is a class library that contains all my custom and
user controls
SP_EF_TEST is my Form Application
I created a custom control cc_User_DropDown with the following code
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
LoadUsers()
End Sub
Private Sub LoadUsers()
Dim UserList As List(Of SP_User) = Nothing
UserList = (From c In ent.SP_User
Where c.usr_Active = True
Select c
Order By c.usr_Name).ToList
Dim blank As New SP_User
blank.usr_ID = 0
blank.usr_Name = "Please select a user..."
UserList.Insert(0, blank)
Me.DisplayMember = "usr_Name"
Me.ValueMember = "usr_ID"
Me.DataSource = UserList
End Sub
The problem comes when I try and add the custom control to either u_Users or Form1 I get the error:
If I comment the code and build I can add the control, but as soon as I uncomment the code and build I get the following:
I have tried suggestions that say I must add the app.config to all the projects, Copy the connectionstring to all the .config files and remove the .config file from the dll and add it to the Form Application but it does not work.
Here is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog" />
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<connectionStrings>
<add name="SPEntities" connectionString="metadata=res://*/SP_Model1.csdl|res://*/SP_Model1.ssdl|res://*/SP_Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SPDEV;initial catalog=SP;persist security info=True;user id=sa;password=xxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

Default Role Provider could not be found when using SimpleMembershipProvider

I'm trying to get authorization working on asp.net mvc4, so I try to use WebSecurity.
WebSecurity.InitializeDatabaseConnection("tradefairindia", "Users", "Id", "Username", false);
I've put this into Global.asax, and this is where the error comes, "Default Role Provider could not be found".
On the internet I read that I had to add this line of code to my web.config <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">. But I had it added already because of previous errors.
How can I resolve this problem??
Edit:
When I change it to defaultProvider="SimpleRoleProvider" it gives me a new error. It says
The type or namespace name 'Data' does not exist in the namespace 'WebMatrix' (are you missing an assembly reference?)
I fixed it by changing the defaultProvider to SimpleRoleProvider. The second error I fixed by adding Webmatrix.data as a reference, and going to its property's and put copy local on true. I dont know how this fixes it, if anyone can elaborate that would be nice.
Here is my web.config for anyone who bumps into the same prob:
<system.web>
//...
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
//...
</system.web>

REST methods not accessible when hosting wcf service in IIS

I have a WCF REST service that exposes a method in class GreetService:
[ServiceContract]
public class GreetService
{
[WebGet(UriTemplate = "greet/{name}")]
public String GreetName(string name)
{
return "Hello " + name;
}
}
Also, I registered a route in Global.asax:
RouteTable.Routes.Add(new ServiceRoute("GreetService", new WebServiceHostFactory(), typeof(GreetService)));
Now when i run this directly from visual studio, I am able to leverage the UriTemplate and invoke this method using a GET call to
http://localhost:5432/GreetService/greet/JohnDoe
However, after deploying this to IIS7 by creating a Greet.svc file for it, I am observing the following behavior:
I can call http://localhost:5432/Greet.svc and it says that a service has been created
I can point wcftestclient to http://localhost:5432/Greet.svc?wsdl to generate a test client which can call GreetName() directly
However, I can't call http://localhost:5432/Greet.svc/GreetService/greet/JohnDoe nor http://localhost:5432/Greet.svc/greet/JohnDoe although I expected to be able to since I specified an empty relative endpoint address in the corresponding web.config file prior to hosting it in IIS7.
Any ideas why the WebGetAttribute is not working in IIS? Or is there something else I am doing wrong?
EDIT:
This is the ServiceModel part of my web.config file which resides in the directory that IIS uses:
<system.serviceModel>
<!-- <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> -->
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
EDIT 2: For completeness' sake here is my full web.config file:
<?xml version="1.0"?>
<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>
<handlers>
<add name="UrlRoutingHandler"
preCondition="integratedMode"
verb="*" path="UrlRouting.axd"
type="System.Web.HttpForbiddenHandler,
System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
<system.serviceModel>
<!--<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>-->
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
If you've defined your route to be:
new ServiceRoute("GreetService", .....
then you should be able to call your service at
http://localhost:5432/YourVirtualDirectory/GreetService/greet/JohnDoe
and if your web app is deployed to your IIS root (not in a virtual directory), that would be:
http://localhost:5432/GreetService/greet/JohnDoe
When defining a ServiceRoute, that's done to get rid of having to specify the Greet.svc file, really - the ServiceRoute entry already contains all the information IIS needs to instantiate your service and call it - no need for having the *.svc file involved in your URL (the svc file basically contains the same info your ServiceRoute entry has).
Change the line in your global.asax.cs to read:
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(GreetService)));
and put the following in your web.config right under the root <configuration> node:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing, Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=31BF3856AD364E35" />
</modules>
<handlers>
<add name="UrlRoutingHandler"
preCondition="integratedMode"
verb="*" path="UrlRouting.axd"
type="System.Web.HttpForbiddenHandler,
System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
(do make sure you're using the right .NET version) and see what that does for you.
NOTE: please post the web.config, at least the system.servicemodel part.
You normally use either the Route-based configuration or a .svc file, not both, but that's orthogonal to your problem. FWIW, you should be able to kill the .svc file once you get the service working and just use the route.
Since you're able to generate WSDL and call it, that sounds like you might not have webhttp as an endpoint behavior?
Make sure you have an endpoint behavior defined like this (can be a diff name of course)
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
and then make sure your service endpoint includes behaviorConfiguration="webHttpBehavior"
The problem is machine config missing the following section
<configSections>
<sectionGroup name="system.serviceModel" type="System.ServiceModel.Configuration.ServiceModelSectionGroup, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="standardEndpoints" type="System.ServiceModel.Configuration.StandardEndpointsSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</sectionGroup>
</configSections>
Add it on top of web.config (after the opening tag of <configuration> ) should fix this problem.