Category: projects

NetCoreUsefullEndpoints–part 7–restart application

In order to do the shutdown, I have added the following extension

public static CancellationTokenSource cts=new ();

public static void MapShutdown(this IEndpointRouteBuilder route, string? corsPolicy = null, string[]? authorization = null)
        {
            ArgumentNullException.ThrowIfNull(route);
            var rh = route.MapPost(“api/usefull/shutdown/”,
                (HttpContext httpContext) =>
                {
                    var h= cts.Token.GetHashCode();
                    cts?.Cancel();                   
                    return h;
                   
                });

           rh.AddDefault(corsPolicy, authorization);

        }

This code defines a static field called “cts” in the “UsefullExtensions” class. “cts” is an instance of the “CancellationTokenSource” class, which is used to create a CancellationToken that can be used to stop the application gracefully.

The “MapShutdown” method is an extension method for IEndpointRouteBuilder that creates a new endpoint for a POST request to the “api/usefull/shutdown/” URL. When the request is received, the method cancels the “cts” CancellationTokenSource if it is not null, and returns the hash code of the CancellationToken. The method also sets the “corsPolicy” and “authorization” parameters for the endpoint.

You can call with

app.MapUsefullAll();

or with

app.MapShutdown

Anyway , the runAsync should be modified with

await app.RunAsync(UsefullExtensions.UsefullExtensions.cts.Token);

The “RunAsync” method of the “app” object is used to start the application and listen for incoming requests. The method takes a CancellationToken as an argument, which allows the application to be stopped gracefully by cancelling the token. In this case, the token is provided by the “cts” field of the “UsefullExtensions” class. The code uses the “await” keyword to wait for the task returned by “RunAsync” to complete before continuing.

DIForFunctions – Improving constructor–part 5

I have received a suggestion : what if we just put into constructor what we need , and everything else ( such as ILogger ) are into fields ?

The Roslyn Source Code Generator will generate a constructor that calls the this constructor  and will assign fields needed.

Let’s give an example : We wrote

public partial class TestDIFunctionAdvWithConstructor2Args
    {
        [RSCG_FunctionsWithDI_Base.FromServices]
        private TestDI1 NewTestDI1;

       public TestDI2 NewTestDI2 { get; set; }

       public readonly TestDI3 myTestDI3;

       private TestDIFunctionAdvWithConstructor2Args(TestDI3 test, TestDI2 a)
        {
            myTestDI3 = test;
            NewTestDI2 = a;
        }

   }

and the generator will generate a new constructor with the required  field

public partial class TestDIFunctionAdvWithConstructor2Args
{
public TestDIFunctionAdvWithConstructor2Args  
(TestDI3 test, TestDI2 a, TestDI1 _NewTestDI1) : this (test,a)
{
this.NewTestDI1 = _NewTestDI1;
}//end constructor

}//class

The code is non trivial  – to find if a constructor exists, take his fields, generate new constructor with all fields.

But , as anything in IT , it is doable .

Record visitors- work on issues–part 7

Now it is time to solve some issues  There were 12 issues written by me – you can see here:

https://github.com/ignatandrei/RecordVisitors/issues?q=is%3Aissue+is%3Aclosed

Between the most important:

  1. Improve readme.md with more links and explanations for potential programmer and contributors
  2. Write version in static constructor – to know about the version, if some issue occurs
  3. Added custom link  lastvisitors/minutes/{time:int} to see the latest visitors in a time frame
  4. Add read the docs site https://record-visitors.readthedocs.io/en/latest/
  5. Modification on the interfaces – replacing FUNC property with a real Func

There seems little – but it takes a while.

The links for the project are now

SideCARCLI–Finish process after some time

Summary links SideCarCLI

NoName + Link 
1Description
2Specifications
3Refactor specifications and code
4Create Release
5Finish interceptors
6Send part of command to interceptors
7Line Interceptors
8Finish process after some time
9Documetation Diagram
10Technical Summary
11Create dotnet tool
( Description : SideCar for CLI applications. Interceptors for Line, Finish, Timer . See Code )

One of the feature is to let the original process execute just a limited amount of time. For this, I have defined an option

var maxSeconds = app.Option(“-mS|–maxSeconds”, “max seconds for the StartApp to run”, CommandOptionType.SingleOrNoValue);

and the code for waiting is

Process p = new Process()
{
StartInfo = pi
};

//code

var res=p.WaitForExit(this.MaxSeconds);

//code

if (res)
{
exitCode = p.ExitCode;
RunFinishInterceptors(exitCode);
}
else
{
Console.WriteLine($”timeout {MaxSeconds} elapsed”);
exitCode = int.MinValue;
}

 

