Tag Archives: .net certification in pune

An Introduction To Cookies and Session Stored In TempData In ASP.NET Core

People who used TempData in ASP.NET MVC, probably knows that by default TempData is stored in a Session state. This means that the web application must have sessions enabled. Now, the ASP.NET Core 2.0 gives two TempData providers; a Cookie based and a Session State-based. This blog shows how to use both of them in an application in ASP.NET Core.

Cookies-and-Session-Stored-In-TempData-In-ASP-Dot-Net-Core

Cookie-based TempData

By default, ASP.NET Core 2.0 makes use of cookies based TempData provider. This means values of TempData are stored in cookies present in the client’s machine. Since TempData gest stored in cookies you don’t require Session state through the session state middleware. Storing TempData in cookies could be useful in following situations:

The data being stored is small in size.

A web application is a part of a web farm and you don’t need sticky sessions.

Since cookie based TempData is used by default you don’t have to do any configuration to use it. Just store and receive the TempData key-value pairs as you do. An example is given here:

public IActionResult Index1()

{

TempData[“message”] = DateTime.Now;

return View();

}

public IActionResult Index2()

{

return View();

}

The above code highlights two actions – Index1 and Index2 – of HomeController. The Index1 () action stores a date-time stamp in a dictionary of TempData with a key name of the message. The Index1 view offers a hyperlink to direct to the Home/Index2. The Index2 () action gives back Index2 view. The Index2 view reads the TempData and shows the message to the user.

Index1 view is given below:

<h1>Index 1</h1>

@if (TempData.Peek(“message”) == null)

{

<h2>TempData has not been set.</h2>

}

else

{

<h2>TempData has been set.</h2>

}

<br />

<a asp-controller=”home” asp-action=”index2″>

Go to Index2

</a>

As shown the Razor code finds out whether the message has been stored in TempData or not. It does by using Peek () method of TempData. Since Peek() issued, the key won’t be removed from the TempData. And a message gets displayed in the browser mentioning the status of the message key.

An anchor tag helper offers a hyperlink which points to the Index2 () action of HomeController.

When user clicks on the hyperlink given by Index1. The value of message is sent out in the browser. Markup of Index2 is given below.

<h1>Index 2</h1>

<h2>@TempData[“message”]</h2>

<br />

<a asp-controller=”home” asp-action=”index1″>

Go to Index1

</a>

Index2 reads the TempData dictionary and yields the date-time stamp value in the browser. A hyperlink permits the user to go back to the Index1.

How to know that the TempData is really using the cookies. You need to run the application with F12 tools and locate the cookies option.

The cookie value is Base64 encoded. Since cookies are being used to store TempData all the limitations of cookie storage apply like browser support, size etc.

Session State based TempData

Let’s see how to use Session State based TempData and not the cookie based.

Session state based TempData

To allow Session state based TempData storage you must enable sessions using middleware and you also have to change the default provider. The following code shows how to do it.

public void ConfigureServices(IServiceCollection

services)

{

services.AddMvc().AddSessionStateTempDataProvider();

services.AddSession();

}

public void Configure(IApplicationBuilder app,

IHostingEnvironment env)

{

app.UseSession();

app.UseMvcWithDefaultRoute();

}

The ConfigureServices() calls out AddSessionStateTempDataProvider() to alter the default TempData provider to SessionStateTempDataProvider. It also summons AddSession() to allow in-memory session state for the application. The Configure() summons UseSession() to use the session state middleware.

The HomeController and its both the actions, Index1() and Index2() remains unchanged. On running the application, you can see that the final outcome will be same as before. But there won’t be any CookieTempDataProvider cookie. Instead, a Session cookie.

Session state based TempData comes handy when the application is using session state for other reasons.

That’s it for now!

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

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

Happy Coding!

Code source: Online 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

Top Web Designing Trends To Watch Out In 2018

From changing web apps to static sites, here we take a look at the trends that developers are expecting to see this year.

Top Web Designing Trends In 2018

