Category Archives: .net online training

A Look At The ASP.NET Core Pitfalls

When you intend to redirect after a Post, following the Post-Redirect-Get pattern but your previous view is constructed using a route parameter, then it would be sent to the redirect action too.

A Look At The ASP.NET Core Pitfalls

For instance, you are responding to a request for /Filter/Smartphone, where Smartphone is a route parameter, you Post it to some other controller action and at the end, you redirect to the Index action making use of the RedirectToAction method:

Return this.RedirectToAction(name of(Index));

The browser would issue the GET request for Index but takes the Smartphone route parameter, which is not fine.

The solution is to pass a routeValues parameter to RedirectToAction that do not have any of the possible route parameters. One way to do it is that you can create a dictionary with all action parameters zeroed:

return this.RedirectToAction(nameof(Index), MethodBase.GetCurrentMethod().GetParameters().ToDictionary(x => x.Name, x => (object) null));

The solution to do this automatically lies in the MethodBase.GetCurrentMethod() method. This way, you can surely avoid unwanted route parameters during your next request.

In case you wonder, passing null, a dictionary without object or entries would not work, the only other way is to pass an unknown value with the parameters set to null.

That’s it for now!

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support.

We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.

Happy Coding!

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

The Future Of Dot Net Core

Microsoft .NET as a platform which has an open source component and is an evolving platform. Not only .NET Core is an open source, but also managed by a well-managed body namely, the .NET Foundation. In short the future of .Net is really bright. To know more, keep reading.

The Future Of Dot Net Core

The future of .NET Core is also very bright and exciting. Many people and organizations are getting involved in.NET Core.

What is .NET Core?

This is a cross-platform, fast, lightweight, updated, open-source framework for developing mobile, Web, and Windows applications and services that can be deployed and run on Windows, Linux and Mac operating systems.

Key features of .NET Core:

  • An open source
  • A cross-platform
  • A a high-performance and a scalable platform
  • This supports Docker containers
  • This is designed to support Microservices architecture
  • This supports Github and NuGet integration
  • Supports command line tools
  • Created to target cloud deployment
  • This is continuously evolving

 

Built on a proven foundation

Though a newly and rewritten platform it, has a great proven foundation of .NET Framework, compilers, CLR, and languages. There are approximately 8 to 10 million .NET developers, according to Scott Hanselman (Microsoft) and Joe Spolsky (StackOverflow). The .NET Core is developed depending on today’s market needs and feedback from many .NET developers.

 

A Built for the Future

It is a well-planned framework with a foundation of a successful framework, languages, toolset, and several other third-party supports. .NET Core has a foundation of .NET framework and its core languages include C#, VB.NET, and F#. .NET Core also brings very powerful developer tools which include VS IDE, VS Team Services, and VS Code editor.

 

Xamarin and Mobile Apps

Microsoft acquired Xamarin and news is that it could be a part of .NET Core to support Android and iOS development which uses C# and F# programming languages.

 

An Open Source

The .NET Foundation is an independent organization and has open development and collaboration around the .NET ecosystem.

 

This is developed for Cloud

Allen O’Neill says that .NET Core is the first and foremost, modular, managed and cross-platform in real manners. The platform is built with cloud keeping in mind and is initially targeting low level or server-based systems.

 

How .NET Core fits in the .NET Ecosystem?

The .NET ecosystem comprises of 3 major high-level components, namely .NET Framework, .NET Core, and Xamarin.

The .NET Framework is used to create Windows applications using WPF and Windows Forms and Web applications making use of ASP.NET MVC.

.NET Core supports UWP and ASP.NET Core libraries. UWP is used to create Windows 10 targeted apps and ASP.NET Core is used to build Web apps for Windows, Linux, and Mac operating systems.

 

Today Microsoft supports WPF, Windows Forms, and ASP.NET MVC and would continue to do so for a longer time. If you’re a .NET developer, know that .NET Core is the future of your development process.

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute would be of great help and support.

We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in Pune, CRB Tech has developed its own identity. Happy Coding!

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

An Overview Of How To Seed Users And Roles With Code In ASP.NET Core Identity

With the help of ASP.NET Core identity, you can implement authentication and authorization for your web applications. Working with ASP.NET Core Identity, sometimes you have to create a default user accounts and roles in the system. In ASP.NET MVC it can be done in Global.asax and Application_Start event handler. In ASP.NET Core the process different because its application startup process is different.

Seed Users And Roles With Code In ASP DOT NET Core Identity

In case you there is a MyIdentityDbContext, MyIdentityUser and MyIdentityRole classes ready, next your aim is to create a few user accounts and some roles when the application executes for the first time. This is to be done only when those users and roles don’t exist in the database.

Here we shall discuss two ways of putting the data:

  • Using Configure () method
  • Using Main () method

The former method is simple and direct with minimal coding, as you inject objects in other parts of your application, you can inject them into the Configure () method also. The latter approach is complex and needs you to shift the seeding operation to the Main() from Program.cs.

