C# 7.0 – #5. reference return function

In addition to function input parameters, which can be passed by value (default) or by reference (with the keyword ref), in C# 7.0 the value return function can also be returned by reference with the same keyword; furthermore it can be stored in a local variable by reference; this local variable stores the memory address of the data and not the value, and then modifiyng this variable means that every variable that points at the same address would be modified too.

Example:

public struct Point
{
   public int X { get; set; }
   public int Y { get; set; }
}

Point[] arr = new[]
{
   new Point {X=12, Y=15 }, new Point {X=56, Y = 754}, 
   new Point {X=65, Y= 39}, new Point {X=21, Y=63}
};

var p = new Point { X = 65, Y = 39 };
ref Point place = ref Find(p, arr);
place.X = 99;
place.Y = 99;    // replaces 3rd Point element in the array
Console.WriteLine("X=" + arr[2].X + " " + "Y=" + arr[2].Y); // prints X=99 Y=99

public ref Point Find(Point p, Point[] points)
{
   for (int i = 0; i < points.Length; i++)
   {
      if (points[i].X == p.X && points[i].Y == p.Y)
      {
         return ref points[i]; // return the storage location, not the value
      }
   }
   throw new IndexOutOfRangeException($"{nameof(p)} not found");
}

In this example Point is a structure, and then it is a value type.
The variable called “arr” contains an array (a reference type) of this structure.
The Find method simply searches a value in that array, but it returns the reference of the Point structure founded, and not its value. You can notice the “ref” keyword before the return type and the “ref” keyword after the return statement. Then the code stores this reference in a local “ref” variable (called “place”) containing the reference to the Point structure searched (the third element of the array).
After that the values are modified (X=99; Y=99), and the array element is modified too, which proves that the memory address has been used instead of the value.

C# 7.0 – #4. Local functions

In C# 6.0 there is no way to declare a function which is local to another function, that is a function visible only inside the body in which is declared. The best way to accomplish this is to declare a delegate variable of type Func<T1,TResult> (or one of the several overloads available), ad then use anonymous methods or lambda expression to write the code of the function, as shown here.

// c# 6.0
Func<int, int, int> sum = (k, y) => {
      return k + y;
};

int c = sum(a, b);

This is not an optimal way to use local function, because of some limitations.

C# 7.0 comes with a true local function, and overcomes all the previous limitations.

Here is an example:

int DoSum(int a, int b)
{
   return LocalSum(a, b);

   int LocalSum(int x, int y)
   {
      return x + y;
   }
}

This is a more natural way to declare and use a local function.

C# 7.0 – #3. New Tuple value type

First of all, at least for C# 7.0 included in Visual Studio 2017 RC, it needs to download the System.ValueTuple Nuget Package, providing the System.ValueTuple structs, which implement the underlying types for C# 7 tuples.

In C# 6.0 after invoking an appropriate Tuple object constructor, the object magically contains a series of properties named Item1, Item2 and so on, one for each type parameter.
There wasn’t an easy way to rename the property names with most significant one.
The best way to accomplish this is to create a custom class that inherits from System.Tuple and then expose the Items properties with significant names.

C# 7.0 comes with a much better Tuple object. First of all it is a value type, then it performs faster (reference type can still be used).

A Tuple variable, known as Tuple literal, containing multiple values each of which may have its own data type:

var axes = ("Axis X", "Axis Y", "Axis Z");
Console.WriteLine("Axes are: {0}, {1} and {2} ", axes.Item1, axes.Item2, axes.Item3);
Console.WriteLine($"Axes are: {axes.Item1}, {axes.Item2}, {axes.Item3}");

Members type are automatically inferred by the compiler, in the above example are string, string, string. Furthermore, it’s possible to override the default named Tuple public properties ItemX

var points = (x: 100, y: 20, z: 50);
Console.WriteLine("Points are : {0} , {1}, {2} ", points.x, points.y, points.z);

And different data types are also possible:

var customerInfo = ("Joe Doe", 10, false); //(string,int,bool)
Console.WriteLine("Customer information: Name: {0}, Discount: {1}, IsProspect: {2} ", customerInfo.Item1, customerInfo.Item2, customerInfo.Item3);

A Tuple member may be a reference type:

var customerInformation = (customer: new Customer { FirstName = "Foo", LastName = "Bar" }, Id: 1 );
Console.WriteLine("Customer details are - Id: {0}, First Name: {1}, Last Name: {2}", customerInformation.Id, customerInformation.customer.FirstName, customerInformation.customer.LastName);

public class Customer
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

A function may return a Tuple literal:

(string description, double x, double y, double z) GetMultipleValues()
{
   return ("Short description", 100D, 120D, 140D);
}

In this case the funcion gets called in this way:

var values = GetMultipleValues();
Console.WriteLine("Values are: string value={0}, first double value={1}, second double value={2}, third double value={3}", values.Item1, values.Item2, values.Item3, values.Item4);

The return statement in the above function may contain the explicit name of each field:

return (description: "Short description", x: 100D, y: 120D, z: 140D);

So in this way the function would get called:

var values = GetMultipleValues();
Console.WriteLine("Values are: string value={0}, first double value={1}, second double value={2}, "third double value={3}", values.description, values.x, values.y, values.z);

C# 7.0 – #2. Numbers code readability

These are some minor but nice improvements regarding numbers code readability:

Now it is possible to write digit separator of number literals:
The digit separator is the “_” character, like in Java language, isn’t it ?

int number = 1_345_782
Console.WriteLine(number); // prints 1345782

This is mostly useful for large numbers.
The separator is ignored by the compiler; it’s just used to improve the numbers readability, and it can be placed anywhere inside the number, but only inside, not at beginning or at the end for instance:

// this not compile
int number = _1_345_782
int number = 1_345_782_

Strange but true, the separator can be multiple, i.e. you can place more than one separator one beside another:

// this is allowed
int strangeNumber = 1_____2______3______4______5;

For decimal number, it cannot be placed right before the separator character:

// this not compile
double numberDouble = 12_.34;

Same for type specifier:

// this not compile
float numbewFloat = 12_f;

Finally it is available the literal for binary constant values (0b):

int binaryNumber = 0b0100_0010;
Console.WriteLine(binaryNumber); // prints 66

C# 7.0 – #1. New out parameter usage

In C# 7.0 using an out variable is simpler than in older version of the language.
In a nutshell an out variable doesn’t need to be declared anymore before its usage, but can be inline declared just before use it, as shown here:


var n = "2";
//pre-declaration for out parameter variable isn't required anymore
//int p;
//inline declaration for out parameter variable.
int.TryParse(n, out int p);
Console.WriteLine(p);

Furthermore, it’s possible to use the var keyword to inline declare the variable, and not the specific type only, as you would do with C# 6.0 with not initialised pre-declared variables.


var n = "2";
int.TryParse(n, out var p2);
Console.WriteLine(p2);

The inline declared out variables are in scope with the code block that contain them, then they can be used after the declaration inside that block.

If you don’t care about some out function parameter you can complitely ignore them by using wildcards (the “_” symbol).


var n = "2";
int.TryParse(n, out int _);

DotNet Core “Unable to load DLL ‘System.Security.Cryptography.Native” error

I was trying to play with DotNet Core in Visual Studio Code, and I was following the instructions as stated here.

After installed Brew I installed the latest version of OpenSSL as required by DotNet Core and then I tried to run the classic “Hello World” program, but the command

dotnet restore

failed with this error:

“Unable to load DLL ‘System.Security.Cryptography.Native”

This error has to do with OpenSSL, or even better with Brew that refuseed to correctly link OpenSSL.

Here is the correct command sequence that needs to correctly setting up OpenSSL for DotNet Core.

brew update
brew install openssl
ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/
ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/
ln -s /usr/local/Cellar/openssl/1.0.2j/bin/openssl openssl

Hope this helps

Blog moved to WordPress

It’s long time I don’t write anything on this blog, I was very busy in recent times, but now the time has come and I intend to regain the time lost.

When I came back to this blog, the first thing I noticed were the look & feel and the software engine on which it was based, SubText, a very old bog software, but still widely used, so I decided to move it to another platform, possibly in step with times, and my choice was WordPress.

Now this blog is based on WordPress engine the most popular online publishing platform, currently powering more than 20% of the web.

Here are the necessary steps (and troubleshooting) to move an entire blog content based on SubText to WordPress:

STEP 1: Subtext – Export your blog content

This is a “one choice” step, because SubText exports its content only in BlogML format, based on XML, and creates an XML file with all your posts, your categories and son forth. To accomplish this, logon to SubText as administrator, go to “Options > Import/Export” and click on the Save button. The check “embed attachment” must remain unchecked otherwise WordPress won’t be able to import the file.

The file’s content is base64 encoded, so I was recommended to convert it as normal text. Don’t worry, fortunately there always are other people who had before the same problem as you had. Not that writing a very little program that convert the file’s content from base64 encode to normal text is a particularly difficult task, but if things are already done it’s better! So if you surf here you can copy and past the code, compile it, run it, and have the file correctly converted.

STEP 2: WordPress – configure the permalink structure

This step is strongly recommended if you don’t want that the structure of all URL’s doesn’t change compared to the URL’s structure of the SubText blog.so as not to lose the Google indexing of your blog. Then the URL’s structure of the WordPress based blog must remain the same.

To accomplish this, you need to change the permalink structure in WordPress. After you login as administrator, go to “Settings > Permalink” and check “Custom structure”, then typing this URL structure:

/archive/%year%/%monthnum%/%day%/%postname%.aspx

This is exactly the URL’s structure used by SubText. Note the “ASPX” suffix, even if WordPress isn’t an ASP .NET application.

This picture may helps:

Schermata 2014-09-18 alle 22.59.53.png

STEP 3: WordPress – import your blog using the BlogML WordPress plugin importer.

This plugin is built in into WordPress installation, so it’s nothing to download and install. Just click to “Tools > Import” and then choose BlogMl importer, upload the file XML generated at step 1 and click the button “Upload file and import”

Schermata 2014-09-18 alle 23.10.10.png

Just a few seconds and your blog is imported in WordPress and is up and running!

STEP 4: WordPress – troubleshooting.

1) The BlogML Importer plugin doesn’t import blog categories correctly. They have been imported with the ID they had in SqlServer SubText repository in place of description. You must correct them manually.