where the default value for this.MaxSeconds is –1 – wait undefinetely

SideCarCLI – Line interceptors

Summary links SideCarCLI

NoName + Link 
1Description
2Specifications
3Refactor specifications and code
4Create Release
5Finish interceptors
6Send part of command to interceptors
7Line Interceptors
8Finish process after some time
9Documetation Diagram
10Technical Summary
11Create dotnet tool
( Description : SideCar for CLI applications. Interceptors for Line, Finish, Timer . See Code )

For the SideCarCLI I have the concept of Line Interceptors. That means for each line from the original program another program will be start .

The json looks like this

“LineInterceptors”: [
{
“Name”: “WindowsStandardWindowsOutputInterceptor”,
“Arguments”: “/c echo \”{site} {line}\””,
“FullPath”: “cmd.exe”,
“FolderToExecute”: null,
“InterceptOutput”: true
},
{
“Name”: “NextInterceptor”,
“Arguments”: “/c echo {line}”,
“FullPath”: “cmd.exe”,
“FolderToExecute”: null,
“InterceptOutput”: true
}
]

and you can activate by command line

-aLi WindowsStandardWindowsOutputInterceptor

Pretty simple , right ? For the code , means intercepting each line

p.OutputDataReceived += P_OutputDataReceived;
p.ErrorDataReceived += P_ErrorDataReceived;

and then run the process

foreach(var item in runningInterceptors.LineInterceptors)
{
try
{

var local = item;
var dataToBeParsed=new Dictionary<string, string>();

if(this.argsRegex.Count>0)
{
foreach (var reg in argsRegex)
{
dataToBeParsed.Add(“{“+reg.Key+”}”, reg.Value);
}
}
dataToBeParsed[“{line}”]= e.Data;
allProcesses.TryAdd(local.Name, local.RunLineInterceptor(local.Name,dataToBeParsed));

}
catch (Exception ex)
{
Console.WriteLine($”LineInterceptor:{item?.Name} error:!!!” + ex.Message);
}
}

Every time it is interesting how a simple specification means multiple lines of code….

SideCarCLI | Command Line – description –part 1

Summary links SideCarCLI

NoName + Link 
1Description
2Specifications
3Refactor specifications and code
4Create Release
5Finish interceptors
6Send part of command to interceptors
7Line Interceptors
8Finish process after some time
9Documetation Diagram
10Technical Summary
11Create dotnet tool
( Description : SideCar for CLI applications. Interceptors for Line, Finish, Timer . See Code )

There are those days a great deal of command line applications that performs a variety of things. The problem is that you cannot control them . The command line performs their duty well – but , from time to time, you need something else integrated with this.

The pattern for this is https://docs.microsoft.com/en-us/azure/architecture/patterns/sidecar – it is applied to microservices , but why not applied to command lines ?

So – let’s start this project  with specifications.

Let’s suppose that I want to run an command line application – let name it StartApp. But I want also:

  1. Intercept every line of the StartApp that is outputting to the console and run something with that with the line ( send to HTTP endpoint, log somewhere, and so on).
  2. Intercept the finish of the StartApp and run something with the output ( either all lines, either with the result of the application)
  3. Timers:
    • Do not let the StartApp to run more than an maximum amount of time
    • Run something periodically  with arguments  from the StartApp arguments

 

 

The solution is to make another application ( let’s name SideCarCLI ) that runs the  StartApplication.

What it is complicated her is how we pass the arguments of the SideCarCLI versus the arguments of the StartApp .

Full Projects