Edit your Configure () method signature as shown below :

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

}

Next can be inserted UserManager and RoleManager into the Configure() method. Hence you can use UserManager to develop user accounts and RoleManager to create roles at the application startup. Instead of directly writing codes inside the Configure() method, it would be isolated in a separate class and then get it from there.

What is necessary is to add a new class called MyIdentityDataInitializer into the project. The following code shows the structure of this class :

public static class MyIdentityDataInitializer

{

public static void SeedData

(UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

}

public static void SeedUsers

(UserManager<MyIdentityUser> userManager)

{

}

public static void SeedRoles

(RoleManager<MyIdentityRole> roleManager)

{

}

}

The MyIdentityDataInitializer class has 3 static methods – SeedRoles(), SeedUsers() and SeedData(). If you want to create both – users and roles – then you would summon SeedData().

Here we shall take a look at the codes that go inside the methods.

The SeedRoles() develops desired default roles in the system and appears like this :

public static void seed rolls

(RoleManager<MyIdentityRole> roleManager)

{

if (!roleManager.RoleExistsAsync

(“NormalUser”).Result)

{

MyIdentityRole role = new MyIdentityRole();

role.Name = “NormalUser”;

role.Description = “Perform normal operations.”;

IdentityResult roleResult = roleManager.

CreateAsync(role).Result;

}

if (!roleManager.RoleExistsAsync

(“Administrator”).Result)

{

MyIdentityRole role = new MyIdentityRole();

role.Name = “Administrator”;

role.Description = “Perform all the operations.”;

IdentityResult roleResult = roleManager.

CreateAsync(role).Result;

}

}

The SeedRoles() method takes in RoleManager as its parameter. Inside, is created two roles in the system – NormalUser and Administrator. You must change the role names and their description as you need.

The SeedUsers() develops desired default user accounts and appears like this :

public static void SeedUsers

(UserManager<MyIdentityUser> userManager)

{

if (userManager.FindByNameAsync

(“user1″).Result == null)

{

MyIdentityUser user = new MyIdentityUser();

user.UserName = “user1″;

user.Email = “user1@localhost”;

user.FullName = “Nancy Davolio”;

user.BirthDate = new DateTime(1960, 1, 1);

IdentityResult result = userManager.CreateAsync

(user, “password_goes_here”).Result;

if (result.Succeeded)

{

userManager.AddToRoleAsync(user,

“NormalUser”).Wait();

}

}

if (userManager.FindByNameAsync

(“user2″).Result == null)

{

MyIdentityUser user = new MyIdentityUser();

user.UserName = “user2″;

user.Email = “user2@localhost”;

user.FullName = “Mark Smith”;

user.BirthDate = new DateTime(1965, 1, 1);

IdentityResult result = userManager.CreateAsync

(user, “password_goes_here”).Result;

if (result.Succeeded)

{

userManager.AddToRoleAsync(user,

“Administrator”).Wait();

}

}

}

The SeedUsers() method accepts a UserManager and develops two users – user1 and user2. It has to be first checked if a user with the same name exists or not. If it doesn’t exist then it has to be created with default values of l, full name, and birth date. The values can be changed as needed.

The SeedUsers() and SeedRoles() do not return any value. But the signature can be changed to return some status of success or failure if you so wish.

The SeedData() basically summons SeedRoles() and SeedUsers() and appears like this :

public static void SeedData

(UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

SeedRoles(roleManager);

SeedUsers(userManager);

}

The SeedData() method accepts a UserManager and a RoleManager. Inside, it summons SeedRoles() and SeedUsers(). Watch out that, SeedRoles() is summoned first because SeedUsers() assigns certain roles to the users being added and those roles must exist in the system before adding the users.

Seeding data in Configure()

And it is time to use the MyIdentityDataInitializer class. Open the Startup class, go to Configure() method and add the following line of code:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

app.UseAuthentication();

MyIdentityDataInitializer.SeedData(userManager, roleManager);

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}/{action=Index}/{id?}”);

});

}

After summoning, UseAuthentication() we summon SeedData() on MyIdentityDataInitializer.

Execute the application and see if the users get created in the database or not.

In the previous code are created default users and roles in the Configure() method. You can also do that work in Main() method. The following code shows how the Main() code would look like :

public static void Main(string[] args)

{

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())

{

var serviceProvider = scope.ServiceProvider;

try

{

var userManager = serviceProvider.

GetRequiredService<UserManager<MyIdentityUser>>();

var roleManager = serviceProvider.

GetRequiredService<RoleManager<MyIdentityRole>>();

MyIdentityDataInitializer.SeedData

(userManager, roleManager);

}

catch

{

}

}

host.Run();

}

Instead of inserting UserManager and RoleManager into Configure() you take them from GetRequiredService() method. The userManager and roleManager objects are next passed on to SeedData() as earlier.