2) The RSS Feed wasn’t generated correctly; the procedure ended with a XML parsing error, as shown in this picture:

Schermata 2014-09-18 alle 23.34.06.png

and it seems to be related to some whitespace or blank lines into the various *.php files of the WordPress installation, or with custom permalinks that break RSS feed, like they said here

This problem was quite difficult to resolve and it took several time and Google searching.

Initially I founded this WordPress Fix plugin, I tried it but it fixed anything, on the contrary it said that my RSS feed was working well and that all was fine!

After an hour of Google searching, I found the solution in this Peter Krzyzek’s post, and I can never be grateful enough to the author for having solved this problem.

These are the steps you have to do:

– Download this: http://wejn.org/stuff/wejnswpwhitespacefix.php (this is a php file)

– Copy this file in the ROOT folder of your WordPress installation

– Edit the index.php file in the ROOT folder and add the followings:

include(“wejnswpwhitespacefix.php”);

after the first line, e.g. just after the <?php line

– Reload the page and….BOOM….IT WORKED!!!!!!

I don’t know anything about php, I’m a .Net developer, and without that post I will never solve this problem.

Thank you Peter!

NHibernate QueryOver is not a Linq provider (that is how to do join with QueryOver API)

Starting from NHibernate 3.0 a new API was build as a wrapper around the ICriteria object.

Obviously I’m talking about the powerful API called QueryOver. With this API you can build a wide range of query object, from the simplest to the more complicated one. But you need to remember that this API is not a Linq provider, and then you cannot apply those constructs typically applied in a Linq query. I explain with an example what I really mean.