My first blog post in English is from 14 nov 2009 ( http://msprogrammer.serviciipeweb.ro/2009/11/14/jquery-learning/ ). It was on the time that Jquery was just integrated in VS 2010.

My first blog post about programming was from 13 March 2005 (http://serviciipeweb.ro/iafblog/2005/03/13/pentru-inceput/ ). I was working on “ log4Net, NUnit , C#, asp.net, VB.Net sai VB6” …..

From the old blog in Romanian, those are the projects that remains ok: http://serviciipeweb.ro/iafblog/2015/03/23/proiecte-codeplex/

From the new blog in English , those are the projects that I have created:  http://msprogrammer.serviciipeweb.ro/full-projects/

Enjoy!

YouTube playlist exporter

 

The point here is about how simple is in our days to make a simple script as a programmer.

I wanted to export my playlists ( 5 minutes .NET , Export Word Exce l PDF  , EF 6 , Traceability ) videos into a simple HTML file that I could put into my website.

I searched first on internet – however, I found just you tube google api .

So I read the documentation (e.g. https://developers.google.com/youtube/v3/docs/videos/list)  , grab a developer key from https://console.developers.google.com/ and made a simple project.

Used also a NuGet package for JSON( Newtonsoft.Json) and one for export in Excel /Word /HTML / PDF /ODS (ExporterWordExcelPDF).

Total time : 2 hours. You can find the project here https://github.com/ignatandrei/YouTube . It has only console application  – but it will have soon a GUI .

The point is that in our days it is easy to use third party application – and , for a programmer, easy as pie( eating, not making ; – ) )

MVC planning poker -Test driven development and Version control and Continuous Integration– foundation – 2

After setting the use cases, I have now think about code. ( Ok, maybe it should be first architecture, but I am a programmer first )

So I start to code the first Use case :

 
public class UseCase1CreateTable
    {
        [TestMethod]
        public void UseCase1RightPath()
        {
            var ModeratorName = "ignat andrei";
            var roundName = "UseCase1 - Create Table";
            var table = TableFactory.CreateTable(ModeratorName);
            table.AddDuration(1);
            table.AddDuration(2);
            table.AddDuration(3);
            table.AddRoundName(roundName);
            
            Assert.AreNotEqual(0,table.Id.Length);
            Assert.AreEqual(true,table.CanAddUser);
            Assert.AreEqual(ModeratorName,table.ModeratorName);
            Assert.AreEqual(1,table.Rounds.Length);
            Assert.AreEqual(roundName, table.Rounds[0].Name);


        }
    }
 

Running the test was a no-brainer – it does not even compile. And it is good, according to https://msdn.microsoft.com/en-us/library/aa730844(v=vs.80).aspx 

Now I want to test the code, so I created the classes and now the  tests were all red (because there is nothing implemented yet, just compiling) . A hour and all is going smoothly until the test was green – http://en.wikipedia.org/wiki/Test-driven_development

Now the point is to enforce this behavior every time the programmer checks in some code.

So I think about Visual Studio Online – to test if , aside Version Control, it can help me with running test.

And yes, they have builds.And, being the single contributor to this project, I choose Gated Checkins

image

 

Now every time I check-in some code, the build will start and see what’s happening.

The code is at https://ignatandrei.visualstudio.com/DefaultCollection/MVC%20Planning%20Poker 

Exercise  for home:

Do you spot what is missing from
this test code ?

 
public class UseCase1CreateTable
    {
        [TestMethod]
        public void UseCase1RightPath()
        {
            var ModeratorName = "ignat andrei";
            var roundName = "UseCase1 - Create Table";
            var table = TableFactory.CreateTable(ModeratorName);
            table.AddDuration(1);
            table.AddDuration(2);
            table.AddDuration(3);
            table.AddRoundName(roundName);
            
            Assert.AreNotEqual(0,table.Id.Length);
            Assert.AreEqual(true,table.CanAddUser);
            Assert.AreEqual(ModeratorName,table.ModeratorName);
            Assert.AreEqual(1,table.Rounds.Length);
            Assert.AreEqual(roundName, table.Rounds[0].Name);


        }
    }
 

MVC planning poker – use cases and mockups – 1

 

I have decided to start a new project – MVC planning poker . This is inspired by http://en.wikipedia.org/wiki/Planning_poker  – and it is a program to sharpen my skills

The project is aimed to software enterprises using Active Directory – however, it can be used by any organization.

 

UseCase 1: Create table
Moderator identified by Name -  creates the table and the duration times(1,2,3,5,10) and optional the round name.

He has an ID to share to the next participants

UseCase 2: Participants join the table
Any user can join the table by entering the ID + name .

Use Case 3: Moderator can boot from the table
Moderator can boot from the table( permanently of just for this session ) any participant.
If permanently, the participant with this name can not join anymore

Use Case 4: Estimation saved
Moderator enters a round name (?) .
Participants choose a value.
When all participants have choosen the value, the cards are shown
The cards with  high estimates and low estimates are highlighted
Host press "create new estimation" and create new estimation
The old estimation is saved in history

Use Case 5: Round reset
Moderator enters a round name (?) .
Participants choose a value.
Host press "reset round " and a fresh new round is created
The old one is not saved

Use Case 6: Round save
After a round is saved, the users can see the history round names and picked value
They can see also a total

Use Case 7: Export
Participants can choose if they download the results in CSV / EXCEL / Word /PDF format

Use Case 8: Round delete
The host can delete a round previously saved

 

The mockups are the following:

 

create_table table

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.