That’s it for now!

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among various best institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.

Happy Coding!

Codes: Google database

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Know About The MiniBlog.Core Built Using ASP.NET Core 2.0

Are you aware of the MiniBlog.Core? Well, to mention it is a new and powerful blog platform built on ASP.NET Core 2.0 and offers an excellent reading experience on every device. It has the best practices for web development, which includes best-in-class performance, readability, accessibility, SEO, social web integration with the help of a mobile-first strategy.

Know About The MiniBlog.Core Built Using ASP DOT NET Core 2.0

Building Miniblog.Core

One who designed the blog wanted to design a blog engine based on ASP.NET Core that takes every advantage of modern browsers to develop the best possible experience for both the visitors and authors. To achieve that, the blog must load very fast, offer a great reading experience, appear amazing on every type of devices and handle every technical stuff like social media integration and SEO automatically.

Web fonts

To select the right font is essential to offer a good experience for the readers. For that, you need to use a custom web font which is being loaded and used by CSS. The problem with custom web fonts is that the browser has to download them followed by a slow mobile connection.

Instead, its maker wanted to apply fonts which are built on various browsers to offer the same high-quality reading experience but without any extra file downloads.

Image optimization

An extension for image optimisation for Visual Studio is used for years to optimize the images in the web projects. That is good for images up front, but what about those being uploaded by the users as part of blog posts? How to optimise the images, on the production server while they get uploaded.

As there are no .NET Core libraries which can optimize images as well as the Image Optimizer extension, so an Azure Web job is created. This contains the exact and same optimization algorithms as the extension and enveloped it in a NuGet package.

It’s named as Azure Image Optimizer and works by adding it to an ASP.NET project without any extra steps. When an ASP.NET app gets published to Azure, the NuGet package would add a Web job to the publish output which automatically starts up and supervises image files once it reaches Azure. It leaves no artifacts in the project and doesn’t need any code changes, only add NuGet package and deploy to Azure.

Content delivery network (CDN)

And the advantage of CDNs has been taken to make sure that the blog can be optimized as desired, to adress all the static files like the JavaScript, CSS, and images. You need to use WebEssentials.AspNetCore.CdnTagHelpers Nuget package :

{

“cdn”: {

“url”: “https://myname.azureedge.net”

}

}

Sass, bundling, and minification

Since Sass has been used instead of plain old CSS it had to be compiled. The maker decided to go with a much simpler approach which is LigerShark WebOptimizer.Core and LigerShark.web optimizer.Sass NuGet packages.

With the use of those packages, you get runtime and build time asset pipeline management with almost no code. The only thing required is to register the service and middleware in Startup.cs so:

services.AddWebOptimizer(pipeline =>

{

pipeline.MinifyJsFiles();

pipeline.CompileScssFiles()

.InlineImages();

});

That will automatically compile the Sass files into CSS and minimise the JavaScript files. No additional code or artifacts are needed.

A Checklist

Like any website, this provides the best practices outlined by the Web Developer Checklist which includes many automated tests which run in the browser and a list of highly useful tools in Miniblog’s Technical Features section.

So here we conclude with this discussing the new Miniblog.Core. 

Keep coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRBtech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Why .NET Core and C# Are The Next Programming Languages

It seems that .NET Core is picking up steam fast, and there is expected huge demand for .NET Core and C# developers in the coming year.

DOT_NET_Core_and_C_Are_The_Next_Programming_Languages

According to TIOBE programming index, C# is one of the top 5 programming languages.

6 Things You Should Know About C# and .NET Core

1. Features Of Modern Languages

.NET has changed and improved in a span of 15 years. With .NET Core, even more, things are changed, including the entire ASP.NET stack being completely overhauled. The C# programming language was around for about 15 years and continues to improve over time.

Some top attributes:

Well typed

Huge base class libraries

Asynchronous programming

Garbage collection, auto memory management

LINQ

Generics

Share binaries over several platforms and frameworks

Easy to use frameworks to design MVC web apps and RESTful APIs

2. Easy to Learn

If you have done C, Java, or even javascript, the syntax of C# will look familiar to you. The syntax is simple and readable.

There are also many online resources to help you learn C#. Most of them are free and there are a few with low cost.

3. Versatility

The best thing about C# and .NET is that it is versatile. You can program desktop apps, background services, web applications, and also mobile apps owing to Xamarin. Besides C#, you have to know little JavaScript to hack the UI code together.

4. .NET Core is Open Source

One of the biggest changes to occur in .NET history is the open sourcing of the code. All the codes could be found on GitHub for anyone to review and contribute. A big change that most people in the IT industry never thought could happen.

You might not have contributes to the source code, but you can benefit from the huge community there. Problems and solutions are fast discussed, coded, and released on a regular basis.

5. Awesome Developer Tools

Visual Studio is regarded as one of the best IDEs for developers. Being a good code editor and supports features like debugging, code completion, profiling, unit testing, and lots more. VS currently offers a full-featured free Community edition.