Introduction: you have a data model with 2 table, Category and Customer, with a one-to-many relationship between them.

With Entity Framework and Linq To Entities it’s pretty simple to query data that belong to both entities, thanks to navigation properties and Linq provider, i.e. all customers that belong to a category with a specified Id, as shown in this example:


var customerList = customers.Where(c => c.CategoryId == 1);

If you try to execute the same query with the same where conditions applied to a QueryOverObject, like this example:


QueryOver<Customer>; qu = QueryOver.Of<Customer>()
      .Where(c => c.CategoryId == 1);

This code throws a NHibernateException saying that “could not resolve property: Category.Id of : MyNamespace.Customer”, suggesting to verify the mapping as property “Category.Id” could not be found”.

Obviously such a property doesn’t exist at all, it’s only the QueryOver API that concatenates the Navigation property and and its field named Id (in this example).

This means that: you cannot make a query with QueryOver API that refers to fields belonging to a navigation property in where clause….without explicitly defying a join between the object itself and its navigation property. An example will help to understand better.

Category cat = null;
QueryOver<Customer> query = QueryOver.Of<Customer>()
 .JoinAlias(x => x.Category, () =>; cat)
 .Where(x => cat.Id == 1);

I have defined a join with the JoinAlias method, which uses an alias (the Category object declared two rows before) to project the object under the navigation property. After that you can use this alias inside the others method (such as “Where” in this example) to refer to the navigation property field (cat.Id).

As you can see, the way you write the lambda expression inside a Linq provider’s where clause is quite different than the “”Where” condition of a QueryObject object.

Not even the logical operator “And” can be used in the same way. To apply this logical operator to the “where” filter you have to use the “And” method, as shown here:

Category cat = null;
QueryOver<Customer> query = QueryOver.Of<Customer>()
   .JoinAlias(x => x.Category, () => cat)
   .Where(x => cat.Id == 1)
   .And(x => cat.IsEnabled);

Pluralisation services in .Net Framework

Starting from .Net Framework version 4.0 developers have available a new service for converting a single word from singular to plural form, or from plural to singular form.

I’m talking about the class PluralizationService contained in namespace System.Data.Entity.Design.PluralizationServices in assembly System.Data.Entity.Design.

it’s very simple to use it:

string plural = System.Data.Entity.Design.PluralizationServices
        .PluralizationService.CreateService(new System.Globalization.CultureInfo("en-US"))
        .Pluralize(singular);
// returns "dresses";

or

string singular = "woman";
string plural = System.Data.Entity.Design.PluralizationServices
         .PluralizationService.CreateService(new System.Globalization.CultureInfo("en-US"))
         .Pluralize(singular);
// returns "women";

I don’t know how reliable a translation service inside a framework can be, but it’s use can be very useful.

Be careful because the only supported culture is “English” (so far). Then if you call the service with another culture, i.e. Italian (it-IT), you end up with a NotImplementedException, as shown here:

Technorati Tags: ,

Dynamic build of generics types at runtime

How to create dynamically a type in .Net when it’s only known a string representation of that type, I think it’s an operation known to almost all .Net programmers, but what happened with types with type parameters (or generics) ?

In .Net is possible to create dynamically both generics with a known type, i.e. List<>, and generics with type in turn dynamically built.

Here’s an example:

a) Dynamic generated both type parameter and type

Type collectionType = Type.GetType("System.Collections.Generic.List`1, mscorlib");
if (collectionType == "null")
    throw new InvalidOperationException("Invalid type");
Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = collectionType.MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;

b) Dynamic generated type parameter with a known type (System.Collection.Generic.List in this case):

Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = typeof(List<>).MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;
Technorati Tags: ,,

[ASP .NET] How to access Request data when HttpContext.Current.Request is unavailable

What happened if you need to access the HttpRequest object whitin the event Application_Start of an ASP .NET Web Application ?

Response: you end up with an exception.

