Archivi categoria: .net

Programmare da zero | Imparare a programmare per principianti

Per me sono stati i videogiochi: è sempre colpa dei videogiochi. Non volevo semplicemente giocarli, volevo costruirli. E così ho capito che dovevo studiare come funzionano i computer i programmi. Perché i videogiochi sono tra i programmi più complessi, costosi e difficili da realizzare. Poi la vita è sempre ricca di sorprese e ora della fine non programmo videogiochi ma sono comunque diventato un programmatore 😊

Per te potrebbe essere l’automazione, la robotica, la domotica, i chatbot… Comunque sei qui a chiederti: come programmare da zero? Come si inizia a programmare?

Ecco qualche linea guida su come approcciarsi al vastissimo mondo della programmazione. Questo mondo è così ampio che è impossibile trattare tutto in un solo articolo.

Cos’è un programma?

Un programma non è altro che un insieme di istruzioni codificate in modo comprensibile per un pezzo di ferro (cioè Silicio, di cui sono fatti i circuiti dei PC) che prendono degli input e danno un output. Pensa per esempio a quella parte del sistema operativo (windows, mac o linux che sia) che trasforma il movimento del tuo mouse in una freccia che si muove sullo schermo.

Quale linguaggio di programmazione scegliere?


Per scrivere un programma serve un linguaggio di programmazione. Ce ne sono tantissimi, divisi in categorie, e ognuno è progettato per uno scopo preciso. Non c’è quindi in generale un linguaggio migliore, dipende sempre da cosa dobbiamo fare. Se dobbiamo fare pezzi di un sistema operativo molto probabilmente lavoreremo in C o C++. Programmi per gli smartphone con Java, C#, Swift, Objective-C. SQL se dobbiamo interagire con le basi di dati relazionali. Python è molto usato per le elaborazioni numeriche e data science.

Quindi in base al tuo progetto sceglierai lo strumento (linguaggio di programmazione) che ti metterà a disposizione le funzionalità più adeguate.

Per imparare a programmare, per conoscere le basi, i linguaggi più idonei sono quelli che mettono a disposizione la miglior documentazione e i cui strumenti siano facili da reperire e gratuiti.

Come imparo a programmare?


Per imparare a programmare ci sono moltissime opzioni on-line: i produttori di strumenti di sviluppo stessi, nei loro siti, mettono a disposizione tutorial e materiale per iniziare. Puoi quindi procedere da autodidatta, scenario che nel mondo della programmazione è molto comune. Ci sono corsi di formazione in campus sia fisici che remoti. Si spazia anche passando per corsi serali.

Non è necessario essere dei mostri in matematica (come spesso si pensa): la matematica è utile ma diventa davvero necessaria quando si devono scrivere programmi come motori di calcolo fisico o programmi a supporto di ricerca scientifica.

La maggior parte dei programmi, tuttavia, consiste nel prendere dati da uno schermo/tastiera/mouse/tocco/penna, salvarli da qualche parte e recuperarli in un secondo momento.

Costruiamo il primo programma insieme

Ma ora basta con le chiacchiere, ti mostro come creare il tuo primo programma dallo zero totale, in dieci minuti (più o meno, a seconda della velocità del tuo computer).

WCF config to avoid content-length error

Low quality blog post. This is a personal note/reminder.

I quickly post here a reference WCF config file to avoid the content-lenght error when uploading some content.

The key config section here was <system.webServer></system.webServer>

<?xml version="1.0" encoding="utf-8"?>
 <!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1" maxRequestLength="50000"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <bindings>
      <basicHttpBinding>
        <binding name="SchedulerWSServiceBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
                 allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="2000000" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
            <message clientCredentialType="UserName" algorithmSuite="Default"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="W.Scheduler">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="SchedulerWSServiceBinding" contract="Web.Services.IScheduler"/>
      </service>
    </services>
    <client>
      <endpoint address="http://localhost/W/Scheduler.svc" binding="basicHttpBinding" bindingConfiguration="SchedulerWSServiceBinding" contract="Web.Services.IScheduler" name="WSClientScheduler"/>
    </client>
  </system.serviceModel>
  <system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="50000000" />    <!-- Allow files of upto 50,000,000 bytes (about 50Mb) to be uploaded -->
    </requestFiltering>
  </security>
