European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 8 Hosting - HostForLIFE.eu :: Unleash the Power of SuperInject with.NET Dependency Injection

clock December 18, 2023 05:53 by author Peter

Overview
Greetings, fellow programmers! Has your.NET project ever left you entangled in the complex web of dependency injection? Do not be alarmed! We've got you covered, and today we're launching the revolutionary SuperInject NuGet Library!

How does SuperInject work?
SuperInject is your reliable dependency injection sidekick, not just another NuGet package. Imagine this: simplified service and repository registration that incorporates a little bit of fun and simplicity.

How to Begin

First Step: The Installation Dance
Now let's start the celebration! Grab a terminal and give SuperInject a hug:

dotnet add package SuperInject

SuperInject loves to be invited to the party!

Step 2. Mark Your Classes, It’s Attribute Time!
Now, here comes the fun part. Mark your classes with the ServiceAttribute or RepositoryAttribute. It’s like giving your classes a VIP pass for the dependency injection club.

using SuperInject;

[Service(ServiceLifetime.Singleton)]
public class MySingletonService : ISomeInterface
{
// Implementation goes here...
}


And for repositories:
using SuperInject;

[Repository(ServiceLifetime.Transient)]
public class MyTransientRepository : ISomeInterface
{
// Implementation goes here...
}

Let’s Get SuperInjecting!

The stage is set, and the lights are on, now let’s call the shots with the SuperInject extension method. In your Startup.cs or Program.cs file, give your services and repositories a grand entrance:
// ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Use the AddSuperInject extension method to automatically register services and repositories
services.AddSuperInject();

// Your other service registrations go here...

// And the party continues...
}


Why SuperInject?
Attribute Awesomeness: No more tedious configurations! SuperInject’s attributes make your classes stand out, like stars on the red carpet.
Extension Method Magic: Say goodbye to manual registrations. Let SuperInject handle the heavy lifting, leaving you with more time for the fun stuff.
Avoid Circular Dependency Drama: SuperInject knows how to navigate the tricky paths of circular dependencies. It’s like having a GPS for your dependency injection journey.

Wrapping Up
SuperInject isn’t just a NuGet package; it’s your accomplice in writing cleaner, more maintainable code. So, what are you waiting for? Add a dash of SuperInject to your projects, and let the dependency injection party begin!

Ready to supercharge your dependency injection game? Grab SuperInject, and let the coding festivities begin!



ASP.NET Core 8 Hosting - HostForLIFE.eu :: Beginning Your NodaTime Journey

clock December 11, 2023 06:52 by author Peter

A more complete and reliable substitute for the built-in DateTime and DateTimeOffset classes in the.NET Framework is the date and time management library NodaTime. It is intended to handle typical problems and intricacies related to changing dates and times.

Important aspects of NodaTime

  • Immutable Types: NodaTime represents dates, times, and durations using immutable types. This encourages the development of a more consistent and thread-safe programming model and aids in the prevention of accidental object change.
  • Rich number of Types: NodaTime offers a rich number of types, such as ZonedDateTime (a date and time in a particular time zone), LocalDate (a date without a time), Instant (a point on the timeline), and LocalTime (a time without a date).
  • Time Zones: NodaTime provides extensive time zone support, enabling developers to operate across time zones, carry out conversions, and manage changes in daylight saving time.
  • Duration and Period: To handle time spans and calendar discrepancies, respectively, more expressively and precisely, NodaTime provides the Duration and Period types.
  • Compatibility with.NET Platforms: NodaTime is made to function with the.NET Framework,.NET Core, and.NET 5/6, among other.NET platforms.
  • Improved Thread Safety: Reasoning about concurrent programs requiring date and time operations is made easier by the usage of immutable types.
  • NodaTime's extensibility enables developers to specify their own calendar systems and, if necessary, provide more time zone data.
  • Testing Support: NodaTime comes with features to make testing easier, like a FakeClock to manage time in unit tests.
NodaTime was developed to provide a more reliable and developer-friendly method of handling date and time in.NET programs by addressing some of the shortcomings and difficulties related to the DateTime and DateTimeOffset classes. When handling situations where exact control over time and time zones is necessary, it is quite helpful.

Noda Time aims for.NET Standard 1.3 and.NET 4.5. We don't utilize dynamic typing in the distributable libraries for optimal compatibility, although we do use it periodically in testing. Noda Time users do not require a current C# compiler, but we usually make advantage of language features as soon as they are made available in stable beta and general release. Although we make every effort to avoid adding external dependencies, using C# 7 tuples is currently not possible since System.ValueTuple would add another dependence.