There is also the possibility of writing code for .NET Core as basic text files with your favorite text editor. You can use VS Code on any OS as a great basic code editor.

The whole .NET ecosystem is filled with amazing developer tools.

6. Standardise The Skills

.NET has a good set of base class libraries. The wide array of base classes widely lessens the need for external packages.

Microsoft gives a very good set of patterns and practices for.NET. Most developers make use of standard frameworks, which makes it easy as a developer to move between teams and also understand how things work.

Conclusion

It is great to see what Microsoft, and the community, has done with .NET Core and how it has become the cool new thing.

The problem with several programming languages is that they are good at one use case. Ruby and PHP are good for web applications. Swift or Objective C works for creating iOS or MacOS applications. To write a background service there is python, java, or other languages. Besides C#, JavaScript and Java are the only languages which can be applied to a wide set of use cases.

An amazing thing about C# is the wide versatility which can be used for a wide variety of types of applications. And with .NET Core that works on MacOS and Linux, there is no limit to what you can do.

With this, we conclude. Keep coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

How To Test Logging In ASP.NET Core

In some cases, like analysis of problems in production, logging is really essential. Even you would like to test that your logging really works.

Testing_Logging_In_ASP_DOT_NET_Core

Let’s take the following function:

Public void DoSomething(int input)

{

_logger.LogInformation(“Doing something…”);

try

{

// do something that might result in an exception

var result = 10 / input;

}

catch (Exception ex)

{

// swallow but log the exception

_logger.LogError(ex, “An error occurred doing something.”, input);

}

public void DoSomething(int input)

{

_logger.LogInformation(“Doing something…”);

try

{

// do something that might result in an exception

var result = 10 / input;

}

catch (Exception ex)

{

// swallow but log the exception

_logger.LogError(ex, “An error occurred doing something.”, input);

}

}

We can assume that with an occurrence of this exception, it’s costing the company good amount of money. Hence it is good to know about it to solve a problem. From a developer’s point of view, the LogError method has the business Importance. And to be sure about it’s working right, there must be automated tests.

Now, consider how to test this code when the _logger case in question is an ASP.NET Core ILogger<T> type, input like as it is:

public class SomeService

{

private readonly ILogger<SomeService> _logger;

public SomeService(ILogger<SomeService> logger)

{

_logger = logger;

}

// methods

}

public class SomeService

{

private readonly ILogger<SomeService> _logger;

public SomeService(ILogger<SomeService> logger)

{

_logger = logger;

}

// methods

}

Now the question is how to test this scenario! You can’t call the method and then observe SomeService’s state to see if it is working. The only way to confirm in a unit test is to pass in your own implementation of ILogger<SomeService> into SomeService, and then find out if this instance was called by the DoSomething method. One way to do this is to use a mocking library like Moq, as shown below:

public void LogsErrorWhenInputIsZero()

{

var mockLogger = new Mock<ILogger<SomeService>>();

var someService = new SomeService(mockLogger.Object);

someService.DoSomething(0);

// Option 1: Try to verify the actual code that was called.

// Doesn’t work.

mockLogger.Verify(l => l.LogError(It.IsAny<Exception>(), It.IsAny<string>(), 0));

}

public void LogsErrorWhenInputIsZero()

{

var mockLogger = new Mock<ILogger<SomeService>>();

var someService = new SomeService(mockLogger.Object);

someService.DoSomething(0);

// Option 1: Try to verify the actual code that was called.

// Doesn’t work.

mockLogger.Verify(l => l.LogError(It.IsAny<Exception>(), It.IsAny<string>(), 0));

}

To mention, this approach fails as there is no LogError method on ILogger<T>, which is the LoggerExtension. This is the main reason why unit testing logging is difficult in ASP.NET Core.

A solution to this is to open a code for the logger extensions and find out what non-extension method is finally executed on ILogger. This would lead to a test like this one:

public void LogsErrorWhenInputIsZeroTake2()

{

var mockLogger = new Mock<ILogger<SomeService>>();

var someService = new SomeService(mockLogger.Object);

someService.DoSomething(0);

// Option 2: Look up what instance method the extension method actually calls:

//https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.Abstractions/LoggerExtensions.cs#L342

// Mock the underlying call instead.

// Works but is ugly and brittle

mockLogger.Verify(l => l.Log(LogLevel.Error, 0, It.IsAny<FormattedLogValues>(), It.IsAny<Exception>(),

It.IsAny<Func<object, Exception, string>>()));

}

public void LogsErrorWhenInputIsZeroTake2()

{

var mockLogger = new Mock<ILogger<SomeService>>();

var someService = new SomeService(mockLogger.Object);

someService.DoSomething(0);

// Option 2: Look up what instance method the extension method actually calls:

// https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.Abstractions/LoggerExtensions.cs#L342

// Mock the underlying call instead.

// Works but is ugly and brittle

mockLogger.Verify(l => l.Log(LogLevel.Error, 0, It.IsAny<FormattedLogValues>(), It.IsAny<Exception>(),

It.IsAny<Func<object, Exception, string>>()));

}

But you might have to mock calls that don’t even exist in the method we’re testing.

But every problem has a solution finder. So finally a trouble-shooter solved it by mentioning the need to create own version of ILogger<T> and give it with its own implementation of the method that has to be checked.

As instance methods are used before extensions methods, this would rather override the extension method in the test code. Thus, will appear the implementation:

public void LogsErrorWhenInputIsZeroTake3()

{

var fakeLogger = new FakeLogger();

var someService = new SomeService(fakeLogger);

someService.DoSomething(0);

// Option 3: Create your own instance of ILogger<T> that has a non-extension version of the method

// Doesn’t work, unless you change system under test to take in a FakeLogger (which is useless)

Assert.NotNull(FakeLogger.ProvidedException);

Assert.NotNull(FakeLogger.ProvidedMessage);

}

private class FakeLogger : ILogger<SomeService>

{

public static Exception ProvidedException { get; set; }

public static string ProvidedMessage { get; set; }

public static object[] ProvidedArgs { get; set; }

public IDisposable BeginScope<TState>(TState state)

{

return null;

}

public bool IsEnabled(LogLevel logLevel)

{

return true;

}

public void Log<TState>(LogLevel, EventId, TState state, Exception, Func<TState, Exception, string> formatter)

{

}

public void LogError(Exception ex, string message, params object[] args)

{

ProvidedException = ex;

ProvidedMessage = message;

ProvidedArgs = args;

}

}

public void LogsErrorWhenInputIsZeroTake3()

{

var fakeLogger = new FakeLogger();

var someService = new SomeService(fakeLogger);

someService.DoSomething(0);

// Option 3: Create your own instance of ILogger<T> that has a non-extension version of the method

// Doesn’t work, unless you change system under test to take in a FakeLogger (which is useless)

Assert.NotNull(FakeLogger.ProvidedException);

Assert.NotNull(FakeLogger.ProvidedMessage);

}

private class FakeLogger : ILogger<SomeService>

{

public static Exception ProvidedException { get; set; }

public static string ProvidedMessage { get; set; }

public static object[] ProvidedArgs { get; set; }

public IDisposable BeginScope<TState>(TState state)

{

return null;

}

public bool IsEnabled(LogLevel logLevel)

{

return true;

}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception, Func<TState, Exception, string> formatter)

{

}

public void LogError(Exception ex, string message, params object[] args)

{

ProvidedException = ex;

ProvidedMessage = message;

ProvidedArgs = args;

}

}

