Quickly create a 12-digit Number Generator Securely in C#

Step 1:

Add Reference to your project to System.Security

Step 2:

In you class add:

using System.Security.Cryptography;

Step 3:

In your class add the following  method using RNG encryption service provider to enforce secuity on your random number:

public long GetNextInt64()
var bytes = new byte[sizeof(Int64)];
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();

long random = BitConverter.ToInt64(bytes, 0);

//Remove any possible negative generator numbers and shorten the generated number to 12-digits
string pos = random.ToString().Replace(“-“, “”).Substring(0, 12);

return Convert.ToInt64(pos);


Easy huh??

Error during serialization or deserialization using the JSON JavaScriptSerializer


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();



function getUsersUpdate() {
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);

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:

<jsonSerialization maxJsonLength=”99999999″/>

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=, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ requirePermission=”false” allowDefinition=”Everywhere”/>

if not, add that too.

Error: NHibernate.LazyInitializationException was unhandled by user code


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();


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.


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:


Id(x => x.Id);

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


Id(x => x.Id);

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

MVC Passing Parameters from one view to another through Query Strings

Pass Parameter to another view of another controller:

In view:

@Html.ActionLink(“Movies”, “Index”, “Movie”, new { CategoryId = item.Id}, null)


  • 1st par “Movies” refers to the link text visible to user
  • 2nd par “Index” is the page you want to link to in the other view
  • 3th par “Movie” is the other View folder you want to link to
  • 4th par is the actual parameter you want to pass, in this case we will be passing category Id to filter the movie list by category


In the Movie Controller where we will retrieve the Query String:

public ActionResult Index(int CategoryId)

return View(new GetMoviesByCategory(CategoryId);  //replace text in brackets with own methods or preferences.


P.S Make sure Parameters are the same (CategoryId) in both View and Controller. You can also pass and assign a parameter manually by replacing item.Id with the CategoryId for instance:

new { CategoryId = 5 }

LINQ for Nhibernate

References Required:

  • using Domain;   //this is the folder where your entities are found
  • using NHibernate;
  • using NHibernate.Criterion;

Other Requirements:

  • Nhibernate / Fluent Nhibernate
  • Linq for Nhibernate
  • Nhibernate Session Helper (can find ready ones on the internet)

1. Return a row by integer Id

public Movies GetById(intId)

using(ISession session = NHibernateHelper.OpenSession())

return session.Get<Icon>(Id);


2. Return a simple IList<> / Return all rows in a table:
public IList<Movies> GetAll()

using(ISession session = NHibernateHelper.OpenSession())

return session.CreateCriteria(typeof(Movies)).List<Movies>();


3. Return an IList<> with a WHERE clause:

public IList<Movies> GetMoviesByCategory(int CatId)

using(ISession session = NHibernateHelper.OpenSession())

return session.CreateCriteria(typeof(Movies)).Add(Restrictions.Eq(“CategoryId”, CatId)).List<Movies>();


4. Return an IList<> with a 3-way JOIN and WHERE clause

public IList<MovieImages> GetMovieImagesByMovieCategory(int CatId)

IList<Movie> movies = GetAllMovies(); //Change with your query
IList<MovieCategory> categories = GetAllCategories(); //Change with your query
IList<MovieImages> images = GetAllImages(); //Change with your query

using(ISession session = NHibernateHelper.OpenSession())

return (from mi in images
join m in movies on mi.Movie.Id equals m.Id
join c in categories on m.CategoryId.Id equals c.Id
where c.Id == category.Id
select mi).ToList<MovieImages>();


5.Convert List to IList<>

IList<MovieImages> list = myNormalList.ToList<MovieImages>(); //myNormalList would be a common List()