How Do I Begin Using NodaTime?
1) Use the package manager console to perform the following command or install the NodaTime package/library from the Manage NuGet package. This is NodaTime's core library.
Install-Package NodaTime

2) Install the NodaTime Serialization package/library as below in the package manager console. This library is useful when serializing the NodaTime type.
Install-Package NodaTime.Serialization.JsonNet

3) Install the NodaTime Testing library for building the Unit test project.
Install-Package NodaTime.Testing

NodaTime properties
Instant

In NodaTime, Instant is a fundamental type representing an instantaneous point on the timeline. It is similar to DateTimeOffset in the .NET Framework but provides a more precise representation of time, particularly in scenarios where high precision is required.Install-Package NodaTime

2) Install the NodaTime Serialization package/library as below in the package manager console. This library is useful when serializing the NodaTime type.
Install-Package NodaTime.Serialization.JsonNet

3) Install the NodaTime Testing library for building the Unit test project.
Install-Package NodaTime.Testing

NodaTime properties
Instant

In NodaTime, Instant is a fundamental type representing an instantaneous point on the timeline. It is similar to DateTimeOffset in the .NET Framework but provides a more precise representation of time, particularly in scenarios where high precision is required.
Instant instant = SystemClock.Instance.GetCurrentInstant();
Console.WriteLine($"NodaTime Instant : {instant}");

Output. NodaTime Instant: 2023-12-08T05:22:05Z

Converting Instant type into UTC time.
Instant convertedToUtc = instant.InUtc().ToInstant();
Console.WriteLine($"NodaTime in UTC : {convertedToUtc}");

Output.
NodaTime in UTC: 2023-12-08T05:22:05Z

Getting Instant type with TimeZone specified.
Instant convertedToEastern = instant.InZone(DateTimeZoneProviders.Tzdb["America/New_York"]).ToInstant();
Console.WriteLine($"NodaTime in Zone : {convertedToEastern}");

Output. NodaTime in Zone: 2023-12-08T05:22:05Z

ZonedDateTime
'ZonedDateTime in NodaTime is a type that represents a specific date and time with an associated time zone. This is particularly useful for handling time-related information in a way that considers different time zones and daylight saving time changes.
ZonedDateTime zonedDateTime = instant.InZone(DateTimeZoneProviders.Tzdb["Europe/Berlin"]); //US/Pacific
Console.WriteLine($"NodaTime ZonedDateTime : {zonedDateTime}");


Output. NodaTime ZonedDateTime : 2023-12-08T06:22:05 Europe/Berlin (+01)

OffsetDateTime
'OffsetDateTime in NodaTime represents a date and time along with an offset from UTC (Coordinated Universal Time). This type is useful when you want to work with an absolute point in time while considering the offset from UTC.
OffsetDateTime offsetDateTime = OffsetDateTime.FromDateTimeOffset(dateTimeOffset);
Console.WriteLine($"NodaTime offsetDateTime : {offsetDateTime}");


Output. NodaTime offsetDateTime : 2023-12-08T10:52:05+05:30

LocalDateTime
'LocalDateTime in NodaTime represents a date and time without any specific time zone or offset from UTC. It's a combination of a LocalDate and a LocalTime. This type is suitable for situations where you want to work with a date and time without considering time zone-related adjustments.
LocalDateTime localDateTime = zonedDateTime.LocalDateTime;
Console.WriteLine($"NodaTime LocalDateTime : {localDateTime}");

Output. NodaTime LocalDateTime : 12/8/2023 6:22:05 AM

LocalDate
'LocalDate in NodaTime represents a date without considering any time zone or offset from UTC. It only consists of the year, month, and day components. This type is suitable for situations where you need to work with dates independently of time zones or daylight-saving time changes.
LocalDate LD = new LocalDate(1992, 05, 08);
Console.WriteLine($"LocalDate : {LD}");


Output. LocalDate : Friday, May 8, 1992

LocalTime

'LocalTime in NodaTime represents a time of day without any association with a specific time zone or offset from UTC. It captures the hour, minute, second, and fractional seconds of a given time, allowing you to work with time-related operations without considering time zone changes.
LocalTime LT = new LocalTime(8, 0, 0);
Console.WriteLine($"LocalTime : {LT}");


Output. LocalTime : 8:00:00 AM