Even now you could assume that DoSomething is still calling the method LogError on ILogger<T>, Yet the extension method will be used because ILogger<T> doesn’t have an instance method that it could match. The only solution is to change the SomeService method to accept a FakeLogger, instead of an ILogger<T>, but even that doesn’t come as a real solution.

So what could be done?

The actual problem is we are dependent on types which are outside our control, and the types are using static methods which can’t be decoupled in tests. To attain loose coupling in our applications, we have to bring together dependencies on specific implementations by working with interfaces that can be controlled. This is a segment of the Interface Segregation Principle (ISP).

Now, some developers will counter because it’s not an implementation and even its part of the framework that we depend upon. But to accept the fact that, ILogger<T> isn’t an implementation, it’s only a use of extension methods and makes testing difficult. The best way to address the problem is with the use of an adapter.

You can start with the minimal interface which your client code needs. You don’t need to create one adapter for all but with every variation of method found on LoggerExtensions. Most applications won’t need all of them, so include the ones you require.

public interface ILoggerAdapter<T>

{

// add just the logger methods your app uses

void LogInformation(string message);

void LogError(Exception ex, string message, params object[] args);

}

public interface ILoggerAdapter<T>

{

// add just the logger methods your app uses

void LogInformation(string message);

void LogError(Exception ex, string message, params object[] args);

}

You can implement the adapter easily by passing in the implementation type it’s using. In this case, the ILogger<T> type and its extension methods:

public class LoggerAdapter<T> : ILoggerAdapter<T>

{

private readonly ILogger<T> _logger;

public LoggerAdapter(ILogger<T> logger)

{

_logger = logger;

}

public void LogError(Exception ex, string message, params object[] args)

{

_logger.LogError(ex, message, args);

}

public void LogInformation(string message)

{

_logger.LogInformation(message);

}

}

public class LoggerAdapter<T> : ILoggerAdapter<T>

{

private readonly ILogger<T> _logger;

public LoggerAdapter(ILogger<T> logger)

{

_logger = logger;

}

public void LogError(Exception ex, string message, params object[] args)

{

_logger.LogError(ex, message, args);

}

public void LogInformation(string message)

{

_logger.LogInformation(message);

}

}

