Entity Framework enable migration based on DbContext situated in another project

In order to create a new locally database to run tests you can create your migrations in the test project by taking in care that you can use your repository db context in another VS project.

To achieve this result you can do the following in the Package Manager Console

Enable-Migrations -ContextProjectName MyProject.Repository -ContextTypeName MyProject.Repository.MyDbContext -ProjectName MyProject.Tests -StartUpProjectName MyProject.Tests -ConnectionStringName "MyConnectionString"
Add-Migration "Init Test Db"
Update-Database -ProjectName MyProject.Tests -StartUpProjectName MyProject.Tests -ConnectionStringName "MyConnectionString"

Create a NuGet package for a C# library

In this article we discuss a simple way to create, configure and publish your first c# library through personal NuGet repository.

  • Download NuGet.exe from https://docs.nuget.org/create/creating-and-publishing-a-package
  • Add environment variable path that refer the installed nuget.exe file
  • Build your project in Release mode
  • Get the “bin” folder path where you can retrieve the project assembly
  • Move under your project bin/release folder and copy the generated *.ddl (pay attention: copy only your project assembly file and not all the dependencies) and paste in a new different folder
  • In this folder create these two folders:
    • lib – contains only the project dlls
    • content – contains all the solution content after the build process (Release mode) without the “bin” and “obj” folders
  • Open cmd with admin priviledges:
    • move under the temp folder where you create the folder at the step above
    • enter in the lib folder (> cd lib)
    • run > nuget.exe spec MyAssembly.dll
    • this creates a Nuspec file
    • move the .nuspec file outside the lib folder
    • you must now have this configuration inside the folder:
      • content
      • lib
      • MyAssembly.nuspec
    • edit the NuSpec file as needed (see the section below)
    • then run > nuget.exe pack MyAssembly.nuspec
    • a new MyAssembly.nupkg was created.

Nuspec file configuration

<?xml version="1.0"?>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<copyright>Copyright 2015</copyright>
<tags>Tag1 Tag2</tags>
<dependency id="Newtonsoft.Json" version="7.0.1" />
<dependency id="NLog" version="4.2.1" />
<dependency id="NLog.Config" version="4.2.1" />
<dependency id="NLog.Schema" version="4.2.1" />

In the .nuspec file you can configure all the dependencies that you dll requires. In this way the NuGet repository can download the dependencies when a client install your NuGet package.

Now you can provide this package and retrieve via Visual Studio as all the other libraries.

Manage Session in Asp.Net application

This post illustrate the 3 main steps to manage session in Web Forms application. This is not the only one way to do this, but it’s easy and responsive to a better user experience.

Step 1

In the Global.asax.cs in the Session_Start event add this code:

// Code that runs when a new session is started
if (Context.Session != null)
    if (Context.Session.IsNewSession)//|| Context.Session.Count==0)
        string sCookieHeader = Request.Headers["Cookie"];
        if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
           //if (Request.IsAuthenticated)

and also in the Session_End event


Step 2

Add this in the web.config


Step 3

Create a custom Logout page and add this snippet on the Page_Load

if (User.Identity.IsAuthenticated)



In this post we are going to explain how to use reCAPTCHA in an ASP.NET. application.

It is easy and intuitive to integrate Google’s reCAPTCHA  but you have to pay attention to some “validation” details that we are going to see in the course of the post.

First of all, you need to sign up to get 2 registration keys, a public one and a private one that will have to be used during the integration of this component within the APSX page.

You can download the DLL to be integrated within the site from here.

It is easy to Integrate the library and it can be done by following these steps:

1) Add the library Reference downloaded in VS.

2) Register the dll in the web.config file if you need to reuse the library in several pages

      <add tagPrefix="recaptcha" assembly="Recaptcha" namespace="Recaptcha" />

Or in the page in which you want to integrate the reCAPTCHA

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

3) Put the reCAPTCHA control in a tag <form runat=”server”>


This is what you need to integrate the control within the web application

Everything is fine up to now!

Now let’s see how to solve some problems like the validation of the page and of the reCAPTCHA and especially the hosting security problems.

First, let’s see how to solve the problems related to the hosting servers rights.

As you don’t have the rights in full trust, you can’t invoke the assembly.

The solution to the security problem

You can solve this problem by doing the following things:

  • Download the reCAPTCHA library sources for ASP.NET by checking out from here
  • Open the solution and change the rights in the AssemblyInfo.cs file, like this:
[assembly: AllowPartiallyTrustedCallers()]
  • Fill in and copy the new assembly in your solution ASP.NET.

