Azure Tools 2.6 troubles

Some days ago i noticed that was available the 2.6 update of Azure Tools for Visual Studio 2013, and obviously..immediately installed.
Until now i was working on Windows Phone 8.1 projects, then i decided to try an Universal App, and ..error: “No exports were found that match the constraint…”, with a plethora of other error messages; project not created.
After some struggle, the solution : the uninstallation of the Azure Tools 2.6 for Vs 2013, leaving the previous versions 2.5 and 2.4 installed.
Featured image
After that, the creation of an Universal App is successfully.
I’m using Windows 8.1 in English, Visual Studio 2013 in English, both with the latest updates: how is possible that in Microsoft no one got this error while trying to create an Universal App, the new Microsoft Verb ?

Categories: Azure

Azure Fixit demo..fix

Microsoft has a lot of material for the Azure beginners, for example there is an interesting ebook with a page for the course code.

In the downloadable code there are some PowerShell scripts , that prepares the demo environment (SQL db, web app) in your Azure subscription.

These scripts are in the \fixit\C#\Automation folder.

It must be installed the Azure Powershell extensions, this can be done from the Web Platform installer.

The instructions say that must be launched the New-AzureWebsiteEnv.ps1 , but if you try, does not work.

The code in New-AzureWebsiteEnv.ps1 and New-AzureSql.ps1 must be corrected, where there is the line

Get-AzureSubscription -Current

Must be substituted with

Get-AzureSubscription -Current -ExtendedDetails

It seems that from a certain point in time is necessary to add the ExtendedDetails switch, otherwise you don’t get every needed bit.

But wait, don’t launch the script now.

The Azure PowerShell has a local cache, that could not be correctly initialized.

Then go to C:\Users\\AppData\Roaming\Windows Azure Powershell, delete everything.

Launch the PowerShell command line (better if as Administrator, i have done this but i don’t know if really needed)

Write at the prompt Get-AzurePublishSettingsFile and press return.

Immediately appears a Window , with the login request if needed, where is requested to download a file.

Still In the Azure Powershell command write Import-AzurePublishSettingsFile, return: you are prompted for the previously downloaded file.

Notice that in C:\Users\\AppData\Roaming\Windows Azure Powershell appears some files.

Now in the Azure PowerShell command you can make a cd (ms-dos Change Directory i mean…), then launch


This approach worked for me.

Categories: Azure

Oracle development notes

