ASP.NET Core class

Who is addressed to

This tutorial is aimed to C# programmers with at least 6 months experience. Also , they should  have at least 6 months experience with HTML / CSS / Javascript .. This will help them to understand ASP.NET Core foundations and how to build applications with the .NET Core framework

The class will be taken by Andrei Ignat, former C# MVP for 6 years, https://forums.asp.net moderator and OpenSource contributor( you can find his AspNetCoreImageTagHelper mentioned on https://github.com/aspnet/Mvc ). More details at his blog at http://msprogrammer.serviciipeweb.ro .

What it contains

Day 1. ASP.NET Core Basics

MVC – model , view , controller.

  • Views, Areas, Layout.
  • ViewBag, Controller, Action
  • Model
  • Model binding
  • generate from database ( EF)

Transmitting data from

  • action to action
  • view to action
  • action to view
  • view to view


Day 2. Intermediate WebAPI

WebApi

  • Creation,
  • Formatters ( XML, Json, others)
  • Filters ( logging time, validation)
  • Caching

Practical WebAPI

  • Ajax with WebAPI
  • Knockout with WebAPi


Day 3 Advanced .NET Core

Dependency injection

  • logging
  • action

Middleware – slug routing

Angular with .NET Core

Testing

What to expect

After completing this course, you will be able to:

a.  Understand how to create a new application with ASP.NET Core

b. Know how to use the intermediat features of ASP.NET Core

c. Understand how to make an modern application with Angular on frontend and .NET Core on backend

Putting data into existing PDF

I have had to introduce data for NGO into an existing PDF. Why PDF ? Because yes, it is easy to print. but from a templating point of view it is a nightmare.  by templating I understand putting data at specific places , like

First Name :

Last Name :

And filling in the blanks.

The solution: complicated.  The  pdf can have Form fields to be filled . I discovered

 https://www.pdfescape.com/windows/

that can be used to put form fields into existing documents and save the pdf.

And I figured that this is all. Nope. Look here

109 0 obj
<</Subtype/Widget/Rect[119.52 347.25 565.92 358.77]/AP<</N 110 0 R>>/DA(/Helv 8.64 Tf 0 g)/F 4/FT/Tx/P 1 0 R/T(untitled22)/Q 0/V(*NumeONG*)>>

endobj


110 0 obj

<</Type/XObject/Subtype/Form/BBox[0 0 446.39999 11.51999]/Resources<</Font<</Helv 77 0 R>>>>/Filter/FlateDecode/Length 90>>stream
xœÓ©Ppòuær
á2PIå\†@ª
ÈNñ‹¸ô=RsÊ,ôÌLBÒ¸€ÐPÁHÁHÏÌL!$—+ZC˯47ÕßÏ]K36Ä‹Ë5„Ëh&endstream

endobj

The PDF format is a primitve form of XML. The 109 0 obj  finishes with  endobj . I figured that I will replace
*NumeONG*

with the name and all will be ok. Nope . The critical point is the stream at the next obj

110 0 obj
<</Type/XObject/Subtype/Form/BBox[0 0 446.39999 11.51999]/Resources<</Font<</Helv 77 0 R>>>>/Filter/FlateDecode/Length 90>>stream
xœÓ©Ppòuær
á2PIå\†@ª
ÈNñ‹¸ô=RsÊ,ôÌLBÒ¸€ÐPÁHÁHÏÌL!$—+ZC˯47ÕßÏ]K36Ä‹Ë5„Ëh&endstream
endobj

Not only is is encoded

Filter/FlateDecode

but also it says the length of the stream,

Filter/FlateDecode/Length 90

That is a problem, because the replacement for the name will be dynamic.

Solution?

The qpdf solftware http://qpdf.sourceforge.net that allows to transform those streams into something readable

qpdf –qdf  –object-streams=disable   m.pdf a.pdf

GitHub as a central Hub

I do not know how, but GitHub is now a hub for all things.

I , personnally, used GitHub as a