At this point, you refract your service to remove the ILogger<T> dependency and instead use an ILoggerAdapter<T>. And next writing a text to verify that the error is logged properly becomes easy:

public void LogsErrorWhenInputIsZero()

{

var mockLogger = new Mock<ILoggerAdapter<SomeOtherService>>();

var someOtherService = new SomeOtherService(mockLogger.Object);

someOtherService.DoSomething(0);

mockLogger.Verify(l => l.LogError(It.IsAny<Exception>(), It.IsAny<string>(), 0));

}

public void LogsErrorWhenInputIsZero()

{

var mockLogger = new Mock<ILoggerAdapter<SomeOtherService>>();

var someOtherService = new SomeOtherService(mockLogger.Object);

someOtherService.DoSomething(0);

mockLogger.Verify(l => l.LogError(It.IsAny<Exception>(), It.IsAny<string>(), 0));

}

With this we conclude.

Keep coding!

If you want to enhance yourself in Dot Net and improve yourself through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We offer a well-structured program for the best Dot Net Course.

Stay connected to CRB Tech for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Key Things You Must Know About ASP.NET CORE

ASP.NET core has many benefits like lightweight, able to use Gulp, Bower, and Yeoman, can be developed using a number of text editors like VS Code, Atom, Sublime Text, optimized CLR and so on.

Key Things You Must Know About ASP.NET CORE

Here we discuss a few main benefits :

Benefits of .NET Core -

Independent Platform

This helps them overcome the problems faced by developers while deploying a Linux machine or a Mac machine. The application can be deployed on any OS – windows, mac or Linux. The web server on which the application is hosted is Kestrel.. This server helps the developers to save and refresh to get updates than to compile and debug. To make the developers use any OS to develop the asp.net applications, Microsoft has launched the VS Code that has many of the functions offered in VS but is extremely light weight.

Middleware and Dependency Injection

Dependency injection is significant when developing big applications to keep loose coupling between classes and to provide separation and concerns and most importantly the ability to unit test easily. ASP.NET Core has input the dependency injection into a framework. Using several third party tools, the unit testing can be done well.

Middlewares changes the way a request and response is served. Middlewares can be stacked one above the other and hence when a middleware forwards the request to the next one on the stack, it sees the request.

OpenSource

Another big initiative by Microsoft is to make the ASP.NET Core open source. Since it is an open source, the developer community is improving and the documentation constantly gets updated such that beginners don’t need to spend time searching where to begin.

Simplified Structure and Single Framework

The structure is simplified with no App_Data and App_Start. The Global.asax is replaced by Startup.cs, where all the middleware components will be registered and the start point of the application.

In earlier versions of ASP.NET, to have both MVC and API, we need two types of projects to accomplish it. In the latest version of ASP.NET Core, there is namespace under which both MVC and Web API classes are kept and this would cause lesser confusion for the developers.

Limitations of .NET Core -

Documentation and Tools

It gets updated frequently and any gaps present are being filled. Yet while trying to develop an application and trying to find the root cause for the exception it is very tricky because of the constant updation in the documentation and in the framework. The solution might not work properly because of the changes in the framework.

When to use .NET Core?

Selecting between ASP.NET Core and ASP.NET framework is a purpose based decision.

ASP.NET Core is used when

You try new features in ASP.

You have developers working on Mac and Linux and also intend to deploy it in Mac and Linux machines.

You desire high-performance applications.

You wish to work with containers like Docker for the deployment of the applications.

ASP.NET is used when

You wish to use support and documentation present on the internet.

You want to create an enterprise application that has all the security loopholes and is a big application which uses existing tools and third party apps that are not ported to ASP.NET Core yet.

Conclusion

The features packed inside ASP.NET Core is quite useful and being an open source and platform independent, it attracts several developers to use it. It is developing fast and quite simple as well.

That’s it for now! Keep coding!!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute would be of great help and support. We offer well structured program for the Best Dot Net Training Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

Stay connected to CRB Tech for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

An Introduction To BenchmarkDotNet

In this blog we shall discuss BenchmarkDotNet into our .Net blog discussion. Being a powerful cross-platform library that helps you to measure the action of your source code with a high level of precision even when you work with very rapid operations. It’s nowadays used by a number of big .NET projects.

An Introduction To BenchmarkDotNet

BenchmarkDotNet

Benchmarking is quite difficult mainly micro benchmarking; you can easily make an error during measurement of performance. BenchmarkDotNet will protect you from the common pitfalls as it does all the dirty work for you: it produces an isolated project per each benchmark method, does several launches of a project, run multiple iterations of the method, and much more. Often, you even mustn’t care about a number of utterances because BenchmarkDotNet chooses it automatically to achieve the requested level of precision.

It’s not that difficult to design an experiment with BenchmarkDotNet, rather quite easy it is. You need to mark your method with the [Benchmark] feature and the benchmark is there ready for you.

