Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, July 8, 2021

Task.Yield

 You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously. If there is a current synchronization context (SynchronizationContext object), this will post the remainder of the method's execution back to that context. However, the context will decide how to prioritize this work relative to other work that may be pending. The synchronization context that is present on a UI thread in most UI environments will often prioritize work posted to the context higher than input and rendering work. For this reason, do not rely on await Task.Yield(); to keep a UI responsive.


This can also be useful if you make an asynchronous method that requires some "long running" initialization, ie:

 private async void button_Click(object sender, EventArgs e)
 {
      await Task.Yield(); // Make us async right away

      var data = ExecuteFooOnUIThread(); // This will run on the UI thread at some point later

      await UseDataAsync(data);
 }

Without the Task.Yield() call, the method will execute synchronously all the way up to the first call to await.

Thursday, June 17, 2021

TIUConsulting

  1. What does include function of Linq do

Ans : https://interview-preparation-for-you.blogspot.com/2021/06/when-to-use-include-with-entity.html

  2.  How to write left join in linq query

      Ans using defualtIfEmpty function

var q =
    from c in categories
    join p in products on c.Category equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };

  3. What we will do in ngAfterViewInit

Ans : https://interview-preparation-for-you.blogspot.com/2021/06/ngafterviewinit.html

  4. What we will do in ngDoCheck

  5. Delete duplicate row except one

Delete from Employee m1 , Employee m2 where m1.Name=m2.Name and m1.CreatedDate<m2.CreateDate

Monday, June 7, 2021

Load Balancer

 Load balancing refers to efficiently distributing incoming network traffic across a group of backend servers, also known as a server farm or server pool.

Modern high‑traffic websites must serve hundreds of thousands, if not millions, of concurrent requests from users or clients and return the correct text, images, video, or application data, all in a fast and reliable manner. To cost‑effectively scale to meet these high volumes, modern computing best practice generally requires adding more servers.

load balancer acts as the “traffic cop” sitting in front of your servers and routing client requests across all servers capable of fulfilling those requests in a manner that maximizes speed and capacity utilization and ensures that no one server is overworked, which could degrade performance. If a single server goes down, the load balancer redirects traffic to the remaining online servers. When a new server is added to the server group, the load balancer automatically starts to send requests to it.

In this manner, a load balancer performs the following functions:

  • Distributes client requests or network load efficiently across multiple servers
  • Ensures high availability and reliability by sending requests only to servers that are online
  • Provides the flexibility to add or subtract servers as demand dictates

How to do unit testing?

 

1. Test One Thing at a Time in Isolation

This is probably the baseline rule to follow when it comes to unit tests. All classes should be tested in isolation. They should not depend on anything other than mocks and stubs.

They shouldn’t depend on the results of other tests. They should be able to run on any machine. You should be able to take your unit test executable and run it on your mother’s computer when it isn’t even connected to the internet.

2. Follow the AAA Rule: Arrange, Act, Assert

When it comes to unit testing, AAA stands for Arrange, Act, Assert. It is a general pattern for writing individual tests to make them more readable and useful.

First, you arrange. In this step, you set things up to be tested. You set variables, fields, and properties to enable the test to be run, as well as define the expected result.

Then you act — that is, you call the method that you are testing.

Finally, you assert— call the testing framework to verify that the result of your “Act” is what was expected. Follow the AAA principle, and your test will be clear and easy to read.

3. Write Simple “Fastball-Down-the-Middle” Tests First

The first tests you write should be the simplest — the happy path. They should be the ones that easily and quickly illustrate the functionality you are trying to write.

If you are writing an addition algorithm, the early tests that you write should make sure that your code can do 2 + 2 = 4. Then, once those tests pass, you should start writing the more complicated tests (as discussed below) that test the edges and boundaries of your code.

4. Test Across Boundaries

Unit tests should test both sides of a given boundary. If you are building some tests for date and time utilities, try testing one second before midnight and one second after. Check across the date value of 0.0.

If you are dealing with a structure that holds a rectangle, then test what happens to points inside and outside the rectangle. What about above or below? To the left or right? Above and to the right? Below and to the left?

Moving across boundaries are places where your code might fail or perform in unpredictable ways.

5. If You Can, Test the Entire Spectrum

If it is practical, test the whole set of possibilities for your functionality. If it involves an enumerated type, test the functionality with every one of the items in the enumeration.

It might be impractical to check every possible string or every integer, but if you can test every possibility, do it.

6. If Possible, Cover Every Code Path

This one is challenging as well, but if your code is designed for testing, and you make use of a code coverage tool, you can ensure that every line of your code is covered by unit tests at least once.