– source control ( see https://github.com/ignatandrei/Exporter )

– documentation ( see https://github.com/ignatandrei/Exporter/wiki )

– Angular application deployment (https://ignatandrei.github.io/Decl230   – done with  gh-pages –  see build.bat from https://github.com/ignatandrei/Decl230 )

– read-only database ( Sqlite download from github in the project  https://github.com/ignatandrei/IsThisTaxiLegal )

I have seen many other uses

–  like Docker files generator ( for example, for docker phone gap  see https://github.com/webratio/docker )

– blog

and may others ( https://readwrite.com/2013/11/08/seven-ways-to-use-github-that-arent-coding/)

I need just a server hosting service affordable….

Import large Excel file into SqlServer

I have to import the list of NGO from Romania to SqlServer.  Before seeing my solution , please do it yourself: the file could be found at http://www.just.ro/registrul-national-ong/ and the name is Asociatii

I have tried with SSMS – no luck ( text will be truncated, even when I put nvarchar(max))

The I tried with flat file from CSV  – same

Finally, I have solved with a little bit of VBA : first I have tried to write the insert into file and execute with sqlcmd. The file was too large, so sqlcmd does not report any errors( and not insert anything)

So the solution was to generate a batch file that have this

sqlcmd  -S . -E -d InfoRo -Q “INSERT INTO [dbo].[Asociatii$]  ([Denumire]  ,[Numar inreg Reg National],[pozitie inchisa (da/nu)],[Starea actuala],[Judet],[Localitate],[Adresa],[Asociati/Fondatori],[Scop],[Consiliu director],[Apartenenta federatie],[HG utilitate publica],[Data HG utilitate publica],[F14])values( ////)”

generated by this VBA script

Option Explicit

Sub x()
Dim startInsert As String

startInsert = "sqlcmd  -S . -E -d InfoRo -Q ""INSERT INTO [dbo].[Asociatii$]"
         startInsert = startInsert & "  ([Denumire]"
         startInsert = startInsert & "  ,[Numar inreg Reg National]"
           startInsert = startInsert & ",[pozitie inchisa (da/nu)]"
           startInsert = startInsert & ",[Starea actuala]"
           startInsert = startInsert & ",[Judet]"
           startInsert = startInsert & ",[Localitate]"
           startInsert = startInsert & ",[Adresa]"
           startInsert = startInsert & ",[Asociati/Fondatori]"
           startInsert = startInsert & ",[Scop]"
           startInsert = startInsert & ",[Consiliu director]"
           startInsert = startInsert & ",[Apartenenta federatie]"
           startInsert = startInsert & ",[HG utilitate publica]"
           startInsert = startInsert & ",[Data HG utilitate publica]"
           startInsert = startInsert & ",[F14])values("
           
           
           Dim i As Long, j As Integer, text As String
           Dim insert As String
           For i = 2 To 86813
            insert = insert & startInsert
            For j = Asc("A") To Asc("M")
                text = Sheet1.Range(Chr(j) & i).text
                text = Replace(text, vbCr, " ")
                text = Replace(text, vbLf, " ")
                text = Trim(text)
                 text = Replace(text, "'", "''")
                text = Replace(text, "  ", " ")
                
                insert = insert & "'" & text & "',"
            Next j
            insert = insert & "null)" & """"
            insert = insert & vbCrLf
            If (i Mod 150 = 0) Then
                Open "C:\Users\Surface1\Desktop\2Percent\a.bat" For Append As #1
                Print #1, insert
                Close #1
                insert = ""
            End If
           Next i
           If (Len(insert) > 0) Then
                Open "C:\Users\Surface1\Desktop\2Percent\a.bat" For Append As #1
                Print #1, insert
                Close #1
                insert = ""
            End If
          
           
          
           
     
End Sub


Obtain data from ANAF(local IRS)

In ROmania ANAF is providing a WebAPI that allows access to some of the information that any enterprise should provide. The API is described at https://webservicesp.anaf.ro/PlatitorTvaRest/api/v3/ ,

I have made a C# console and a node,js script.

The differences:

1.it is easiear in node to make an http request.

2. For C# – I think in components. For node – I think in application.

Without further ado, here is the code

using RestSharp;
using System;

namespace InfoAnafWS
{
    class Program
    {
        static void Main(string[] args)
        {
            if(args.Length == 0)
            {
                Console.WriteLine("lipseste CUI ");
                return;
            }
            var client = new RestClient("https://webservicesp.anaf.ro");
            var request = new RestRequest("PlatitorTvaRest/api/v3/ws/tva", Method.POST);
            request.RequestFormat = DataFormat.Json;
            string date = DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd");
            string req = "";
            foreach (var item in args)
            {
                req += string.Format(@"{{'cui': {1}, 'data':'{0}'}}", date, item);
            }
            req = req.Replace("'", "\"");
            req = "[" + req + "]";

            request.AddParameter("application/json", req, ParameterType.RequestBody);
            var data = client.Execute(request);
            Console.WriteLine(data.Content);
        }
    }
}


const start = async () => {
	
let request = require('request');

const d = require('delay');
await d(1000);
var fs = require('fs');
var array = fs.readFileSync('CUI.txt').toString().split("\r\n");
var start=0;

while(start<array.length){
	var nr = Math.floor(Math.random() * Math.floor(495))+1;
	var jsonData=[];
	console.log('start at ' + start+  ' for nr ' + nr);
	var i=0;
	while(i<nr && i+start<array.length){
		jsonData.push({"cui": array[i+start], "data":"2018-03-26"});
		i++;		
	}
	
	var finish=false;
	console.log('array :'+ jsonData[0].cui + '-'  + jsonData[nr-1].cui);
	request.post(
    'https://webservicesp.anaf.ro/PlatitorTvaRest/api/v3/ws/tva',
    { json: jsonData },
    function (error, response, body) {
		finish=true;
        if (!error && response.statusCode == 200) {
            console.log(body);
			fs.writeFile(`text${start}_${nr}.json`, JSON.stringify( body ), function (err) {
            if (err) {
                return console.log(err);
            }

            console.log("The file was saved!" + `text${start}_${nr}.json`);
        });

        }
    });
	start = start+nr;
	while(!finish){
		console.log('waiting');
		await d(13000);
	}
	

}
console.log('finish')
return;

}
start();