After many years (Oracle 8..) i’m back to develop on Oracle (using Microsoft Windows). So, after some problem, here a little quick guide for starting with the current versions (April 2015). Before of all, must be installed the java JDK, the 64 bit package jdk-8u40-windows-x64.exe or 32 (jdk-8u40-windows-i586.exe) depending from your system. Then must be installed , as already written in this post, the ODAC component: in this page for the 64 bit version (is recommended the version with installer, not the Xcopy version) ; the 32 bit version here. The main product for the developer is Oracle SQL Developer from here. The Oracle SQL Developer is installed by default in c:\app, the folder c:\app\client\<your_windows_user_name>\product\12.1.0\client_1\Network\Admin is the default place where to place the tnsnames.ora file, needed for the Oracle connections. We have 2 servers, one for development and the other is the official database:

        (ADDRESS =
          (COMMUNITY =
          (PROTOCOL = TCP)
          (Host = )
          (Port = 1521)

     (ADDRESS = (PROTOCOL = TCP)(HOST = srv-vrj)(PORT = 1521))
       (SERVICE_NAME = XE)

Note that the development entry is using the IP , instead for the official database is used the hostname. If must be used the hostname for some reason (as in this case) could be useful to map the hostname to the ip in C:\Windows\System32\drivers\etc\hosts, in our case:

# Copyright (c) 1993-2009 Microsoft Corp.
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
# For example:
#          # source server
#              # x client host

# localhost name resolution is handled within DNS itself.
#       localhost
#        ::1             localhost        srv-vrj

In order to work, it must be verified that the 1521 port is opened in the firewalls. Launching SQLDeveloper there are 2 problems that you can encounter. The first is the language , for example the software is working in French or Italian and in the preferences menu there is nothing for the language. The language setting in English is done by adding the line AddVMOption -Duser.language=en In the file <path where you unzipped SQL developer>\sqldeveloper\bin\sqldeveloper.conf; another strange problem could be the error ORA-01882: timezone region not found.
This is resolved by adding in sqldeveloper.conf AddVMOption -Duser.timezone=CET.
In SQL Developer we can add a connection selecting the TNS item: 02-04-2015 15-51-19 And we can expand and see the list of tables, views, etc. below the connection name node. 02-04-2015 16-15-14

maxJsonLength property

I was working on a asp:DataGrid table , where in every cell there is an asp:Textbox for immediate editing (think to a sort of Excel).
Then with an html button is called the javascript method save:

function save() {
    $get('ContentPlaceHolder1_UpdateProgress1').style.display = 'block';
    var strSql = "";
    var strPartSql = "";
    $("input.editqt").each(function () {
        var strHtmlId =;
        var arrValues = strHtmlId.split("_");
        var strId = arrValues[1];
        var strValue = $("#" + strHtmlId).val();
        if (strValue.trim() === "")
            strValue = "0";
        strPartSql = "UPDATE TSG123_VoyageRes SET Qt = " + strValue + " WHERE ID_Voyage_Res = " + strId + "; ";
        strSql += strPartSql;
    PageMethods.SaveMatrix(strSql, saveCallback, saveErrorCallback, "save");

function saveCallback(result, response, context) {
    $get('ContentPlaceHolder1_UpdateProgress1').style.display = 'none';
    window.alert("Save success.");

function saveErrorCallback(result, response, context) {
    $get('ContentPlaceHolder1_UpdateProgress1').style.display = 'none';
    if (result._timedOut)
        window.alert("Timeout saving");
    else {
        if (result !== null)
            window.alert("Error saving.");

The javascript code calls an PageMethod (the web site uses ASP.NET 4, VB.NET , Microsoft Ajax Toolkit), defined as:

<System.Web.Script.Services.ScriptMethod(), System.Web.Services.WebMethod()> _
Public Shared Sub SaveMatrix(ByVal sql As String)
    UserFrameworkClass.AccessDB.Database.SetData(sql, Data.CommandType.Text)
End Sub

In practice from the javascript side is generated (not the best method..) a long SQL string, in the Page method is launched “as is” into SQL Server.
At a certain point the datagrid became bigger, and trying to save , crash: error from javascript:
“Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.”
The solution was to add these lines in web.config:

      <jsonSerialization maxJsonLength="2147483647"/>

No more errors, until these pages will be rewritten in a more solid manner.

Arbitrary values in asp:Datagrid

Working at a ships loading planner, i received this request: we can have more work turns, for every turn one or more squads (from 1 to 5).

But there should be an optional special squad , the “0” squad, that must be represented with the “SA” string; note also that only on the first row for every turn must be visible an Word export icon.

The work turn on the db is an Int.. how to write “SA”?

We are speaking of an .NET 4 solution, using VB.NET, the DataGrid is defined as

<asp:DataGrid ID="DG" runat="server" AutoGenerateColumns="False" ShowHeader="true"
    EnableViewState="true" CssClass="DGBorder" Width="99%" Height="1%" HorizontalAlign="left">
    <AlternatingItemStyle CssClass="DGRow2" />
    <SelectedItemStyle CssClass="DGSelect" />
    <ItemStyle CssClass="DGRow1" />
    <HeaderStyle />
        <asp:BoundColumn DataField="Day" HeaderText="Date" DataFormatString="{0:dd/MM/yyyy}">
            <ItemStyle CssClass="DGBorder" Width="200px" HorizontalAlign="Left" />
            <HeaderStyle HorizontalAlign="Center" Width="200px" />
        <asp:BoundColumn DataField="Turn" HeaderText="Turn">
            <ItemStyle CssClass="DGBorder" Width="100px" HorizontalAlign="Left" />
            <HeaderStyle HorizontalAlign="Center" Width="100px" />
        <asp:BoundColumn DataField="Hours" HeaderText="Hours">
            <ItemStyle CssClass="DGBorder" Width="3em" HorizontalAlign="Center" />
            <HeaderStyle HorizontalAlign="Center" Width="3em" />
        <asp:BoundColumn DataField="Squad" HeaderText="Squad">
            <ItemStyle CssClass="DGBorder" Width="100px" HorizontalAlign="Center" />
            <HeaderStyle HorizontalAlign="Center" Width="100px" />
        <asp:ButtonColumn DataTextField="Squad" HeaderText="Fold" DataTextFormatString="<img src=Imgs\word.png border=0>" CommandName="PrintFold">
            <ItemStyle CssClass="DGBorder" Width="100px" HorizontalAlign="Center" />
            <HeaderStyle HorizontalAlign="Center" Width="100px" />

The solution is the SetRenderMethodDelegate method:

Protected Sub DG_ItemCreated(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DG.ItemCreated
    If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.SelectedItem Then
        Dim drv As DataRowView = TryCast(e.Item.DataItem, DataRowView)
        If drv Is Nothing Then
            Exit Sub
        End If
        If strDataRif = String.Empty Then
            strDataRif = drv.Row("Day").ToString()
            strTurnoRif = drv.Row("Turn").ToString()
        End If
        strTempData = drv.Row("Day").ToString()
        strTempTurno = drv.Row("Turn").ToString()
        If strTempData <> strDataRif Or strTempTurno <> strTurnoRif Or boolForceFirst Then
            strDataRif = strTempData
            strTurnoRif = strTempTurno
            boolForceFirst = False
            ' 3 = position of column, starting from 0 , in DataGrid
            e.Item.Controls(3).SetRenderMethodDelegate(New RenderMethod(AddressOf RenderCustom))
            e.Item.Controls(4).Controls(0).Visible = False
        End If
    End If
End Sub

Protected Sub RenderCustom(ByVal writer As System.Web.UI.HtmlTextWriter, ByVal Container As System.Web.UI.Control)
    If DirectCast(Container, System.Web.UI.WebControls.TableCell).Text = "1" Then
    End If
End Sub

If we asked to create the SA squad, we have 0 as number and then must be changed with “SA” , otherwise the squad numbering begins with 1 and must not be changed.
The result:


Strange behaviors in Crystal

I found today a strange behavior with Crystal Reports .NET , using Visual Studio 2010.
In a recordsource there are 2 numeric (integer) columns that were displayed in the preview window, inside Visual Studio.
At runtime for these 2 colums, nothing: no values displayed, even the headers.
This in a subreport; this one in origin had the same SQL of the main report.
Then the datasource of the subreport was changed, some columns previously used in the report was deleted, substituted with other columns, with different names.
I tried even to change the original subreport SQL (a JOIN between 2 CTE, inside every CTE a PIVOT) with a plain SQL (SELECT ‘value’ AS columnname) but without success: still no data displayed at runtime inside the subreport.
The solution is very strange, a Crystal formula (Vb syntax):

If IsNull({Command.TotalTSG}) then
    formula = 0
    formula = {Command.TotalTSG}
end if

If the fields are placed directly in the Crystal editor, data visible in preview but nothing at runtime; instead it works also at runtime with Crystal formulas: data displayed.
Note: all of the remaining fields (also integers) are displayed if placed directly on the report (but are fields in common as name between the main and the subreport), even without a formula.
Mysteries of Crystal Reports.

Outlining in Eclipse

In Visual Studio 2013 by right clicking the code there is an useful menu for code outlining

Is so useful CTRL+MO…

In Eclipse Luna i struggled for a while in order to find the same feature, not easy to discover;

CTRL+SHIFT+/ on numeric keypad is the same of CTRL+MO on Vs2013; CTRL+SHIFT+* (on numeric keypad) is the same of CTRL+ML

The trick works only if is activated the folding: by right clicking on the line numbers appears the menu, with the folding activated are visible the controls (in yellow in the image) for expanding and retracting the code.


Categories: .NET, Android

WebAPI2 errors management in Android

In my last project is used an SQL Server 2014 Phones table, with an Android app that register the device itself in this table via an WebAPI2 call.

The table is simple:

We have an primarykey named “PK_Phones” on PhoneId.

The PhoneID is the IMEI code, if the device has phone capabilities and is installed an working SIM, or the Android ID.

There are other common fields for multiuser management as the timestamp which is very useful with the Entity Framework 6 used in this solution.

The Web counterpart (created with Visual Studio 2013) is a common MVC5 project using WebAPI2 with Breeze, Angular , Bootstrap, Modernizr, Moment, Ninject, Toastr…an huge blob installed from NuGet using the HotTowel package (Ninject , Jasmine for testing and other package needs to be installed by hand).

The first move was to create an ADO.NET Entity Data Model (here i don’t speak in detail of the project organization) and using “Code first from Database” i created the class representing my table:

namespace net.studioalessi.walkad.dl
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Phones
        public string PhoneId { get; set; }

        public string Manufacturer { get; set; }

        public string Model { get; set; }

        public string Notes { get; set; }

        public string PhoneNumber { get; set; }

        public bool Banned { get; set; }

        public string UtenteModifica { get; set; }

        public DateTime? OraModifica { get; set; }

        public string UtenteInserimento { get; set; }

        public DateTime? OraInserimento { get; set; }

        [Column(TypeName = "timestamp")]
        public byte[] SSMATimeStamp { get; set; }

Then the necessary Controller (right click on Controllers folder->add new scaffolded item->

Web API 2 Controller with actions, using Entity Framework as in figure.

Using the previous Phones class we generate the Controller and the Context, in our case the context is the class PhonesContext:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace net.studioalessi.walkad.dl
    public class PhonesContext : DbContext
        public PhonesContext()
            : base("name=WalkadConn")

        // no virtual ? in the previous EF version was generated as virtual...
        public DbSet<Phones> Phones { get; set; }

        // Also the code below was generated automatically in the previous version.
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
                .Property(e => e.UtenteModifica)

                .Property(e => e.UtenteInserimento)

                .Property(e => e.SSMATimeStamp)

And the Controller is changed from the generated version to an BreezeController

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Walkad.Models;
using net.studioalessi.walkad.dl;
using Breeze.WebApi2;

namespace Walkad.Controllers
    public class PhonesController : ApiController
        private IPhoneRepository _repo;

        public PhonesController(IPhoneRepository repo)
            _repo = repo;

        public string Metadata()
            return _repo.MetaData;

        public async Task<IHttpActionResult> RegisterImei(PhoneModel model)
            PhonesContext objT = new PhonesContext();
                Phones objTrace = new Phones
                    UtenteInserimento = "RemoteUser",
                    OraInserimento = DateTime.Now,
                    Model = model.Model,
                    Manufacturer = model.Manufacturer,
                    PhoneId = model.Imei
                await objT.SaveChangesAsync();
                return Ok();
            catch (Exception ex)
                return BadRequest(ex.ToString());

The PhoneModel was created by hand and is the model representing the JSON string sent from the client (Web site or Android app, as in this case)

public class PhoneModel
    public string Imei { get; set; }

    public string Manufacturer { get; set; }

    public string Model { get; set; }

At this point we can try the service from Fiddler

By clicking “Execute” we can see that our call was successful

And in SQL Management Studio we can see the new record:

Ok , we can create the Android app with Eclipse Luna (with the Android Developer Tools).

I don’t show the details, i created an simple Android app with an menu item that calls the routine named registerThisDevice:

private void registerThisDevice() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    String strBasePath = sharedPrefs.getString((String)getText(R.string.pref_httpbase), "");
    new WebApiRegisterImei().execute(strBasePath + "/api/Phones/RegisterImei");

Note the i’m using the IP , the tablet used for the test is in the same WiFi network but is not Windows, is not able to resolve the NETBIOS name.

Note also that we web address is registered in a Preference that defaults to my WiFi address.

In order to follow the best practices , the routine WebApiRegisterImei is an AsyncTask so is called with .execute() passing the server address as String argument (in every case , if we don’t use an AsyncTask we get an NetworkOnMainThread exception):

private class WebApiRegisterImei extends AsyncTask<String, Void, JSONObject> {
    ProgressDialog myProgressBar;
    public String ExportResult = "";
    public String LastException = "";
    public Exception LastExceptionObject;       

    protected JSONObject doInBackground(String... params) {
        BufferedInputStream  in = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            // the Android docs says that HttpURLConnection uses the GET method by default. It will use
            // POST if setDoOutput(true) has been called. Other HTTP methods
            // (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with
            // setRequestMethod(String). Anyway forcing POST as request method is useful.
            JSONStringer vm;
            vm = new JSONStringer()

            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            DataOutputStream wr = new DataOutputStream (
                    urlConnection.getOutputStream ());
                    wr.writeBytes (vm.toString());
                    wr.flush ();
                    wr.close ();                           
            int statusCode = urlConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                // handle unauthorized (if service requires user login)
            } else if (statusCode != HttpURLConnection.HTTP_OK) {
                InputStream errorstream = urlConnection.getErrorStream();
                BufferedReader br = null;
                if (errorstream == null){
                    InputStream inputstream = urlConnection.getInputStream();
                    br = new BufferedReader(new InputStreamReader(inputstream));
                    br = new BufferedReader(new InputStreamReader(errorstream));
                String strResponse = "";
                String strTemp;
                while ((strTemp = br.readLine()) != null){
                    strResponse += strTemp;
                strResponse = strResponse.toLowerCase();
                    ExportResult = getErrorDuplicated();
                    return null;
            ExportResult = getExportCompleted();
        } catch (Exception e) {
            LastException = e.toString();
            LastExceptionObject = e;                
        } finally {
            if (in != null){
                try {
                } catch (IOException e) {
            if(urlConnection != null){
        return null;

    private String getErrorDuplicated() {
        return (String)getText(R.string.imeiduplicatederr);

    private String getExportCompleted(){
        return (String)getText(R.string.registerimeidone);

    protected void onPreExecute() {
        try {
            myProgressBar = new ProgressDialog(MainActivity.thisMainActivity, ProgressDialog.STYLE_SPINNER);    
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), (String)getText(R.string.genericerror),Toast.LENGTH_LONG).show();                  

    protected void onPostExecute(JSONObject result) {
        try {
            if(LastException.length() > 0){
                Toast.makeText(getBaseContext(), (String)getText(R.string.genericerror),Toast.LENGTH_LONG).show();   
                Toast.makeText(MainActivity.thisMainActivity, ExportResult, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), (String)getText(R.string.genericerror),Toast.LENGTH_LONG).show();                  

Examining the code , we can note that onPreExecute and onPostExecute are the only places where we can interact with the main thread and relative controls (the progress bar) so in the background part we register the exceptions details in one string and one object, examining them on the onPostExecute.

Note the use of the JSONStringer: debugging the code you can see that is created the JSON string as used in Fiddler.

If all is ok, we can see that in SQL Server is written a new row in the Phones table.

The test for statusCode != HttpURLConnection.HTTP_OK was the difficult part to discover how it works, the subject of this post.

If you reissue the command from the Android app on the same device you violate the primary key, so the WebAPI code goes in the Exception and is sent to the client “BadRequest” (HTTP error 400) instead of “Ok”(200), sending as other info ex.ToString().

The management of the returned error is done as you can read in the code: we need to examine the returned stream , by reading this stream we can create a string that contains the original ex.ToString, for example

{"$id":"1","$type":"System.Web.Http.HttpError, System.Web.Http","Message":"System.Data.Entity.Infrastructure.DbUpdateException: 
An error occurred while updating the entries. See the inner exception for details. ---> 
System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. 
See the inner exception for details. ---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_Phones'. 
Cannot insert duplicate key in object 'dbo.Phones'. The duplicate key value is…..

So in the Android code we search if the string contains the name of the primary key , giving to the user an scoped message, or we give to the user an generic message and the code uses Splunk Mint Express for registering all infos about the unmanaged exception (that could be an network failure, and so on).

Activity not created in Eclipse

Every time that there is an Android update, i’m prepared to troubles.

Recently i updated ADT to version 24.0.2 , and created a new project.

When i tried to add a new Activity, nothing! no xml for the screen and no Class.

In Logcat only an obscure message “Style contains key with bad entry”.

Also troubles with the appcompat_7 library, importing the new version in the workspace an message “No resource found that matches the given name: attr ‘android:actionModeShareDrawable'”

For appcompat, the solution was to change in manifest.xml the targetSDK to “android-21″, after a Project->Clean problem resolved.

After some attempts, the solution for the Activity not created was to uninstall the ADT (Help->installation details->select all ADT->uninstall)

And then reinstall from Help->Install new software:

Finally, it took some additional time to Eclipse for loading but it seems that adding -clean in the Windows shortcut (“<yourpath>\eclipse.exe -clean”) is useful to prevent minor troubles by deleting old cache entries.

Categories: Android

Get every new post delivered to your Inbox.