Category: nuget

[NuGet]: Polly

This is a Nuget that I use in all projects when I am making HTTP calls..

Link: https://www.nuget.org/packages/polly

Site: https://github.com/App-vNext/Polly

What it does:  Implements all kind of policies for retrying – see https://github.com/App-vNext/Polly/wiki/Transient-fault-handling-and-proactive-resilience-engineering

Usage: – copied from https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly

static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
     return HttpPolicyExtensions
         .HandleTransientHttpError()
         .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
         .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2,
                                                                     retryAttempt)));
}

[Nuget]:NPOI

This is a Nuget that I use in almost every .NET Core project to export files in an Excel format without excel on the PC.

Link: https://www.nuget.org/packages/npoi

Site: https://github.com/nissl-lab/npoi

What it does:  Create real Excel files – not just CSV

Usage:

var wb = new XSSFWorkbook();
var sheet = wb.CreateSheet(“Contractors”);
for (int i = 0; i < allContractors.Count; i++)
{
var contractor = allContractors[i];
IRow row = sheet.CreateRow(i);
for (int j = 0; j < contractor.Length; j++)
{
var cell = row.CreateCell(j);
cell.SetCellValue(contractor[j].ToString());
}
}
wb.Write(File.OpenWrite(“Contractors.xlsx”));

[NuGet]:Scriban

This is a Nuget that I use in almost every .NET Core project to get the error details ( 500)

Link: https://www.nuget.org/packages/Scriban/

Site: https://github.com/scriban/scriban

What it does:  Like Razor –  a template intepreter

Usage:

var template = Template.Parse(@"
<ul id='products'>
  {{ for product in products }}
    <li>
      <h2>{{ product.name }}</h2>
           Price: {{ product.price }}
           {{ product.description | string.truncate 15 }}
    </li>
  {{ end }}
</ul>
");
var result = template.Render(new { Products = this.ProductList });

[NuGet]:Hellang.Middleware.ProblemDetails

This is a Nuget that I use in almost every .NET Core project to get the error details ( 500)

Link: https://www.nuget.org/packages/Hellang.Middleware.ProblemDetails/

Site: https://github.com/khellang/Middleware

What it does:  Gives detailed error when encountering a 500 HTTP Code.

Usage:

services.AddProblemDetails(c=>
             {
                 c.IncludeExceptionDetails = (context, ex) => true;               
             });

app.UseProblemDetails();

[NuGet] : MimeTypeMapOfficial

This is a Nuget that I use in NetCore2Blockly to know the type of the file embedded:

Link: https://www.nuget.org/packages/MimeTypeMapOfficial/

Site: https://github.com/samuelneff/MimeTypeMap

What it does: Provides a huge two-way mapping of file extensions to mime types and mime types to file extensions,

If no mime type is found then the generic “application/octet-stream” is returned.

Usage:

static string contentFromExtension(string file)
{
     var dot = file.IndexOf(“.”);
     if (dot < 1)
         return “text/html”;

    var ext = file.Substring(dot+1).ToLowerInvariant();
     return MimeTypeMap.GetMimeType(ext);

}

Using files in a ASP.NET Core nuget package

To use static (html) files in a NUGET ASP.NET Core package to be displayed I have used the following solution

1. Put the files in a folder ( in my case , blocklyAutomation )

2. Put in the .csproj to embed the files

<ItemGroup>
   <EmbeddedResource Include=”BlocklyAutomation\**\*”>
     <CopyToOutputDirectory>Never</CopyToOutputDirectory>
   </EmbeddedResource>
</ItemGroup>

3.  Create an extension to use it

;

public static void UseBlocklyUI(this IApplicationBuilder appBuilder)
{
    var manifestEmbeddedProvider =
            new ManifestEmbeddedFileProvider(Assembly.GetExecutingAssembly());
    var service = appBuilder.ApplicationServices;
    mapFile("blocklyAutomation", manifestEmbeddedProvider, appBuilder);


}

private static void mapFile(string dirName, IFileProvider provider, IApplicationBuilder appBuilder)
{
    var folder = provider.GetDirectoryContents(dirName);
    foreach (var item in folder)
    {
        if (item.IsDirectory)
        {
            mapFile(dirName + "/" + item.Name, provider, appBuilder);
            continue;
        }
        string map = (dirName + "/" + item.Name).Substring(dirName.Length);
        appBuilder.Map(map, app =>
        {
            var f = item;

            app.Run(async cnt =>
            {
                //TODO: find from extension
                //cnt.Response.ContentType = "text/html";
                using var stream = new MemoryStream();
                using var cs = f.CreateReadStream();
                byte[] buffer = new byte[2048]; // read in chunks of 2KB
                int bytesRead;
                while ((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }
                byte[] result = stream.ToArray();
                var m = new Memory<byte>(result);
                await cnt.Response.BodyWriter.WriteAsync(m);
            });
        });
    }

}

4. That is all

.NET Core global tool CD/CI with AzureDevops to Nuget

I want to can deploy automatically from GitHub  to Nuget a .NET Global ( or local ) tool.

It is enough simple;

1. Get an API key from GitHub

2. Goto to your AzureDevops , settings ( down the page ) and connect with a new Service Connection AzureDevops to GitHub ( name: nugetAndrei)

3. Make an yaml file similar with this:

# ASP.NET Core

# Build and test ASP.NET Core web applications targeting .NET Core.

# Add steps that run tests, create a NuGet package, deploy, and more:

# https://docs.microsoft.com/vsts/pipelines/languages/dotnet-core

#https://dev.azure.com/ignatandrei1970/AOPRoslyn/

pool:

vmImage: ‘VS2017-Win2016’

variables:

buildConfiguration: ‘Release’

deployNuget: ‘0’

steps:

– script: |

    cd AOPRoslyn

    dotnet tool restore

displayName: ‘restore tool’

– script: dotnet restore AOPRoslyn\AOPRoslyn.sln

displayName: ‘restore project’

– script: |

    cd AOPRoslyn

    dotnet tool run pwsh -f ./makenuget.ps1

displayName: ‘powershell to version and pack’

– script: dotnet build AOPRoslyn\AOPRoslyn.sln –configuration $(buildConfiguration)

displayName: ‘dotnet build $(buildConfiguration)’

– script: dotnet pack AOPRoslyn\aopCmd\aop.csproj  –no-build -o $(Build.ArtifactStagingDirectory) /p:Configuration=$(buildConfiguration) # –verbosity Detailed

displayName: ‘dotnet pack ‘

– task: PublishBuildArtifacts@1

inputs:

pathtoPublish: ‘$(Build.ArtifactStagingDirectory)’

artifactName: drop1

# – task: NuGetAuthenticate@0

#   inputs:

#     nuGetServiceConnections: ‘nugetAndrei’

– task: NuGetCommand@2

condition: and(succeeded(), eq(variables[‘deployNuget’], ‘1’))

inputs:

command: push

nuGetFeedType: external

packagesToPush: ‘$(Build.ArtifactStagingDirectory)/**/*.nupkg’

publishFeedCredentials: ‘nugetAndrei’

displayName: ‘dotnet nuget push’

# – task: DotNetCoreCLI@2

#   displayName: Push Nuget Package

#   inputs:

#     command: custom

#     custom: nuget

#     arguments: >

#       push $(Build.ArtifactStagingDirectory)\*.nupkg

#       -s https://api.nuget.org/v3/index.json

#       -k $(NuGetSourceServerApiKey)

You can find the source here:
https://github.com/ignatandrei/AOP_With_Roslyn/commit/e5b244f61e77cd0c5ec34c97e1a0122f9625de25

Entity Framework 6 Record and play use : Unit Testing ( part 2 of 5)

 

Part 1 : What is EF record and play : http://msprogrammer.serviciipeweb.ro/2014/11/29/entity-framework-6-record-and-play-1-of-5/ 

Part 2: EF Record and play use: Testing : http://msprogrammer.serviciipeweb.ro/2014/12/08/entity-framework-6-record-and-play-use-unit-testing-part-2-of-5/

Part 3: EF Record and play use: Make demo: http://msprogrammer.serviciipeweb.ro/2014/12/14/entity-framework-6-record-and-play-use-making-demos-part-3-of-5/ 

Part 4: EF Record and play use: Record user Sql when a bug occurs: http://msprogrammer.serviciipeweb.ro/2014/12/26/ef-record-and-play-use-recording-user-sql-when-a-bug-occurred-part-4-of-5/

Part 5: EF record and play: conclusions: http://msprogrammer.serviciipeweb.ro/2015/01/05/ef-record-and-play-conclusions/

 

Let’s suppose that we have a program that have Departments and Employees.

And we want to make sure that, when we add an employee, the department must exists.

We can ensure this from database ( by foreign key) but we can pro-actively search for the department and throw a more meaningful validation .

More, I like more validation than errors.

So, let’s suppose that in the Validation for the Employee we must check in the database for the IdDepartment to see if there is such a department.

How could we make a test for that runs without a database ?

With some trick:  we first Record with a database  – then we can Play the file – and we do not need anymore the database. The test is self contained. 

 

Let’s see in action here

 

Database.SetInitializer<ContextForDatabase>(null);
            #region set record EF
            var record = new InterceptionRecordOrPlay(@"VerifyIValidatableWorks.zip", ModeInterception.Play);

            DbInterception.Add(record);
            #endregion
            var e= new Employee();
            e.ValidateEmployee = true;
            e.IDDepartment = 60000;
            var err= e.Validate(null).ToArray();
            Assert.IsNotNull(err);
            Assert.AreEqual(1, err.Length);

Source code is available at  https://github.com/ignatandrei/EFRecordAndPlay/wiki/

 

There is also a NuGet package at https://www.nuget.org/packages/EFRecordAndPlay/

Browser history–part 5–conclusions

This is the part 5 of 5 of my implementing of a MVC Browser history

MVC browser history – idea

Browser history –2 – implementing, small bugs

Browser history 3–trying to Nuget – modifications in order to can be transformed from an application to a component

Browser history 4–NuGet again -  finally Nuget deployment

Browser history–part 5–conclusions  – conclusions

 

 

I have reached the (partial) final for my MVC Browser History .  It has started as a simple application – and now it is a NuGet component ready to be used and a demo project at app harbour

What can do for you as a MVC programmer :

  • The component can be integrated in any MVC application easily (via NuGet)
  • you will have a page that displays the list of links that are part of the project and the top 5(configurable) accessed pages
  • You can have this filtered per user basis – or per administrator( small changes in the controller action)
  • It can save the history in memory or in sql server database( configurable in History page, ) or you can make your saving data by implementing  IBrowserUserHistoryRepository
  •  

    You can see in action at app harbour

    If you use, please send me an email.

    If you worry about code source, you can find at github . If you want to improve, feel free to participate Winking smile

    Browser history 4–NuGet again

    This is the part 4 of 5 of my implementing of a MVC Browser history

    MVC browser history – idea

    Browser history –2 – implementing, small bugs

    Browser history 3–trying to Nuget – modifications in order to can be transformed from an application to a component

    Browser history 4–NuGet again – finally Nuget deployment

    Browser history–part 5–conclusions – conclusions

    Prior to Nuget, I think that will be better if the user of my app could play with sql server or memory implementation. So the new GUI is here:

    image

     

    But how could I show to the user where it is saved? Easy – to the history page

    image

     

    And now I can make the NuGet Package .

    In order to can download a controller and not overwrite the Home controller, I must create a controller of its own – so make a modification : History Controller

    Now adding dependencies, fighting with NuGet Explorer,

    In the first test  StructureMap dll reference missing and the Views folder was in the wrong place.

    In the second test , I discovered that I was missing adding the following essential lines

    filters.Add(new BrowserHistory.Models.BrowserUserHistoryFilter());
    ObjectFactory.Configure(ce => ce.For<IBrowserUserHistoryRepository>().Use<BrowserUserHistoryRepositoryMemory>());

     

    So I began reading how to add to global.asax at nuget package installing time – and coming with this:http://blogs.msdn.com/b/davidebb/archive/2010/10/11/light-up-your-nupacks-with-startup-code-and-webactivator.aspx

    Adding code,testing -  another 15 minutes.

    Adding readme.txt – in order to explain what have I done and how to use it – another 30 minutes.

    Now it is ready to be used by you.

    If you want to test it, you can see in action at http://browserhistory.apphb.com/
    Detailed history of creating project at http://msprogrammer.serviciipeweb.ro/category/browserhistory/
    Source code at https://github.com/ignatandrei/MVCbrowserHistory

     

    Next time will do a summary of what I have done in order to build this simple utility project.

    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.