The validation

To validate the reCAPTCHA control is very easy. Add this code to the button click event that submits the form.

protected void ButtonSubmit_Click(object sender, EventArgs e)
if (Page.IsValid)
< processate il form >
< visualizzate un errore >

This code works perfectly if you don’t have validations on other controls.

To overcome the following problem, you have to validate the control Recaptcha in a different way.

Within the same method as above, you have to include this type of validation in order to have the coexistence of the traditional validation on asp.net controls and the recapcha control.

if (recaptcha.IsValid)
< processate il form >
< visualizzate un errore >

And this is it!

Create and retrieve informations from an index with Lucene.NET

Nowadays, users rely blindly on search engines to find the information they need. For this reason, when building a web application, it is good practice to provide users the opportunity to search for information within the site. Everybody would like to have a search engine that has the same effectiveness and efficiency as the most famous and popular ones.
Well, being able to reach this goal by oneself, namely to build one’s own algorithm, is not that unremarkable.
There are various external solutions that can be incorporated in your website using scripts, such as search boxes “powered by Google”. These solutions are very useful but hardly customizable.
In this article, we’re going to discuss an elegant solution, quick to implement and extraordinarily effective to build your own search engine.
To reach our goal, let’s introduce the library that lies at the bottom of everything. We are talking about Lucene. An open-source library written in Java and available for other platforms too.

What we would like to emphasize in this discussion is how to use this library on .NET platforms in C#.


  1. Importing libraries
  2. Creating an index
  3. Including documents in the index
  4. Retrieving information

Creating a project and importing libraries

First of all, we need to create a new project in Visual Studio. Once the new project is created, let’s go to reference and right click on “Manage NuGet Packages”. Look for “Lucene” inside the tool. At this point, let’s import the library clicking on “Install”. All the libraries (.dll) necessaries will be imported.

Now that we have the references, let’s start using them.

Creating an index

In the following snippet, the creation of a Lucene index is described.

Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.GetDirectory(@"C:/INDEX_PATH_LOCATION", true);

Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_CURRENT);

Lucene.Net.Index.IndexWriter writer = new Lucene.Net.Index.IndexWriter(dir, analyzer, Lucene.Net.Index.IndexWriter.MaxFieldLength.LIMITED);

Once the index is created, documents can be added inside of it.

Including documents in the index

Lucene can index any kind of information, from text files (.txt, .xml), to documents (.doc, .pdf).

The information to be added inside Lucene data structure depends on the application context.

To add documents to the index, we first have to retrieve the IndexWriter defined at point 2.

IndexWriter writer = // retrieve your index in your own location

// create a document
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();

doc.Add(new Field("id", istance.property.ToString(), Field.Store.YES, Field.Index.NO));
doc.Add(new Field("yourField1", istance.property.ToString(), Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("yourField2", istance.property.ToString(), Field.Store.YES, Field.Index.ANALYZED));



The last step consists in retrieving the stored information in order to submit it to the user in the desired shape.

Retrieving information

To retrieve information related to what the user requests, Lucene Per recuperare le informazioni relative a quanto richiesto dall’utente, Lucene provides a series of methods that allow u sto retrieve the document in the index. The extra effort that the programmer has to make is to turn Lucene results into a list of business objects that will be presented to the user in the desired shape.

To question the index and get teh results take your cue from this snippet

// Multi fields search
MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[] { "yourField1", "yourField2" }, ANALYZER);
Query query = parser.Parse(userQuery);

IndexSearcher searcher = new IndexSearcher(INDEX_PATH);

Hits hits = searcher.Search(query);
List<T> searchResults = new List<T>();

searchResults.AddRange(ProcessQueryResults(hits)); // ProcessQueryResults, your own method to transform Lucene document in your business object


return searchResults;

With these few lines of code and an in-depth library examination to perform more complex queries, you can integrate a real search engine in your website.

Generate MD5 checksum from file

Sometimes we have the necessity to verify that the file we downloded wasn’t corrupted. A way to do this it’s to generate a MD5 checksum and verify the file integrity.

The purpose of this check is to establish that the file has not been modified by someone.

        public string GetMD5HashFromFile(string fileName)
            FileStream file = new FileStream(fileName, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)

            string checksum = sb.ToString();

            return checksum;

Verify internet connection in C#

The method below vefiry the internet connection in the easiest way as possible.

public bool InternetConnectionAvailable()
     bool connectionAvailable = false;
     if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
          connectionAvailable = true;
     return connectionAvailable;