From the start of its implementation, the internet is evolving. In its hay days, Mosaic and Netscape Navigator were doing great rounds, and since every New Year brought new ideas, new concepts, and trends, sometimes good, sometimes bad.

Here are the web development trends which are expected to impact globally on the industry in 2018:

Progressive Web Apps

A study showed that mobile apps accounted for 89% of the time spent on our Smartphone. It would be logical that the use of a format which is like a mobile application would be well received by the public.

The progressive web apps are applications which take advantage of the attributes of a browser, with a mobile application interface. This technology has several advantages, like an ability to work offline, virtually no load time, good reliability, and to able receive notifications. They can be designed faster than mobile apps, work for all types of users, and are easier to deploy and maintain.

Chatbots

To remain connected to users is quite essential, be in written or oral conversation software, allows a website to be contacted every day, without continuously maintaining a separate department for customer service. The evolution of chatbots offered new capabilities; they can answer the common questions, redirect users to information or web pages, or also helps in completing a transaction.

Website Notifications

Notifications are the best tools for mobile apps. This kind of communication also works with websites after a user authorizes the notifications. This indulges in greater customer engagement without the added costs of making a mobile app which replaces a website.

User Interfaces in Motion

Interfaces are a major concern for developers since a long time. Even the best designs are useless if the user cannot find what he is looking for. Interfaces help you to use animations or transitions that show certain actions, or important parts.

This technology makes the doorway to a wide range of tailoring, giving a developer several options for designing a very functional and attractive website.

The Release of Flash

Flash has interesting things for websites; it lets developers add animations or other movements. Adobe announced this year that there will no updating or new releases in Flash after 2020. Instead of losing the audience, mainly on the mobile version of a site, you should replace Flash with HTML5, which is rapidly becoming the universal internet format.

One-Page Websites

These sites have a well very long, page. To navigate, simply scroll, or use links to go up and down the page to the desired section.

The biggest advantage is their simplicity. There are no endless menus to explore. And this idea works well on smartphones, where the easiest navigation mode is scrolling. It is an updated solution to simple online requirements, and very inexpensive to develop and host.

Photo Content

A good photo is always significant because this can make things change. Though not a new concept, because since in the age of paper magazines, as well a good photo did matter. But now it is being tried uniquely. A unique photo, with individuality, and also giving sufficient information, will be the success key on the internet in 2018.

Conclusion

Trends are fast changing, as our technologies evolve. These new features can attract and retain customers in a better way. Hence, it’s important to look towards the future for new ideas and inspirations and to stand out from the competition.

With this, we conclude.

If you want to enhance yourself in basics and concepts with Dot Net Course and improve yourself 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 several good 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

An Overview Of Unit Testing With .NET Core

In this blog on.Net Core, we shall discuss unit testing for user interface (UI). It is a topic very common, and we will see how to do it here.

An_Overview_Of_Unit_Testing_With_Dot_NET_Core

Selenium is a software-testing framework, quite portable and for web applications and there is a .NET port of it. Here we shall use the Selenium.WebDriver package, and one or more of the following, for different browsers:

Selenium.Chrome.WebDriver: for Chrome

Selenium.Firefox.WebDriver: for Firefox

Selenium.WebDriver.MicrosoftWebDriver: for IE and Edge

Selenium gives a “minimum” contract that works over all the browsers.

Here let’s discuss some examples of how it works. Let’s start with instantiating a driver:

using (var driver = (IWebDriver) new ChromeDriver(Environment.CurrentDirectory))

{

//…

}

Take note of the Environment.CurrentDirectory parameter; it marks the path where the driver can find a chromedriver.exe file, or geckodriver.exe for Firefox or MicrosoftWebDriver.exe, in case of IE/Edge. These executables get added automatically by the Nuget packages. If you don’t remove the driver, the window will remain open after the unit test finishes. You also have a choice to Quit at any time.

Let’s now navigate to some page:

driver

.Navigate()

.GoToUrl(“http://www.google.com”);

And get some element from its name:

var elm = driver.FindElement(By.Name(“q”));

Besides the name, you can also search by:

Id: By.Id

CSS class: By.ClassName

CSS selector: By.CssSelector

Tag name: By.TagName

Link text: By.LinkText

Partial link text: By.PartialLinkText

XPath: By.XPath

Once an element is found, its properties can be accessed:

var attr = elm.GetAttribute(“class”);

var css = elm.GetCssValue(“display”);

var prop = elm.GetProperty(“enabled”);

Then we can send it text strokes:

elm.SendKeys(“asp.net core”);

Or click on it:

elm.Click();

It is to be known that, page loading could take some time, so, you can configure the default time of waiting, before doing a GoToUrl:

var timeouts = driver.Manage().Timeouts();

timeouts.ImplicitWait = TimeSpan.FromSeconds(1);

timeouts.PageLoad = TimeSpan.FromSeconds(5);

ImplicitWait is only a time that Selenium awaits before searching an element.

If you have to wait for some period of time, like, till some AJAX request is done with, you can do the following:

var waitForElement = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

var logo = waitForElement.Until(ExpectedConditions.ElementIsVisible(By.Id(“hplogo”)));

The condition is passed on to ExpectedConditions could be one of:

AlertIsPresent

ElementExists

ElementIsVisible

ElementSelectionStateToBe

AlertState

ElementToBeSelected

FrameToBeAvailableAndSwitchToIt

InvisibilityOfElementWithText

PresenceOfAllElementsLocatedBy

StalenessOf

TextToBePresentInElementLocated

TextToBePresentInElementValue

TitleContains

TitleIs

UrlContains

UrlMatches

UrlToBe

VisibilityOfAllElementsLocatedBy

You can see, there are several conditions that you can make use of. If the condition is not met and the timer expires, then the value returned is null.This is nice for your unit tests.

With this, we conclude.

Keep coding!

If you want to enhance yourself in basics and concepts with 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 several good institutes of dot net training and placement in Pune, CRBtech 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

Method To Implement ListBox in Asp.Net MVC

Microsoft developed ASP.NET MVC as a web application framework which implements the model–view–controller or more popularly known as MVC pattern. It happens to be open-source software, besides the ASP.NET Web Forms component.

Method_To_Implement_List_Box_in_Asp_Dot_Net_MVC

In this blog, we shall discuss the process of implementing ListBox in asp.net MVC. Here, table “tblCity” is used for the demo.

For this demo, the “City” entity is used that is created using ADO.NET entity framework.

The first step is to generate a ViewModel class. In asp.net MVC, view models are used as techniques to transfer data between the view and the controller. Give a right click on the “Models” folder, and add a class file bearing name=CitiesViewModel.cs. Copy and paste the below mentioned code. This class will be the Model for the view.

public class CitiesViewModel

{

public IEnumerable<string> SelectedCities { get; set; }

public IEnumerable<SelectListItem> Cities { get; set; }

}

Next, right click on the folder called “Controllers” and then add a “HomeController”. Add the below two namespaces in the “HomeController”

Using MVCDemo.Models;

Using System.Text;

Copy and paste the following code.

[HttpGet]

public ActionResult Index()

{

SampleDBContext db = new SampleDBContext();

List<SelectListItem> listSelectListItems = new List<SelectListItem>();

for each (City city in db.Cities)

{

SelectListItem selectList = new SelectListItem()

{

Text = city.Name,

Value = city.ID.ToString(),

Selected = city.IsSelected

};

listSelectListItems.Add(selectList);

}

CitiesViewModel citiesViewModel = new CitiesViewModel()

{

Cities = listSelectListItems

};

return View(citiesViewModel);

}

[HttpPost]

public string Index(IEnumerable<string> selectedCities)

{

if (selectedCities == null)

{

return “No cities selected”;

}

else

{

StringBuilder sb = new StringBuilder();

sb.Append(“You selected – ” + string.Join(“,”, selectedCities));

return sb.ToString();

}

}

Next give a Right click on the method called “Index” action in “HomeController” and choose “Add View” from the context menu. Set

View Name = Index

View Engine = Razor

Then click “Add”.

Copy and paste the below mentioned code in “Index.cshtml”

@model MVCDemo.Models.CitiesViewModel

@{

ViewBag.Title = “Index”;

}

<div style=”font-family:Arial”>

<h2>Index</h2>

@using (Html.BeginForm())

{

@Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new { size = 4 })

<br />

<input type=”submit” value=”Submit” />

}

</div>

To note that, if you want to select multiple items from the list box, you have to hold down the CTRL Key.

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, CRBtech 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

Understanding Of Models In An MVC Application

In this blog topic, we shall discuss the models in an MVC application.

Let’s understand the models with the help of examples. Suppose it’s an effort to retrieve employee information from the tblEmployee table and exhibit it.

asp dot net mvc

To envelope Employee information, Employee model class must be added to the Models folder. How to do this?

Steps:

1. Right click on “Models” folder > Add > Class

2. Write the name for the class as Employee.cs

3. Click “Add”

Copy and paste the following code in Employee.cs class file.

public class Employee

{

public int EmployeeID { get; set; }

public string Name { get; set; }

public string Gender { get;set; }

public string City { get;set; }

}

Next add EmployeeController class to “Controllers” folder.

Steps:

1. Right click the “Controllers” folder > Add > Controller

2. Use EmployeeController as name

3. Click “Add”

It is to use “Employee” model class EmployeeController. Next, copy and paste this “using” statement in “EmployeeController.cs”

using MVCDemo.Models;

An Index () Action method is created, by default in EmployeeController. Change the name of the function to Details(). Develop an instance of Employee class. Next, you can hard code Employee data in this class. Now EmployeeController should appear as shown below.

public ActionResult Details()

{

Employee employee = new Employee()

{

EmployeeId = 101,

Name = “John”,

Gender = “Male”,

City = “London”

};

return View();

}

Then you have to pass employee model object which was created in EmployeeController to the view, such that it can produce the HTML and send to the client. So you need to add a view.

Steps:

1. Right click on Details() action method and choose “Add View” from the context menu

2. Set

a)View Name = Details

b)View Engine = Razor

c)Select “Create strongly typed view” checkbox

d)From the “Model class” drop-down list, select “Employee (MVCDemo.Models)”

3. Next and finally, click “Add”

Here, Details.cshtml must be added to “Employee” folder. Take a note that “Employee” folder is created automatically and added to “Views” folder.

Copy and paste the below code into Details.cshtml file.

@model MVCDemo.Models.Employee

@{

ViewBag.Title = “Employee Details”;

}

<h2>Employee Details</h2>

<table style=”font-family:Arial”>

<tr>

<td>

Employee ID:

</td>

<td>

@Model.EmployeeId

</td>

</tr>

<tr>

<td>

Name:

</td>

<td>

@Model.Name

</td>

</tr>

<tr>

<td>

Gender:

</td>

<td>

@Model.Gender

</td>

</tr>

<tr>

<td>

City:

</td>

<td>

@Model.City

</td>

</tr>

</table>

Now if you try running the project, and if you go to the following URL, you will get a runtime error saying: Object reference is not set to an instance of an object.

http://localhost/MVCDemo/Employee/Details

And the best way to correct this error is pass “Employee” object to the view. The “return” statement in Details() action method has to be modified as given below:

return View(employee);

Done!

Run the application and go to http://localhost/MVCDemo/Employee/Details.

With this, we conclude. Happy 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

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

How C# 7.1 Is Different?

With C#, Microsoft has been always some major releases: with a lot of features up, and less frequent release. They went ahead than routinely, omitting the conventional “.0″ when they talked about C# 6.0!

C# 7.1

In the C# 7.0, they are trying something innovative. Tools like Visual Studio upgrade in a frequent mode and they left no reason why the C# couldn’t also be updated more frequently. Hence this time, they are embracing a notion of “point releases”; minor versions of C# with quite useful but smaller language features and with shorter intervals. This indicates that you don’t need to wait for a long time to make some additional value to ship, but also it becomes easy to align a C# release with the shipping of related features, e.g. in.NET.

It is a fact that upgrading to a newer version of programming language every time could be a hassle in an organization and is not the way for everyone. Visual Studio 2017 allows you to decide whether to take the latest or only to the major (“.0″) versions of C#. You can choose your own rhythm.

The first point release

In August of 2017 Microsoft shipped the first point release of C# and named as C# 7.1, and its main purpose is to get practice with point releases, without too many dependencies on accompanying technology to make things complicated.

C# 7.1 is a small release with just a few and well-chosen new language attributes but in the minor range. It’s supported by VS 2017, starting with Update 15.3.

Let’s take a look! There is a program which uses the three C# 7.1 features that are being covered here, and a number of the recent C# 7.0 ones.

using System.Linq;

using System.Threading;

using System.Threading.Tasks;

using static System.Console;

class Program

{

static async Task Main(string[] args)

{

var results = Enumerable.Range(1, 40)

.Select(input => (input, task: FibonacciAsync(input)))

.ToArray();

for each (var tuple in results)

{

WriteLine($”Fib {tuple.input} = {await tuple.task}”);

}

}

private static Task<int> FibonacciAsync(int n, CancellationToken token = default)

{

return Task.Run(() => Fib(n).curr, token);

(int curr, int prev) Fib(int i)

{

if (i is 0) return (1, 0);

var (c, p) = Fib(i – 1);

return (c + p, c);

}

}

}

view raw

cs7.1-Example.cs hosted with by GitHub

It figures out the first 40 Fibonacci numbers in parallel on the thread pool and prints them out in order.

Here let’s take a look at C# 7.1 features used here.

Async Main

The Main entry point method can return a Task or a Task<int>. And as a result, execution will wait for the returned task to complete, before shutting down the program.

The main purpose is to make the Main method async, which you can do as well:

static async Task Main(string[] args)

This makes you wait for the Main method, which you couldn’t do before.

WriteLine($”Fib {tuple.input} = {await tuple.task}”);

Previously what you need to do was that, first you’d create an async helper method, for instance, MainAsync, with all the logic in. Then you can write this cryptic Main method:

static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();

Now you can asynce the Main method and the compiler would rewrite it for you.

Inferred tuple element names

In lambda expression in the query:

input => (input, task: FibonacciAsync(input))

Only a tuple is created, and give a name, task, for the second element. And a few lines later you are able to say

WriteLine($”Fib {tuple.input} = {await tuple.task}”);

To access the first element with the name tuple.input.

Default literals

With an expected type for a default expression, you can omit the mention of the type, as done for the CancellationToken in the signature of the FibonacciAsync method:

Private static Task<int> FibonacciAsync(int n, CancellationToken token = default)

This prevents a repetition of type names or typing the longer ones which are already given by context.

Microsoft is already working on C# 7.2, and also the features intended for their next major release.

With this, we conclude.

Happy 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

How Can .NET Core 2.0 Act As Saviour When there is Dot NET Core DLL Hell

If you know that .NET came with a promise, about 15 years ago to eliminate DLL hell. It was then a big issue to register COM DLL files. And today with mixing, NET Standard, .NET Core and .NET Framework projects have created a new DLL hell.

Can .NET Core 2.0 Act As Saviour When there is Dot NET Core DLL Hell

Here let’s discuss a DLL hell problem.

Suppose there is a simple NetStandard library with some simple classes in it that are used by an ASP.NET Core MVC app and a .NET Framework console application.

There is also System.IO 4.3.0, the latest version.

Other Class Library

In a console app, there is a bunch of classes and business logic. And it is kept in a separate class library. This .NET Framework library also references the CoreLibrary project which is.NETStandard 1.5. And the problem starts, where there are several wonderful messages like this for basic system DLLs.

2> Consider app.config to remap of assembly “System.IO, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” from Version “4.1.1.0” [] to Version “4.1.2.0” [C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\\net461\ref\System.IO.dll] to solve conflict and get rid of warning.

2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2099,5): warning MSB3836: The explicit binding redirect on “System.IO, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” conflicts with an auto-generated binding re-direct. You need to remove it from the application configuration file or disable autogenerated binding redirects. The build will replace it with: “<bindingRedirect oldVersion=”0.0.0.0-4.1.2.0″ newVersion=”4.1.2.0″ xmlns=”urn: schemas-Microsoft-com:asm.v1″ />”.

DLL Version Hell

The .NETStandard class library uses System.IO 4.3.0, and so also the Framework class library.

<Reference Include=”System.IO, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL”>

<HintPath>..\packages\System.IO.4.3.0\lib\net462\System.IO.dll</HintPath>

</Reference>

Then… why the DLL hell there are errors about 4.1.1 and 4.1.2?

It could be that the System.IO 4.3.0 package has different version DLLs in it? You need to recheck. And on looking into the System.IO.dll that gets copied to the bin folder after a build… it says 4.6.24705.1, just like the one in “..\packages\System.IO.4.3.0\lib\net462\System.IO.dll”.

And this is a real cruel deal. Who’s on first? What’s on second?

Why there are 4 Versions of the Same DLL/Package?

Let’s recap; there were versions 4.1.1, 4.1.2, 4.3.0, and 4.6.24705.1. Except, the only one which is actually seen is v4.6 stuck in a v4.3 folder. But why it shows 4.1.1 and 4.1.2 build errors.

Does it make any sense?

Why the .NET team has a v4.6 dll in a v4.3 NuGet package which is really v4.1.1.

It could be the effect of mixing.NETStandard and .NET Framework projects together are the problem.

How .NET Core 2.0 helps?

With the emergence of .NET Core 2.0, you need to switch all the projects. Initially, you were made to use full .NET Framework due to a few NuGet packages that were unavailable for NetStandard.

The false support for .NET Framework packages from a .NET Core application seems an easy solution.

Summary

With different projects that reference each other with conflicts in dependencies, it becomes complicated. The complexity of working with.NET Framework, netcoreapp, and.NETStandard all together is really complicated.

We can hope that .NET Core 2.0 solves the current set of issues.

With this, we conclude. This blog is an adaptation of a blog in Stackify. 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 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

New SPA Templates With ASP.NET Core 2

With the introduction of ASP.NET Core 2 Preview 2, now there are new web application templates present for Single Page Applications or SPA. Presently Angular, React.js, and React.js + Redux are supported. The intention of this blog post is to provide a short overview of the new templates and related applications as a sample.

New SPA Templates With ASP DOT NET Core 2

New SPA templates

While creating new ASP.NET Core application using Visual Studio 2017 Preview 3 there are three new templates for SPA.

The three templates actually create the same sample application but where they differ is in the JavaScript libraries. To mention, these new templates are found only when ASP.NET Core 2 is selected from framework dropdown list on top of the dialog.

TypeScript and webpack

SPA-s have ClientApp folder where JavaScript framework components are kept.

Another new aspect is a support for webpack module bundler. Webpack is added to the project as Node.js module. It is irrelevant as Task Runner. Webpack is run as a part of the build. It takes care of bundling and minimisation as well.

Webpack publishes bundled and minimised files to wwwroot\dist folder when the application is built. JavaScript libraries are piled to file wwwroot\dist\vendor.js and styles that come with these libraries are packet to wwwroot\dist\vendor.css file. Both files are minimised automatically as well.

webpack.config.js is a configuration file for webpack where all piling and minimising rules are defined. You can also add your own rules there.

Sample application

Let’s consider a SPA sample application which demonstrates simple counter and weather forecast page. The counter page uses JavaScript and forecast page uses server call to get weather forecasts. There is SampleDataController where sample data is produced.

Conclusion

The new SPA templates are very simple but potential as most of the work including scripts and adding components is done and to start building your own application become quite easy. Developers coding SPA-s on ASP.NET Core must know well the webpack as it is also one of most popular packing tools in JavaScript world.

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 Training Course.

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