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 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",, Field.Store.YES, Field.Index.NO));
doc.Add(new Field("yourField1",, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("yourField2",, 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;

Send email from Windows Phone

Sometimes an app need to send some information via email. To reach this gol a programmer need to write a few lines of code.

First of all, we can create a button and attach the Click event to send email. After that, in this event we call the EmailComposeTask and thats all.

Now we can build our email with the usual parameters (To, Subject, Body) and then we send the email.

EmailComposeTask email = new EmailComposeTask();
if ("<email_address>" != string.Empty)
     email.To = "<email_address>";
     email.Subject = "Subject message";
     email.Body = "Body message";
     MessageBox.Show("Some error occours.", "WARNING", MessageBoxButton.OK);

Open web browser directly from your application

Sometimes we have the necessity to open web browser from own application to referencing something on the web.

To raise this gol we need for example to add the click event to a button and write few lines of code:

private void Button_Click(object sender, RoutedEventArgs e)
    WebBrowserTask wtb = new WebBrowserTask();
    wtb.Uri = new Uri("", UriKind.Absolute); 

That’s all! The web page will be appear in a few seconds

Create a simple Live Tile

One of the most striking features of the new MS Windows Phone OS are Live Tiles. Customizing your application tile is the argument of this post.

In a few lines of code we can build our custom tile.

The idea is to show, in the back content, the last inserted measure in the application. The application is Pressure Diary, shown in Windows Phone Applications page

public void CreateApplicationTile()
            var appTile = ShellTile.ActiveTiles.First();

            if (appTile != null)
                var standardTile = new StandardTileData
                    Title = App.ApplicationName,
                    BackgroundImage = new Uri("Images/Tile_173x173.png", UriKind.Relative),
                    Count = null, // any number can go here, leaving this null shows NO number
                    BackTitle = App.ApplicationName,
                    BackContent = "Last measure: " + "[" + this.globalMeasure.Systolic.ToString() + "/" + this.globalMeasure.Diastolic.ToString() + "]" + this.globalMeasure.Date.Value.ToShortDateString()


You can use these line of code to build your custom tile.

Write date converter to join localization settings

If you use localization in your Windows Phone application and you need to show date in different formats, you need to built your own data converter to achieve this goal.

To reach this, you can write a DateTimeConverter class that implement IValueConverterInterface, as show below:

    public class DateTimeConverter : IValueConverter

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            if (value != null)
                string dateType = App.cultureInfo.DateTimeFormat.ShortDatePattern;
                return ((DateTime)value).ToString(dateType); // "dd.MM.yyyy"
                return String.Empty;

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            return DateTime.Parse(value.ToString());

Once you do this, you can go to the XAML file and do these 3 things:

  • define a namespace and use this to access you own date converter
  • put this snippet in the PhoneApplicationPage.Resources, like this
     <conv:DateTimeConverter x:Key="MyDateTimeToStringConverter">
  • in the textblock where you bind data you have to add these parameters
<TextBlock Text="{Binding Path=Date, Converter={StaticResource MyDateTimeToStringConverter}, ConverterParameter=\{0:M\}}" >

SQL CE guide for Windows Phone 7.1 – part 2 of 2

Before reading this article read SQL CE guide  for Windows Phone 7.1 – part 1 of 2.

The first thing to do is to create our database, in case the application was started for the first time. It’s a very simple operation, natively managed by the DataContext, that offers us a way to discover if the database already exists  (DatabaseExists(), a Boolean is returned) and another one to create the database (CreateDatabase()).

Actually, the DataContext generated by SQL CE Toolbox already contains a method called CreateIfNotExists() that does everything by itself: it checks if the database already exists and if it doesn’t, creates it.  Moreover, it gives us the opportunity to import an already existing SQL CE Server: with Windows Phone 7.1, it is in fact possible to include a .sdf file in the project, which will be available in read-only, though. The method CreateIfNotExists() is able to find out if the XAP includes a database with a name specified in the DatContext (for example, Orders.sdf) and, if it does, is able to copy it in the Isolated Storage, in order to grand us full access read/write.

When starting the application for the first time, we’ll then have to:

using (DataContext context = new DataContext (DataContext .ConnectionString))

We can notice two things:

  • The use of “using”, as the DataContext is a class that implements the IDisposable Interface. This means that once we’ve finished using it, we have to Dispose it, otherwise the connection to the database is left open, wasting resources. The using statement makes life easier for us, by automatically Disposing the class once the  operations inside the block are finished (successfully or with mistakes).
  • The DataContext generated by SQL CE Toolbox includes a static property called ConnectionString, with the path in which the file is going to be saved on the Isolated Storage. This property has to be used, as in the example, when creating a DataContext instance:
public static string ConnectionString = "Data Source=isostore:/MyDataBase.sdf";
Data entry

To save our objects inside the database, we have to use the DataContext.

using (DataContext context = new DataContext(DataContext.ConnectionString))

As we can notice, we only have to call the InsertOnSubmit method, displayed by the property MyObjects, and to pass the object we want to save in the database.

For the entry, the method InsertAllOnSubmit is available too and it allows us to save several objects at once in the database : it indeed accepts a collection of the IEnumerable<T> type as input (where T is the type we want to save).

Once all the database operations are finished (in our case, just the entry), we have to call the SubmitChanges method, displayed by the DataContext, which generates and runs the SQL code needed. If this method isn’t called, the database operations simply join the queue but are never run.

Data selection

Selecting and searching for elements in the table is very easy, thanks to LINQ, to the lamba expressions and to the properties displayed by our DataContext.

List orders = context.MyObject.Where(x => x.Property > 100).ToList();
Data deletion

In order to erase one or more elements from a table, the methods DeleteOnSubmit and DeleteAllOnSubmit are at our disposal.

The first one is used for removing a specific element and accepts the object to be removed as a parameter.

If you want to remove several elements at the same time instead, the DeleteAllOnSubmit method, which accepts a collection of the IEnumerable type as input parameter, comes to our help.

Data manipulation

To update an already-existing record, simply retrieve it from the collection (as we did in the section on Data selection), make the changes  and afterwards, call the SubmitChanges method.

SQL CE guide for Windows Phone 7.1 – part 1 of 2

Until recently, we were forced to memorize our data in XML files, through serialization. With the coming  of SQL Server CE on Windows Phones 7.1, everything became much easier and much more efficient thanks to the potentiality of a relational database.

Configuration and installation of the tools that make life easier when creating  a database and its context.

On Codeplex, a tool named SQL Server Compact Toolbox, which integrates into Visual Studio and offers a series of features to work with the SQL server CE databases, is available. One of these features, recently introduced, is the automatic generation of Datacontext for projects like Windows Phone.

The add-in for Visual Studio is downloadable from the Visual Studio Gallery.  Once the procedure is finished, let’s open it and we’ll find the item “SQL Server Compact Toolbox” in the Tools Menu. When opening it, we’ll be a shown a window where all the available connections will be listed: this window will be empty, unless we’ve formerly configured some connections to a SQL Server CE database, by using the Visual Studio Server Explorer native tool.

Database creation

This tool gives a chance not only to connect to existing databases, but also to create them: we won’t be able to take advantage of this feature, though, because the tool only allows us to create SQL CE 4.0 databases, while Windows Phone 7.1 is based on the 3.5 version. If we created one based on the 4.0 version, the option to create the DataContext for Windows Phones wouldn’t be enabled.

The tool is nevertheless able to use the Explorer Server: the trick is therefore to create a database with the Visual Studio native tool and, afterwards, to “hook “ on SQL Server Compact Toolbox in order to create our DataContext.

The Trick

Let’s therefore open the Explorer Server (we’ll find it in the View Menu of Visual Studio), let’s click with the right button on Data Connections and let’s choose the Add Connection.

Let’s push the Change button on the Data Source item e let’s make sure that we select the “Microsoft SQL Server Compact 3.5” typology. Afterwards, in the Connection Properties section, let’s click on the Create button in order to choose the position in which the SDF file containing the real database is going to be created. In fact, this file is never going to be used in our application, as the Code-First approach is to have the database automatically generated at the first start of our application. However, we’re going to use it as a “temporary storage” in order to define the structure of our database, to be converted in a DataContext.

Once the database is created, we’ll find our connection in the Explorer Server: if we now go back to the SQL Server Compact Toolbox and push the Refresh button, the list of connections will get updated and the name of our database will appear.

Table creation

The time has come to define entities, or rather the table of our database: let’s therefore go back to the Explorer Server, expand the database just created, click on “Tables” with the right mouse button and select “Create Table”.

Once the Table and its columns was created, if the pattern is to have relations, let’s also define the relationship between tables.

By pushing with the right button on the table, let’s select “Table Properties”. Let’s go to the Add Relations section, let’s give a name to the relation and, in both dropdowns, Primary Key Table Column and Foreign Key Table Column, let’s have the primary key of Table 1, namely Table1Id, and the external key of Table 2, namely always Table2Id, overlap. Let’s push the Add Colomns button: the relation will appear on the panel below. At this point, let’s push the Add Relation button in order to save everything: now the two tables are connected through a one to many relation (in this case).

DataContext Generation

Now that the database has been created, we are ready to “transform” it in an entity and to have LINQ to SQL create the database in the Isolated Storage, through the DataContext.

In order to do this, we need the tool SQL CE Toolbox, which we can recall with the last button in the Explorer Server or from the Visual Studio Tools menu.

Let’s click on the Refresh button (the first one) and our database, which will be recognized as a SQL Sever CE 3.5, will appear. We only have to click with the right button to select “Add Windows Phone DataContext to current Project (beta)” and there you are!

The properties of the different classes will be created with full support at the biding of Silverlight, thanks to the  INotifyPropertyChanged interface implementation. This means that all the checks that are in biding with these properties will be automatically updated at every change in order to reflect the change automatically. At this stage, we’re ready to do some basic operations: insertion,  deletion, change and selection.

SQL CE guide for Windows Phone 7.1 – part 2 of 2