Do you wish to run your code on CoreCLR, Mono, and the Full .NET Framework? A few more attributes and the corresponded projects would be generated; the results will be given at the same summary table. In fact, you can compare any environment that you want: you can check performance difference between processor architectures, JIT versions, different sets of GC flags, and much more. You could introduce one or several parameters and check their performance on several inputs at once.

BenchmarkDotNet offers you help to not only run benchmarks but also analyze the results: it produces reports in different formats and renders nice plots. It calculates many statistics, permits you to run tests on state, and compares results of different benchmark methods. Hence it doesn’t burden you with data, by convention; BenchmarkDotNet prints only the really important statistical values depending on your results: it permits you to keep summary small and simple for primary cases but you will get notified about additional important areas for complex cases (you could request any numbers manually via additional attributes).

BenchmarkDotNet doesn’t only blindly run your code; it tries to help you to carry out a qualitative investigation of the working.

This is already a full-featured benchmark library for several kinds of performance research, and several developers use it. But is continuously being developed to actively create, a lot of nice attributes are coming and are in the process.

If you have any idea to add or discuss, you could write us as a comment below.

With this we conclude. Hope the discussion was helpful for you.

Keep coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute would be of great help and support. We offer well structured program for the Best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

Stay connected to CRB Tech for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Defining Custom Logging Messages Using LoggerMessage.Define In ASP.NET Core

To mention, one of the nicest attributes introduced in ASP.NET Core is the universal logging facilities. In this post we shall discuss one of the helper methods in logging library, and how to make use of it inefficiently logging messages in the libraries.

LoggerMessage.Define In ASP.NET Core

Logging Overview

The logging facility is shown as ILogger<T> and ILoggerFactory interfaces, which you can apply into your services using dependency injection to log messages in various ways. For instance, in the following ProductController, a message is logged when the View action is cited.

public class ProductController : Controller

{

private readonly ILogger _logger;

public ProductController(ILoggerFactory loggerFactory)

{

_logger = loggerFactory.CreateLogger<ProductController>();

}

public IActionResult View(int id)

{

_logger.LogDebug(“View Product called with id {Id}”, id);

return View();

}

}

The ILogger could log message at several levels given by the LogLevel:

public enum LogLevel

{

Trace = 0,

Debug = 1,

Information = 2,

Warning = 3,

Error = 4,

Critical = 5,

}

The final reason of the logging infrastructure are logging givers. These are the “sinks” where the logs are written.You could plug in several providers, and write logs on a variety of different locations, for instance the console, to a file, to Serilog etc.

One good thing about the logging infrastructure and the universal use of DI in the ASP.NET Core libraries is that same interfaces and classes are used all over the libraries and also in your application.

How to control logs produced by different categories

When deevlopin a logger with CreateLogger<T>, the type name you write is used to develop a category for the logs. At the application level, you could choose which LogLevels are output for a given category.

For instance, you can mention that by default, Debug or higher level logs are written to the providers, but for logs written by services in the MS namespace, only logs of Warning level or higher are written.

With this method you can control the amount of logging produced by several libraries in your application, enhancing logging levels for only areas which need them.

Logs without filtering

If you notice, you’ll see that most of the logs come from internal components, from classes in MS namespace. It’s nothing but noise. You could filter out Warning logs in the MS namespace, but retain other logs at Debug level:

Logs with filtering

With a default ASP.NET Core 1.X template, you need to change the appsettings.json file, and set loglevels to Warning as appropriate:

{

“Logging”: {

“IncludeScopes”: false,

“LogLevel”: {

“Default”: “Debug”,

“System”: “Warning”,

“Microsoft”: “Warning”

}

}

}

Note: In ASP.NET Core 1.X, filtering is a second thought. Some logging givers, like the Console provider let you mention how to filter. Otherwise, you can apply filters to all the providers at a same time using the WithFilter method.

Developing logging delegates with the LoggerMessage Helper

The LoggerMessage class is present in MS.Extensions.Logging.Abstractions package, and has a number of fixed, generic Define methods that return an Action<> which in turn could be used to create strong-type logging extensions.

The strong-type logging extension methods

In this instance, we are going to log the time that the HomeController.Index action method produces:

public class HomeController : Controller

{

public IActionResult Index()

{

_logger.HomeControllerIndexExecuting(DateTimeOffset.Now);

return View();

}

}

The HomeControllerIndexExecuting approach is a custom extension approach that takes a DateTimeOffset parameter. We can define it as:

internal static class LoggerExtensions