</system.webServer>
</configuration>

How to fix 8000000A error when building VDPROJ

The Microsoft Visual Studio Setup Project is an old technology to create installer developed by Microsoft. It is out of support from nearly a decade and not present in Visual Studio anymore but when I visit customer sites I find legacy technologies and I need to deal with it on the short-term.

A couple of days ago I was working on an automated CI build on Azure DevOps and we hit an issue when trying to compile an old VDPROJ (migration to Wix in progress, btw ☺). We encountered an HRESULT 8000000A error.

Continua a leggere How to fix 8000000A error when building VDPROJ

Kubernetes baby steps: deploying our first .Net App to a cluster

This blog post is the first of a new topic about Kubernetes.

Kubernetes is an open-source container-orchestration system for automating application deployment, scaling, and management. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation. 

Wikipedia

This post introduces some basic concepts of Kubernetes with a working example based on .Net and Visual Studio.
We’ll develop a simple Web API service, package it as a Docker container, upload it to Docker Hub, and we’ll run it onto Kubernetes.

Our API is built from a project called IC6.RedSvc (Red Service) that when invoked returns a name of a red object. It’s a pretty simple business logic because the main purpose of this post is about learning Kubernetes. The source code for this working example is hosted on my GitHub.

Let’s get started!

Step-by-step

Create a new project ASP.NET Core Web Application.

Solution name: IC6.ColorSvcs, project name IC6.RedSvc.

Rename the DefaultController.cs file into RandomObjectController.cs and replace the code of the class with the following code. This is the controller that implements our simple business logic.

namespace IC6.RedSvc.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RandomObjectController : ControllerBase
    {
        string[] redObjects = { "Ferrari", "Coca Cola", "Pendolino", "Cherry", "Strawberry" };

        // GET api/values
        [HttpGet]
        public ActionResult<string> Get()
        {
            return redObjects[DateTime.Now.Ticks % redObjects.Length];
        }
    }
}

Add Dockerfile

Right click on the Solution Explorer onto the Project, Add, Docker Support…

And we chose Linux.
This step creates the Dockerfile to build our Docker image.

Before we start the application edit launchSettings.json to change the default page. This step makes it easier to test in our browser the API when we launch the project with F5.

Docker build

Now we build our Docker image.

docker build -f "c:devic6.colorsvcsic6.redsvcdockerfile" -t phenixita/ic6redsvc:latest --name=IC6.RedSvc" "c:devic6.colorsvcs"

We have built the Docker image of our app!

Before we can move on with Kubernetes we need to upload this image to Docker Hub because Kubernetes will try to download from it the images for the containers that it will create. In order to do that we need an account (free for open projects) of Docker Hub.

Docker login

The first thing we need to do is a docker login from the command line to handle the authentication to our repository.

Push

Now we can push our image with:

docker push phenixita/ic6redsvc:latest

And it’s done!

Kubernetes time!

We can deploy our app onto Kubernetes!
I recommend to use a managed Kubernetes instance from your provider of choice (AWS, Azure, you name it) or run in your machine something like Minikube. Docker for Windows provides support for a single Kubernetes cluster with low hardware requirements.

This is a Kubernetes Cluster. It is composed by a master node and working nodes. The master node is the coordinator of all the activities that happens inside a cluster. The working nodes are the computer power (most of the time they are virtual machines) that will do the job of running our code.

Check that kubectl is configured to talk to your cluster, by running the kubectl version command.

To view the nodes in the cluster, run the kubectl get nodes command:

Here we see the available nodes (1 in our case). Kubernetes will choose where to deploy our application based on Node available resources. Let’s run our first app on Kubernetes with the kubectl run command.

Run!

The run command creates a new deployment. We need to provide the deployment name and app image location (include the full repository url for images hosted outside Docker hub). We want to run the app on a specific port so we add the –port parameter:

kubectl run ic6redsvc --image phenixita/ic6redsvc:latest --port=80

Testing

We need to get the pod name with:

kubectl get pods
Our app is running in a private network and we need to activate a proxy in another terminal to be able to test it. This is not the standard approach for production environments, we'll see in future blog post how to do it properly. Now we try to keep things as simple as possible.

Call

This is the final step where we call our API. We compose the command like the following example.

curl http://localhost:8001/api/v1/namespaces/default/pods/<podId>/proxy/api/RandomObject

If we did everything correctly we’ll se a repsonse message with one of the objects returned as implemented in the C# code.

TL;DR

With this blog post we learned how to do a very simple deployment of a Docker Image onto Kubernetes. Now we have the foundations to create more meaningful scenarios in future blog posts.

Visual Studio Debug – Tips And Tricks – Part 1

We use Visual Studio many hours a day but can we say that we know all the tips and tricks?

Here I share a brief collection of 3 debugging tips that I collected.

Step into specific

This feature is helpful when we have a situation like below. We set a breakpoint in line 9 and when the program counter hits that point. Now we would like to jump directly into Spagetti() without stepping into Parmiggiano(). To do so we right-click the program-counter line, Step Into Specific and then Spaghetti().

Run To Cursor (CTRL + F10)

If we have a situation like the following picture we may want to run to line 20 without stepping-over (F10) many times. With Run To Cursor we can run to the statement where our cursors is located and stop there. We can do this with right click, Run To Cursor or with the CTRL+F10 keyboard shortcut.

Peek definition

If we want to look quickly without changing context to a definition of a method or class we can use the ALT+F12 keyboard shortcut. It opens a frame inside our current code to show details of what we selected.

TL; DR

In future posts I’ll share other tricks! Stay tuned!

CQRS by Example – Simple ASP.Net CORE implementation

In this blog post we’re going to explore a simple ASP.Net Core CQRS WebApi project. The code for this tutorial exposes a demonstrative API to manage a blog.

Continua a leggere CQRS by Example – Simple ASP.Net CORE implementation

Import from JIRA to VSTS in 5 steps

In previous posts I documented some features of VSTS and a few scenarios of Application Lifecycle Management.

If you like VSTS it’s likely that you want to move your existing project from your current platform to VSTS. I’m currently planning a migration from JIRA to VSTS at work and here I am to share my findings.

This blog post has been inspired by the work of the ALM DevOps Rangers.

We’re going to build a simple tool to migrate and map Jira issues into VSTS items.

The source code is available on GitHub. Continua a leggere Import from JIRA to VSTS in 5 steps

VSTS for beginners: release your web-app to Azure

In the previous post of this series dedicated to VSTS we talked about continuous integration. Now we’ll talk about publishing our Web-App hosted on Azure with the release management tools provided by VSTS. With this kind of tools we can deploy the latest version of our web-app to Azure in complete automation removing manual procedures and human errors. The setup of Azure will be covered in another blog post.

 

Continua a leggere VSTS for beginners: release your web-app to Azure

VSTS for beginners: improve quality with continuous integration in 3 easy steps

In this blog post we’re going to configure a build process in VSTS to enable continuous integration for our ASP.Net Core example web-app.
Continuous integration is a powerful technique to prevent merge-hell and improve quality on the “left” stages of our software production process. In the fast-paced world of development we want to merge into the main line of development the new developed features as soon as possibile to avoid open branches that will cause painful merges. If we keep our unit of work small and focused we’ll have great benefits.

Continua a leggere VSTS for beginners: improve quality with continuous integration in 3 easy steps

How to upload images to an ASP NET Core REST service with Xamarin.Forms

With this blog post we continue the exploration of Xamarin.Forms. We’ll se how to upload a picture to a RESTful service developed with ASP.NET Core.

uwpScreenshot
UWP flavor of the upload with file picker

Continua a leggere How to upload images to an ASP NET Core REST service with Xamarin.Forms