If your language of choice has a code coverage tool, use it in concert with your unit tests. Covering every code path won’t guarantee that there aren’t any bugs, but it surely gives you valuable information about the state of every line of code.

7. Write Tests That Reveal a Bug, Then Fix It

This is a powerful and useful technique. If you find a bug, write a test that reveals it. Then, you can quickly fix the bug by debugging the test.

Then, you have an excellent regression test to make sure that if that bug comes back for any reason, you’ll know right away. It’s easy to fix a bug when you have a simple, straightforward test to run in the debugger.

A side benefit here is that you’ve “tested your test”. Because you’ve seen the test fail and then have seen it pass, you know that the test is valid in that it has proven to work correctly. This makes it an even better regression test.

8. Make Each Test Independent

Tests should never depend on each other. If your tests have to be run in a specific order, then you need to change your tests.

Instead, you should make proper use of the Setup and TearDown features of your unit-testing framework to ensure each test is ready to run individually.

Unit test frameworks don’t guarantee that tests are going to be run in any particular order. If your tests depend on tests running in a specific order, then you may find yourself with some subtle, hard to track down bugs in your tests themselves.

Make sure each test stands alone and you won’t have this problem.

9. Name Your Tests Clearly and Don’t Be Afraid of Long Names

As you are doing one assert per test, each test can end up being very specific. Thus, don’t be hesitant to use a long, complete test name. It is better to have TestDivisionWhenNumPositiveDenomNegative than DivisionTest3.

A long, complete name lets you know immediately which test failed and what exactly what the test was trying to do. Long, clearly named tests also can document your tests.

For example, a test called DivisionByZeroShouldThrowException documents precisely what the code does when you try to divide by zero.

10. Test That Every Raised Exception Is Raised

If your code raises exceptions, then write tests to ensure that every exception you raise gets raised when it is supposed to.

Most xUnit testing frameworks can test for an exception being raised, so you should use that feature to ensure that every exception your code raises is indeed raised under the proper circumstances.

11. Avoid the Use of Assert.IsTrue

Avoid checking for a boolean condition.

For instance, instead of checking if two things are equal with Assert.IsTrue, use Assert.AreEqual instead. Why? Because this:

Assert.IsTrue(Expected = Actual);

Will report something like Some test failed: Expected True, but the actual result was False. That doesn’t tell you anything. Instead, use Assert.AreEqual:

Assert.AreEqual(Expected, Actual)

Which will tell you the actual values involved, such as Some test failed: Expected 7, but the actual result was 3which is much more valuable as an error message.

12. Constantly Run Your Tests

Run your tests while you are writing code. Your tests should run fast, enabling you to run them after even minor changes.

If you can’t run your tests as part of your normal development process, then something is going wrong — unit tests are supposed to run almost instantly. If they aren’t, it’s probably because you aren’t running them in isolation.

13. Run Your Tests as Part of Every Automated Build

Just as you should be running your tests as you develop, they should also be an integral part of your continuous integration process. A failed test should mean that your build is broken.

Don’t let a failing test linger — consider it a build failure and fix it immediately.

Conclusion

Well, there are 13 ways to write useful unit tests. Remember, unless you are writing unit tests, your code will end up hard to maintain and hard to fix. Well-written, thorough unit tests are just a big win all around.


Source : https://betterprogramming.pub/13-tips-for-writing-useful-unit-tests-ca20706b5368

Wednesday, September 4, 2019

Difference between Redirect and RedirectToAction

RedirectToAction lets you construct a redirect url to a specific action/controller in your application, that is, it'll use the route table to generate the correct URL.
Redirect requires that you provide a full URL to redirect to.
If you have an action Index on controller Home with parameter Id:
  1. You can use RedirectToAction("Index", "Home", new { id = 5 }) which will generate the URL for you based on your route table.
  2. You can use Redirect but must construct the URL yourself, so you pass Redirect("/Home/Index/5") or however your route table works.
  3. You can't redirect to google.com (an external URL) using RedirectToAction, you must use Redirect.
RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table.
Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.
Best Practices: Use RedirectToAction for anything dealing with your application actions/controllers. If you use Redirect and provide the URL, you'll need to modify those URLs manually when your route table changes.

https://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

Tuesday, August 20, 2019

Difference Between Dapper and ADO .Net

ADO.NET, for example, won't give you objects (or, at best, will only give you a pseudo object like a DataTable) While Dapper allow to work with classes. Dapper is a wrapper on ADO .net

public class ADONET : ITestSignature
{
    public long GetPlayerByID(int id)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        using(SqlConnection conn = new SqlConnection(Constants.ConnectionString))
        {
            conn.Open();
            using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT Id, FirstName, LastName, DateOfBirth, TeamId FROM Player WHERE Id = @ID", conn))
            {
                adapter.SelectCommand.Parameters.Add(new SqlParameter("@ID", id));
                DataTable table = new DataTable();
                adapter.Fill(table);
            }
        }
        watch.Stop();
        return watch.ElapsedMilliseconds;
    }

}

public class Dapper : ITestSignature
{
    public long GetPlayerByID(int id)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        using (SqlConnection conn = new SqlConnection(Constants.ConnectionString))
        {
            conn.Open();
            var player = conn.Query("SELECT Id, FirstName, LastName, DateOfBirth, TeamId FROM Player WHERE Id = @ID", new{ ID = id});
        }
        watch.Stop();
        return watch.ElapsedMilliseconds;
    }
}

Entityframework vs Dapper






Entity Framework (EF) and Dapper both are object-relational mappers that enable .NET developers to work with relational data using domain-specific objects. Dapper owns the title of King of Micro ORM in terms of performance.

"Micro-ORMs" like Dapper.NET (which is used on the StackExchange family of sites including StackOverflow) which promise performance at the cost of maintainability.
 The major drawback to using Dapper.NET is that you have naked SQL queries in your code.

Entity Framework

Advantages

  • Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer and generate a new database.
  • You can write code against the Entity Framework, and the system will automatically produce objects for you as well as track changes on those objects and simplify the process of updating the database.
  • One common syntax (LINQ) for all object queries whether it is a database or not and pretty fast if used as intended, easy to implement and less coding required to accomplish complex tasks.
  • The EF can replace a large chunk of code you would otherwise have to write and maintain yourself.
  • It provides auto-generated code
  • It reduces development time and cost.
  • It enables developers to visually design models and mapping of database

Disadvantages

  • You have to think in a non-traditional way of handling data, not available for every database.
  • If there is any schema change in database FE won't work and you have to update the schema in solution as well.
  • The EF queries are generated by the provider that we cannot control.
  • It is not good for a huge domain model.
  • Lazy loading is the main drawbacks of EF

Dapper

Advantages

  • Dapper make it easy to correctly parameterize queries
  • It can easily execute queries (scalar, multi-rows, multi-grids, and no-results)
  • Make it easy to turn results into objects
  • It is very efficient and owns the title of King of Micro ORM in terms of performance.

Disadvantages

  • Dapper can't generate a class model for you
  • It cannot generate queries for you
  • It cannot track objects and their changes
  • The raw dapper library doesn't provide CRUD features, but the "contrib" additional package does provide basic CRUD.



Friday, May 24, 2019

Liskove Sustituion

The Liskov Substitution Principle states that any class that is the child of a parent class should be usable in place of its parent without any unexpected behaviour.

If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program
One rule that should be abided by in PHP is that any method should return the same type as that of its parent. For example, if the search method of T returns an instance of Illuminate\\Support\\Collection then any search method of S should also return an Illuminate\\Support\\Collection.

The four conditions for abiding by the Liskov Substitution principle are as follows:

Method signatures must match
Methods must take the same parameters
The preconditions for any method can’t be greater than that of its parent
Any inherited method should not have more conditionals that change the return of that method, such as throwing an Exception
Post conditions must be at least equal to that of its parent
Inherited methods should return the same type as that of its parent
Exception types must match
If a method is designed to return a FileNotFoundException in the event of an error, the same condition in the inherited method must return a FileNotFoundException too
Practical Example(s)
As PHP does not enforce the return type of a method (unless explicitly stated), we must ensure that we adhere to the documentation and return the same types that the parent class or interface define.

As most of the SOLID Principles overlap, one of the best things that you can do to ensure that you follow the Liskov Substitution Principle is code to an interface. Rely on abstractions rather than concretions.

Abiding by the LSP
Below is a basic example of a Repository following the Liskov Substitution Principle:

interface LessonRepositoryInterface
{
/**
* Gets all lessons.
*
* @return array
*/
public function getAll();
}
class FilesystemLessonRepository implements LessonRepositoryInterface
{
public function getAll()
{
// Fetch the lessons from the filesystem
return $files;
}
}
class DatabaseLessonRepository implements LessonRepositoryInterface
{
public function getAll()
{
return Lesson::all()->toArray();
}
}

As you can see from the code above, both classes implement the LessonRepositoryInterface by having a getAll method. While this code would compile normally, we have ensured that the Eloquent Model returns an array of the results so that it follows the documentation correctly.

Conclusion
The Liskov Substitution Principle means that you can inherit from a base class as long as you conform to the standards that it sets, such as having the same method name and parameters, you do not specify any deeper conditions that must be fulfilled, you return the same type that the base method does and that any Execption that is thrown must match the ones thrown by the base method.

Followers

Link