Summary
NodaTime offers a robust and flexible solution for handling date and time in .NET applications, addressing many of the limitations and ambiguities present in the standard DateTime types.



ASP.NET Core 8 Hosting - HostForLIFE.eu :: Enhancing Code Readability with Return Templates in the View Section

clock December 4, 2023 07:00 by author Peter

The programming approach known as "code-behind" allows for a more tidy division of responsibilities by separating the HTML code and display logic. It entails putting the code in a different class file, which can make it easier to comprehend and manage.


Most people associate Microsoft web forms with Code-Behind. Please be aware that the CodeBehind framework has nothing to do with Microsoft's previous web form; rather, it is a back-end framework for.NET Core. With the Code-Behind pattern, the server-side and client-side developers carry out the development work independently of each other, fully separating the design (such as HTML) from the server-side coding portion.

The issue of conditionals and loops
Please be aware that unless the server part code is added, variables such as those between the design part code are still regarded as Code-Behind.

It is quite obvious when variables are included between html or xml codes, etc.

Variable examples between the design section
Razor syntax

<h1>@model.PageName</h1>

Standard syntax
<h1><%=model.PageName%></h1>

The @model in the previous two cases.The Code-Behind method is still in place because PageName and <%=model.PageName%> data are clearly visible in the html tags and are easily recognizable by designers or client-side developers.

This is built on the Code-Behind design, thus there won't be any issues.

However, in most cases, you should either add the server side codes in the design part or the server side codes in the design part for recurring sections like loops and conditions.

Therefore, there is no way out!

In the design part is an illustration of server-side coding.
<table>
    <thead>
        <tr>
            <th>Column1</th>
            <th>Column2</th>
            <th>Column3</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Column1</td>
                <td>@item.Column2</td>
                <td>@item.Column3</td>
            </tr>
        }
    </tbody>
</table>

Example of integration of the design part in the server-side codes

model.ListValue = "<ul>";

foreach(string s in List)
    model.ListValue += "<li>" + s + "</li>";

model.ListValue += "</ul>";

Using Code-Behind Compliance Templates
Microsoft's web form was one of the most well-known frameworks that ensured the separation of server-side scripts from the design department. However, this guarantee came at a high cost, with extra codes and limited designer control over the design department.

The most recent version of the CodeBehind framework includes a new recursion template feature that allows for the development of a 100% Code-Behind based design structure.

A page view's templates are segments that are linked to template variables prior to the compilation of the view section.

Both standard and razor syntax use the template. It is not possible to utilize the standard syntax template for razor syntax or the razor syntax template for standard syntax.
A basic template example using standard syntax.
<%@ Page Controller="YourProjectName.DefaultController" Model="YourProjectName.DefaultModel" %>
<!DOCTYPE html>
<html>
<head>
+   <#GlobalTags#>
    <title><%=model.PageTitle%></title>
</head>
<body>
    <%=model.BodyValue%>
</body>
</html>

+<#GlobalTags
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1.0" />
+<meta http-equiv="Content-Type" content="text/html; charset=utf-16" />
+<meta http-equiv="content-language" content="en">
+<script type="text/javascript" src="/client/script/global.js" ></script>
+<link rel="alternate" type="application/rss+xml" title="rss feed" href="/rss/" />
+<link rel="shortcut icon" href="/favicon.ico" />
+<link rel="stylesheet" type="text/css" href="/client/style/global.css" />
+#>

The output is translated as follows in this example when the Template variable calls a Template section.
<%@ Page Controller="YourProjectName.DefaultController" Model="YourProjectName.DefaultModel" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-16" />
    <meta http-equiv="content-language" content="en">
    <script type="text/javascript" src="/client/script/global.js" ></script>
    <link rel="alternate" type="application/rss+xml" title="rss feed" href="/rss/" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="/client/style/global.css" />
    <title><%=model.PageTitle%></title>
</head>
<body>
    <%=model.BodyValue%>
</body>
</html>

The aforementioned example introduced you to the idea of templates and demonstrated their basic functionality in the CodeBehind framework. However, return templates have one special feature: they are first put into the template before replacing the entire template.

Two categories of templates exist.

Template: Return to template
The template variable can be used to call either type of template.
A template definition example using Razor syntax.

+@#TemplateName{
@{
string ExampleText = "This is example text";
}
<b>Example value is : @ExampleText</b>
+}