{

private static Action<ILogger, DateTimeOffset, Exception> _homeControllerIndexExecuting;

static LoggerExtensions()

{

_homeControllerIndexExecuting = LoggerMessage.Define<DateTimeOffset>(

logLevel: LogLevel.Debug,

eventId: 1,

formatString: “Executing ‘Index’ action at ‘{StartTime}'”);

}

public static void HomeControllerIndexExecuting(

this ILogger logger, DateTimeOffset executeTime)

{

_homeControllerIndexExecuting(logger, executeTime, null);

}

}

The HomeControllerIndexExecuting approach is an ILogger extension method which cites a fixed Action field on our fixed LoggerExtensions method. The _homeControllerIndexExecuting field is initiated by using the ASP.NET Core LoggerMessage.Define method, by giving a logLevel, an eventId and the formatString to create the log.

That seems like lots of effort. You could only call _logger.LogDebug() directly in the HomeControllerIndexExecuting extension method.

The goal is to improve performance by logging messages for unfiltered categories, without having to elaborately write: if(_logger.IsEnabled(LogLevel.Debug). The answer remains in the LoggerMessage.Define<T> approach.

The LoggerHelper.Define approach

The purpose this method is 3-fold:

Envelop the if statement to permit performant logging

Apply the correct strong-type parameters are passed when message is logged

Make sure that log message has the correct number of placeholders for parameters

Let’s summarise how the method appears:

public static class LoggerMessage

{

public static Action<ILogger, T1, Exception> Define<T1>(

LogLevel logLevel, EventId eventId, string formatString)

{

var formatter = CreateLogValuesFormatter(

formatString, expectedNamedParameterCount: 1);

return (logger, arg1, exception) =>

{

if (logger.IsEnabled(logLevel))

{

logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback);

}

};

}

}

First, this does a check that the given format string, (“Executing ‘Index’ action at ‘{StartTime}'”) has the correct number of parameters named. Next, it gives back an action method with the required number of generic parameters. There are several overloads of the Define method, that takes 0-6 generic parameters, which depends on the number you would require for your custom message log.

We conclude now. Keep coding! 

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We offer well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

Stay connected to CRB Tech for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Exploring CQRS within the Brighter .NET open source project

This article shall discuss the project called “Brighter.” It has been around in .NET space since many years and is in the process of moving to .NET Core for greater portability and performance.

Brighter is nothing but .NET Command Dispatcher, with Command Processor features for QoS and support for Task Queues.

Exploring CQRS within the Brighter .NET open source project

The Brighter project includes many libraries and examples that you could take in to support CQRS architecture styles in .NET. CQRS is the acronym for Command Query Responsibility Segregation. In the words of Martin Fowler ,” At its heart is the notion that you can use a different model to update information than the model you use to read information.” The Query Model studies and the Command Model updates or validates.

Brighter supports the “Distributed Task Queues” with which you could improve performance when you’re making use of a query or integrating with Microservices.

While creating distributed systems, Hello World is not the case of use. But, it is a good example in that it sidelines any business logic and shows you the elemental structure and concepts.

Suppose imagine there’s a command you wish to send. Say a GreetingCommand. A command could be either write or “do this” sort of command.

internal class GreetingCommand : Command

{

public GreetingCommand(string name)

:base(new Guid())

{

Name = name;

}

public string Name { get; private set; }

}

Suppose there is something else will “handle” these commands. This is the DoIt() method. Noweher its mentioned Handle() ourselves. Very much like dependency injection, you don’t need to call Handle() ourselves; the framework will do it that away.

internal class GreetingCommandHandler : RequestHandler<GreetingCommand>

{

[RequestLogging(step: 1, timing: HandlerTiming.Before)]

public override GreetingCommand Handle(GreetingCommand command)

{

Console.WriteLine(“Hello {0}”, command.Name);

return base.Handle(command);

}

}

Next register a factory that takes the handlers for types and returns. In a real system you could use IoC dependency injection for the mapping also.

The Main() has a registry that could be passed into a larger pipeline where you can set policy for processing commands. This pattern might feel familiar with “Builders” and “Handlers.”

private static void Main(string[] args)

{

var registry = new SubscriberRegistry();

registry.Register<GreetingCommand, GreetingCommandHandler>();

var builder = CommandProcessorBuilder.With()

.Handlers(new HandlerConfiguration(

subscriberRegistry: registry,

handlerFactory: new SimpleHandlerFactory()

))

.DefaultPolicy()

.NoTaskQueues()

.RequestContextFactory(new InMemoryRequestContextFactory());

var commandProcessor = builder.Build();

}

Once you have the commandProcessor, you could send commands to it quite easily and the work is completed. To mention, how you make the commands is up to you.

commandProcessor.Send(new GreetingCommand(“HanselCQRS”));

Methods within RequestHandlers has other behaviours associated like, in case of “[RequestLogging] on the Handle() method as shown above.

You could add other things like Validation, Retries, or Circuit Breakers. The fact is that Brighter gives a bunch of handlers that could operate on a Command.

One of the best things about Brighter is that it is prescriptive and not unhandy.

In short, Brighter is supposed to be a library and not a framework, so it is actually lightweight and divided into several packages that permit you to take in only facilities which you need in the project.

We conclude now. Keep coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We offer well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

Stay connected to CRB Tech for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr