Error during serialization or deserialization using the JSON JavaScriptSerializer

Scope: 

Returning a DataTable from a WebMethod to JavaScript using C#

WebMethod in code behind:

[WebMethod(BufferResponse = false, CacheDuration = 5)]
public static string GetUsers()
{

//Using Subsonic //Replace with your queries to return a dataset
System.Data.DataSet users= DB.Select().From(Tables.Users).ExecuteDataSet();

return users.GetXml();

}

JavaScript:

function getUsersUpdate() {
$.ajax({
type: “POST”,
url: “default.aspx/GetUsers”,
data: ‘{}’,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: OnCompleteSuccess,
failure: OnCompleteFailure,
error: OnCompleteError
});
return false;
}

function OnCompleteSuccess(response)
{
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
alert(xml);
}

function OnCompleteFailure(response) {
alert(“Failed: ” + response.reponseText);
}
function OnCompleteError(response) {
alert(“Error Occurred: ” + response.responseText);   //This is where the JSON serialization error is caught
}

Reason for error:

Your DataSet if returning large amount of JSON data while the web.config is configured to allow a max amount of JSON serialization data.

Solution to error:

Remove the max amount of data allowed in the web.config to cater for large amount of JSON data.

In the Web.Config:

Under the <system.web> </system.web> copy and paste the following configs:

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength=”99999999″/>
</webServices>
</scripting>
</system.web.extensions>

P.S: Make sure that under the <configsection> within the <sectiongroup> you have one section similar to the below:

<section name=”jsonSerialization” type=”System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ requirePermission=”false” allowDefinition=”Everywhere”/>

if not, add that too.

Error: NHibernate.LazyInitializationException was unhandled by user code

Error:

When using Fluent Nhibernate I have encountered several times the following exception:

NHibernate.LazyInitializationException was unhandled by user code

In my situation, the error was showing up when I try to get details from a referenced  column. For instance, from a movies table I have several columns, one of which was CategoryID. In my details view, I wanted to display CategoryName rather than CategoryId so my code looked similar to:

string Category = movie.Category.Name.toString();

That’s when the error was coming up stating that the session was closed. However, when using:

string Category = movie.Category.Id.toString();

Cause:

The last example when I was getting the Id, the error was not fired since the CategoryId is within the same table and thus the session would be open. However, when attempting to get the Category Name, the session would be closed since that session was opened specifically for the movie table.

Solution:

To solve this I simply modified a line of code in my mapping class where I was adding the reference and added the fetch join:

before:

Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”);

After:

Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”).Fetch.Join();

Error: system.data.entity.edm.edm entitytype entity type has no key defined

Cause: 

No Primary Key is defined. Visual Studio generally looks out for an entityproperty int ID or similar and set it as a primary key. However, if our primary key is something like “Username” then we need to specify which one it is.

 

Solution:

Include the namespace:

using System.ComponentModel.DataAnnotations;

Before your Primary Key add the following attribute:

[Key]

 


FileUpload Error: Object reference not set to an instance of an object

I have come across an error of fileUpload where it kept on saying that the fileUpload.FileName is not set to an instance of an object.

After a lot of debugging and testing I realized that AJAX is limited to update panels. Therefore, make sure you do not place the file upload inside an update panel.

FileUpload requires a FULL POSTBACK!

Error: Cannot use a leading .. to exit above the top directory.

Error: Cannot use a leading .. to exit above the top directory.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Cannot use a leading .. to exit above the top directory.

Solution:

Check The Master page or any Default Page currently using before error appears.

Make sure that references in the <head> </head> section do not go above directory listings.

simple basic example:

If your page is in the main project:

ERROR:         <link href=”../CSS/help.css” rel=”stylesheet” type=”text/css” />

SOLTION:    <link href=”CSS/help.css” rel=”stylesheet” type=”text/css” /> //Removing the ../ 

                        <link href=”<%= ResolveUrl(“~/”) %>CSS/help.css” rel=”stylesheet” type=”text/css” /> //When using ASP.NET we can resolve the URL when not sure about the path

Error: The Controls collection cannot be modified because the control contains code blocks (i.e. )

Error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

SOLUTION:

Search within the <head> </head> part of your page and look for any content with the following characters “<%” or use ctrl+F to look for them.

Make sure you gather all <% parts and place them in a simple PlaceHolder, no matter if they are placed in style tags, script tags or simple html tags.

Example:

<asp:PlaceHolder runat=”server”>

<script type=”text/javascript” src=”<%# ResolveUrl(“~/scripts/jquery.js”)%>“></script>

<script type=”text/javascript”>

function SearchUser() {

document.getElementById(“<%= txt_search.userID%>“).value = “”;

}

</script>

</asp:PlaceHolder>

Error: It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

Error: It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level

Cause: Such error is usually due to a project opened as a Website

Solution: Close Application and open sln (solution file)  or all files as Open Project not Open Website.

Storing Greek | Polish | Cyrillic (Russian) Alphabet in Database

When saving cryillic alphabet or other languages which do not use the english alphabet, the datatypes text and varchar do not support the alphabet symbols.

It usually turns all text into ??????

For instance I had tested saving “Интернет-программирование ” into a column with datatype text and it saved all as ” ???????- ? ???? ???”.

In order for this not to happen we simply save the column with the datatype nvarchar(MAX) since nvarchar supports a vast range of symbols which other datatypes do not. The only disadvantage of such datatype will be that it takes some more space than other datatypes.

PS. To send Such alphabets in an email it is required to first add the following:

MailMessage mm = new MailMessage(“EmailAddress”, “EmailAddess”);

mm.IsBodyHtml = true;
mm.SubjectEncoding = System.Text.Encoding.UTF8;
mm.BodyEncoding = System.Text.Encoding.UTF8;

Error: String was not recognized as a valid DateTime (SOLUTION)

DateTime

This happens mainly due to the fact that the actual accepted date format is not dd/MM/yyyy as we all prefer to use it, but instead it is MM/dd/yyyy. Therefore, all we need to do is convert it to such format by using ParseExact.

Below is the exact code you will need to solve issue, replace the DateAsString “25/09/2012” to your label, textbox or whatever your requirements.

Continue reading