In each template definition, the at sign and sharp (@#) characters are used first, followed by the template name, and finally the block character ({) at the conclusion. The block is closed (}) when the desired values have been added.The template variable must be written in order to call the template. The name of the template is typed after the sign and sharp (@#) letters are added at the beginning to write the template variable.Example of using a template variable to call a template.

<!DOCTYPE html>
<html>
<body>
+  @#TemplateName
</body>
</html>

Example of after pasting the template.

<!DOCTYPE html>
<html>
<body>
@{
string ExampleText = "This is example text";
}
<b>Example value is : @ExampleText</b>
</body>
</html>

Returned templates are first inserted into a variable with the same name as the template name, and then the entire template is replaced by the returned template (all three are the same name).

The at sign and sharp (@#) characters are used at the beginning of each return template definition, and then the name of the template is written. Then, the equal character (=) is added, and at the end, the block character ({) is used. Then, the desired values are added, and finally, the block is closed (}).

Example (Razor syntax)View the section before pasting the template.

In the codes above, there is a return template called Tags, which is specified with the string @#Tags= and its value is known inside the blockpPasting template auto step 1.

<div class="header">
  <a href="#default">@model.Title</a>
  <div class="header-right">
    @#Tags={<a href="@#Href">@#PageName</a>}
  </div>
</div>

@#Tags{
@foreach (PageItem page in model.PageItemList)
{
    <a href="@#Href">@#PageName</a>
}
}

@#PageName{@page.Title}
@#Href{@(((page.Path == "main")? "/" : page.Path))}


As you can see in the above codes. First, the value inside the returned template block with the name Tags is replaced in the Tags template variable inside the Tags template.

pasting template auto step 2.
<div class="header">
  <a href="#default">@model.Title</a>
  <div class="header-right">
    @foreach (PageItem page in model.PageItemList)
    {
        <a href="@#Href">@#PageName</a>
    }
  </div>
</div>

@#PageName{@page.Title}
@#Href{@(((page.Path == "main")? "/" : page.Path))}


According to the above codes, in the second step, the values of the Tags template are replaced in the place of the returned template.

pasting template auto step 3 (finally).

<div class="header">
  <a href="#default">@model.Title</a>
  <div class="header-right">
    @foreach (PageItem page in model.PageItemList)
    {
        <a href="@(((page.Path == "main")? "/" : page.Path))">@page.Title</a>
    }
  </div>
</div>


In the last step, the values of other templates are replaced in the place of template variables.

In the template placement example, if you add the template externally, you will have the following html in the design section.

View the section before pasting the template.

<div class="header">
  <a href="#default">@model.Title</a>
  <div class="header-right">
+    @#Tags={<a href="@#Href">@#PageName</a>}
  </div>
</div>


Without a return template, at best, you will have the following html in the design section.

View the section without the use of the return template.

<div class="header">
  <a href="#default">@model.Title</a>
  <div class="header-right">
+ @foreach (PageItem page in model.PageItemList)
+ {
+    <a href="@(((page.Path == "main")? "/" : page.Path))">@page.Title</a>
+ }
  </div>
</div>


Please note that this was a simple example, and the situation may be very complex.

You can also use a template for standard syntax. The following code shows the previous template example in standard syntax.

<div class="header">
  <a href="#default"><%=model.Title%></a>
  <div class="header-right">
    <#Tags=<a href="<#Href#>"><#PageName#></a>#>
  </div>
</div>

<#Tags
<% foreach (PageItem page in model.PageItemList)
{
    <#Tags#>
}
%>
#>

<#PageName <%=page.Title%>#>
<#Href <%=((page.Path == "main")? "/" : page.Path)%>#>


If the return value is placed between the standard syntax tags, the syntax will be automatically closed before the return value, and the syntax will be opened after it.
Copy template auto step finally for standard syntax.

<div class="header">
  <a href="#default"><%=model.Title%></a>
  <div class="header-right">
    <% foreach (PageItem page in model.PageItemList)
    {
        %><a href="<%=((page.Path == "main")? "/" : page.Path)%>"><%=page.Title%></a><%
    }
    %>
  </div>
</div>


Conclusion
No matter how much you try to avoid mixing server-side codes in the view section, in some cases, such as loops and conditions, you will have to use server-side codes in the view section; the presence of mixing server-side codes reduces the readability of the codes and makes the appearance of the view section ugly, and it becomes difficult to maintain the codes and also leads to complex interaction between the server-side and client-side developers in high-scale applications. Applying the return template keeps the code of the server section outside the view section. As a result, the view section will have a great appearance, and the Code-Behind pattern will be fully respected.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in