Someone might observe that such event is not a valid place for a task like that, but sometimes things are simply different from those that appear at first sight.

So, if you want to get for example the virtual path or the physical path of a web application before the HttpRequest object is constructed  this is a valid solution:

HttpRuntime.AppDomainAppVirtualPath;
HttpRuntime.AppDomainAppPath;

Simply use HttpRuntime instead of HttpContext.Current.Request!

Technorati Tags: ,

How to enable Visual Studio Intellisense for NHibernate configuration files

If you are an NHibernate’s user and you want to benefit of the Intellisense support during the editing of its configuration files in Visual Studio 2010 environment, just copy these 2 files: nhibernate-configuration.xsd and nhibernate-mapping.xsd,  from the NHibernate zip into the following folder:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas

where C:\Program Files (x86)\Microsoft Visual Studio 10.0 is your Visual Studio 2010 installation folder.

Technorati Tags: ,

Javascript code block formatting

For those who develop applications using C# or Javascript, but I think Java too, (I’m not a Java developer and then I don’t know if what I’m going to say is true for them as well) ,  there are two kind of writing styles for indentation and code’s blocks formatting .

These styles, known as K&R (Kernighan & Ritchie) style and Allman style, concern the way the opening curly brace is opened, when defining a block of code.

The former places the brace in the same line as the preceding line of code, as you can see in this example:

return {
   name: "Joe"
};

the latter places the curly brace in its own line, as shown here:

return
      {
        name: "Joe"
      };

So, the question is:

Can I use both of these styles or not when writing code ?

The answer is: yes, except for Javascript code.

In Javascript you must always use the K&R style if you want to avoid some subtle bugs that may be very difficult to identify.

For example, if you used the code in Allman style showed below

the return value would be “undefined” and not an object as expected, because the browser insert a semicolon after the word “return”.

If the code below had written in K&R (Kernighan & Ritchie) style:

as shown in first example, the return value would have been an object as expected.

Tag di Technorati: ,

Raven2Go posts editor portable application

Raven2Go is a valid alternative to blog posts editor much more famous like Word or Windows Live Writer, and it can even be installed as a portable application in a USB pen drive, feature very useful for people who often move from one pc to another.

Main features are:

  • Tabbed true WYSIWYG Editing
  • Manage multiple media storage services
  • Improved content management
  • Manage multiple blogs offline
  • WordPress 2.2+ Page & Tag support

Download

Powered by Zoundry Raven

HeidiSQL – Free portable client for Sql server and MySql

Free portable client for Sql server and MySql.

This is the software I always needed!

Features:

Entity Framework for Oracle is dependent by an environment variable

Those who using Entity Framework Provider for Oracle have certainly already run into this issue, i.e., the proper functioning of this provider depends on an environment variable! It’s a bit strange, but it’s the truth.

If you forget (or if you simply don’t know) to setup an environment variable named “TNS_ADMIN” which contains the full path used by Oracle software to search for the “tnsnames” file, which in turn is used for reading the necessary parameters to establish a connection to the database server, attempting to open a connection will fail.

After setup the environment variable you have to reboot Visual Studio, if already opened, in order to apply the change.

After applying the environment variable if you try to create a new Oracle connection using the Visual Studio wizard, if all is working fine you will see the list of the tnsnames file entries in the data source dropdown list instead of a blank list.

Also, this environment variable needs only to Entity Framework for Oracle, as other software, like Toad for example, doesn’t need it to search for tnsnames files.

You can obtain the same result by adding a registry key, but it’s certainly easier to create an environment variable than modifying the registry.

Hope this helps.

Coding Horror #2

Some time ago I started writing a series of blog post (only one for precision) about some “absurd” code I meet in my daily work.

I called this series “Coding horror”, and, so far I have written only one post, this one.

This is the second one.

About the code below, I thing that every comment is unnecessary because it speaks for itself.

if (myVar == null)
    return myVar = null;

As an additional reason, the Resharper tooltip about the row number 2 is:

“Destination has the same value before assignment”.

It could not be much clearer than that.

Technorati Tags: