Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

The Importance of Unit Testing in .NET Applications

Leave a Comment

 A crucial component of contemporary software development is unit testing. It focuses on testing distinct program elements (or "units") one at a time to ensure that each one functions as expected. Unit testing is essential for enhancing code quality, reducing errors, and increasing an application's general maintainability in the context of.NET applications.

The importance of unit testing in.NET programs, its benefits, and the proper use of tools like NUnit and MSTest will all be covered in this article. To further elucidate important ideas, we will also include real-world code examples.

What is Unit Testing?

Unit testing refers to testing the smallest units of code (usually individual methods or functions) in isolation from the rest of the system. It makes sure each unit functions as intended in its own way. In the case of .NET, we would do this with the help of xUnit, NUnit, or MSTest frameworks probably.

Why is Unit Testing important?

  1. Early Bug Detection: We're talking about unit tests here; they help catch bugs early. Unit tests focus on test cases of small, isolated code units, making it easier for the developer to locate bugs and resolve them before they become larger issues.
  2. Code Refactoring: Developers need to refactor code from time to time as projects grow. Unit tests provide a safety net that allows developers to confidently modify code and be notified via green/red test results if they break something.
  3. Documentation: Good unit tests act as documentation for the code. They define explicitly the external behavior of each unit of code and thereby help other developers understand and use the code more easily.
  4. Improved Code Quality: Unit testing requires developers to reflect more on their code's design. It promotes better, modular code that is more manageable and extensible.
  5. Faster Development: Having a strong unit testing strategy allows developers to implement changes and roll out new features at a faster pace. Automated tests help maintain the application's integrity even as new modifications are made.

Tools for Unit Testing in .NET

There are multiple tools available for unit testing by .NET developers. Some of the popular frameworks are,

  1. NUnit: NUnit is a popular unit testing framework in .NET. It is simple to use and provides built-in features for assertions and organizing tests.
  2. MSTest: MS Unit test Gen is an extension that generates unit tests for existing code. NET applications.
  3. xUnit: Another widely used testing framework that tends to be preferred for its simplicity and community-driven improvements.

We will be using NUnit for this article.

Example. Simple Calculator Class

Let’s consider a simple calculator class with basic arithmetic operations. We will write unit tests to ensure that the calculator methods behave as expected.

Setting Up NUnit: To get started, you need to install the NUnit and NUnit3TestAdapter packages. You can do this via NuGet or through the .NET CLI.

dotnet add package NUnit
dotnet add package NUnit3TestAdapter
dotnet add package Microsoft.NET.Test.Sdk

Step 1. Implement the Calculator Class.

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }

    public int Multiply(int a, int b)
    {
        return a * b;
    }

    public int Divide(int a, int b)
    {
        if (b == 0)
            throw new ArgumentException("Cannot divide by zero.");

        return a / b;
    }
}

Step 2. Create Unit Tests for the Calculator Class.

using NUnit.Framework;

[TestFixture]
public class CalculatorTests
{
    private Calculator _calculator;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Calculator();
    }

    [Test]
    public void Add_TwoNumbers_ReturnsCorrectSum()
    {
        int result = _calculator.Add(3, 5);
        ClassicAssert.AreEqual(8, result);
    }

    [Test]
    public void Subtract_TwoNumbers_ReturnsCorrectDifference()
    {
        int result = _calculator.Subtract(10, 5);
        ClassicAssert.AreEqual(5, result);
    }

    [Test]
    public void Multiply_TwoNumbers_ReturnsCorrectProduct()
    {
        int result = _calculator.Multiply(3, 5);
        ClassicAssert.AreEqual(15, result);
    }

    [Test]
    public void Divide_TwoNumbers_ReturnsCorrectQuotient()
    {
        int result = _calculator.Divide(10, 2);
        ClassicAssert.AreEqual(5, result);
    }

    [Test]
    public void Divide_ByZero_ThrowsArgumentException()
    {
        ClassicAssert.Throws<ArgumentException>(() => _calculator.Divide(10, 0));
    }
}

Explanation

  • [TestFixture]: This is an attribute used to indicate that the class contains tests and is a test fixture.
  • [SetUp]: This characteristic defines a method that is going to run before each test. In this case, it initializes the Calculator object before each test is run.
  • [Test]: This attribute marks methods as test methods.
  • ClassicAssert.AreEqual(): This is an assertion that checks if the actual result matches the expected result.

We can run the tests using the dotnet test command in the terminal or using an IDE like Visual Studio. The test runner will execute the tests and report any failures or successes.


 Best Practices for Unit Testing in .NET

  • Test One Thing at a Time: A unit test should verify only one behavior or condition. Avoid testing multiple behaviors within a single test.
  • Use Mocks and Stubs: In complex applications, we might need to isolate the unit from dependencies like databases or external services. We can use mocking frameworks like Moq to create mocks and stubs for these dependencies.
  • Write Readable Tests: Tests should be easy to read and understand. Use descriptive names for test methods that clearly state what behavior is being tested.
  • Test Edge Cases: Not only the expected behavior but also edge cases and error conditions (like dividing by zero, null values, etc.) should be tested.
  • Keep Tests Independent: Each unit test should be independent of others, so changes in one test shouldn't affect the results of another.
Conclusion

Unit tests are instrumental in writing software with high quality for any modern .NET application. This extremely valuable practice helps to spot bugs as early as possible, thereby directly impacting the maintainability of long-running software projects. By including unit tests in your development workflow, you create a safety net that allows you to confidently change things, refactor without fear, and guarantee that your application really works the way it should. By keeping your tests clean, explicit, and independent, you can enormously boost the quality and maintainability of your software. Recall that unit tests are not information-heavy but rather light text in terms of volume.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

Read More

Preventing XSS in AJAX Web Apps: Best Practices & Prevention

Leave a Comment

AJAX-based online applications have also grown rapidly with the introduction of online 2.0 architecture. Perceiving AJAX-based web apps as more secure than standard web applications is a major mistake that some firms still make in current modern times. In actuality, there are no unique security features associated with AJAX technology. Like traditional online applications, AJAX-built web apps are equally vulnerable to attack. Cross-Site Scripting in AJAX-based web applications is covered in this article.


AJAX

AJAX is a new technology brought about by the Web 2.0 architecture.It connects to the server asynchronously. It makes use of JavaScript, XML, HTML, and CSS to deal with data objects in web applications using XMLHttpRequest. This means that a web application that uses AJAX can easily update specific parts of a web page without having to refresh the entire page. This AJAX capability has its pros and cons since AJAX carries some of its data objects in plain text to and from the server making it vulnerable to attacks such as XSS and CSRF.

XSS in AJAX

XSS can be used in AJAX to manipulate user data if web applications are deployed without sanitizing input and output data streams that the web application deals with. XSS can easily be used to hijack sessions or user identities. All forms of XSS such as Stored, Reflected, and DOM-based XSS can also be exploited on AJAX-based web applications. Developers should ensure that they encode the data before presenting to safeguard the application from possible attacks.

It is important that developers closely check the entire application for any loopholes where XSS can be exploited especially through user input or output from the server. AJAX functions that fetch data from the server may contain XSS entry points which attackers may use to steal information from the user. A browser can be attacked if the developer uses JavaScript functions such as ‘document. write()’ or ‘eval()' which may result in a DOM-based XSS attack.

Since AJAX-based applications are normally used to provide real-time updates such as RSS feed an application can be exposed to XSS attacks if the developer fetches the data from untrusted Web Service APIs and presents the received data without properly filtering and validating it. AJAX applications are also required to check for special characters such as ‘<, >, /’ to avoid malicious code on user input that goes to make requests to the server.

Prevention
  • Sanitize XMLHttpRequest data before sending it back and ensure that all proper validations and escaping of characters have been properly implemented.
  • Lock invalid requests.
  • Check the application for simultaneous logins to protect users from identity theft.
  • Not to use functions like ‘write()’ or ‘eval()’.
  • Implement Content-Security-Policy to ensure that any XSS attempts are mitigated by allowing data from trusted sources only.
  • Replace special characters such as ?, &, /, < with their HTML and URL equivalents to avoid malicious input from users.
Conclusion

Developers and organizations respectively should take note that AJAX-based applications can also be vulnerable to XSS attacks and take time to sanitize and scan their applications for XSS as well as other common vulnerabilities before deploying them. Perhaps developers should take caution on how the XMLHttpRequests are handled and how data is sanitized and scanned before being presented to avoid common XSS attacks.

Best AJAX Hosting for you Ecommerce Site

After we try HostForLIFE.eu service for 3 months, our site never down and with just one click our AJAX hosting success installed. Their loading speed is so fast and recommended for you who want to get powerful AJAX hosting. 


Read More

An Example of a Modern Feature-Rich Entity Framework using SQLite DB

Leave a Comment

Modern features like C#'s async/await will be employed, along with an entity framework and SQLite database to handle user addition and fetching.Net Core software. Let's install the Entity framework and SQLite Database packages from Manage NuGet Packages and construct a basic.NET Core application in Visual Studio 2022.

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools

Asynchronous methods can help to perform tasks without blocking the running threads. Asynchronous functions generally contain the await expression and Task keyword Task<T> with returns.

Example

static async Task Main(string[] args)
    {
        Console.WriteLine("Fetching data...");
        //
    }
static async Task<string> FetchDataAsync(string url)
    {
        using (HttpClient client = new HttpClient())
        {

            string response = await client.GetStringAsync(url);
            return response;
        }
    }

Create a model Class file for table structure and execute application SQLite DB file will create

Example Model Class

public class ItemContext : DbContext
{
    public ItemContext() { }

    public DbSet<Item> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=Item.db");
    }
}

public class Item
  {

      public int Id { get; set; }
      public string Name { get; set; }
      public decimal Price { get; set; }
  }
public static async Task  ClassDBExample()
{
    using (var db = new ItemContext())
    {
        await db.Database.EnsureCreatedAsync();
        var product = new Item { Name = "PC", Price = 899.99m};
        db.Products.Add(product);
        await db.SaveChangesAsync();
        var products = await db.Products.ToListAsync();
        foreach (var item in products)
        {
            Console.WriteLine($"ID: {item.Id}, Name: {item.Name}, Price: {item.Price}");
        }

        product.Price = 899.99m;
        await db.SaveChangesAsync();

        db.Products.Remove(product);
        await db.SaveChangesAsync();
    }
 }

Output


 

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Best & Cheap Drupal 11.0.4 Hosting in Australia

Leave a Comment
If you're looking for Best, Cheap Drupal 11.0.4 Hosting in Australia, we'll offer you with the answer. Extremely Drupal 11.0.4 is user-friendly - setup requires no programming knowledge and the interface is modern and intuitive. Drupal 11.0.4 offers a one-page checkout process. Drupal 11.0.4 is built-in coupons, sales pricing, up-selling, and cross-selling functionality.


 
Drupal 11.0.4 is a free and open source content management system (CMS). DiscountHosting.com.au is a leading provider of web hosting, now hosting many domain names. Tens of Thousands of Drupal clients depend on DiscountService's reliable hosting environment to keep their Drupal-powered web sites running smoothly.

Best Drupal 11.0.4 Hosting in Australia with Special Price

DiscountService.biz is a line of business under Macrodata Enterprise (ABN: 42 797 697 621), specializes in providing web hosting service to customers in Australia. DiscountService.biz is an excellent Drupal 11.0.4 hosting provider focusing on providing rich-featured and super fast web hosting solutions to all kinds of customers ranging from personal bloggers to enterprises. Now webmasters wonder whether this company is good for Drupal 11.0.4 websites, so our editors conduct a comprehensive review on the company in price, features, usability, uptime, speed and technical support.

http://www.discountservice.biz/Australia-Visual-Studio-2017-Hosting

DiscountService.biz offers a variety of cheap and affordable Australia Windows ASP.NET Shared Hosting Plans to fit any need. No matter whether you’re starting a Blog with WordPress, installing a CMS solution with Drupal, opening a Forum with PHPBB, starting an Online Store with Drupal 11.0.4, or any number ventures beyond those mentioned above, our Windows ASP.NET Web Hosting plans are exactly what you’ve been looking for.

Microsoft presents this award to DiscountService.biz for the ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 5 / ASP.NET Core, ASP.NET MVC 6.0/5.2, Silverlight 5 and Visual Studio Lightswitch. 

DiscountService.biz Drupal 11.0.4 Hosting Review on Feature, Price and Performance

Available at this low price, the Beginner plan comes with sufficient web hosting resources and the latest versions of almost all the widely-used software, such as unlimited 2 GB Disk Space storage, 20GB monthly data transfer, unlimited hosted domains, PHP 5.5, MySQL 5.5, SQL 2008/2012/2014, etc. As a leading small to mid-sized business web hosting provider, they strive to offer the most technologically advanced hosting solutions available to their customers across the world. Security, reliability, and performance are at the core of their hosting operations to ensure each site and/or application hosted on their servers is highly secured and performs at optimum level. Unlike other web hosting companies, they do not overload their servers.
https://discountservice.biz/

All DiscountService.biz servers are equipped with minimum Intel Dual Processor Multi Core, 8 GM RAM and the fastest 1,000 Mbps connection backbone. This is to ensure that all sites hosted on our server has an access to the best performance, reliability and connectivity feature.

DiscountService.biz data center is located at Sydney, NSW. Their data centers are built upon a unique pod design concept, making them functionally independent with distinct and redundant resources, and fully integrated through their revolutionary network architecture. You can have direct control over your system in any data center and full access to all of their back-end services—all fully automated and on demand.

With their fully support on Microsoft Windows and ASP.NET, DiscountService.biz is the best choice to host your Drupal. The following are some of the reasons why you should choose them as your Drupal Hosting provider:
  1. Load balanced They automatically distribute traffic across multiple servers to help prevent sudden, unexpected surges from affecting workload performance.
  2. Monitored 24x7x365 Continuous monitoring enables them to proactively respond to anomalies—like suspicious traffic or attempted spam attacks.
  3. High performance They use high quality hardware and server. Their infrastructure is amongst the fastest in the World. UK data center. 

DiscountService.biz Drupal 11.0.4 Hosting is the Best Hosting in Australia

In short, DiscountService.biz offer Drupal 11.0.4 friendly hosting solutions which are featured rich, fast, reliable, and affordable. Taking these factors into consideration, DiscountService.biz is strongly recommended for people to host their Drupal 11.0.4 site.
Read More

Discover How to Utilize FileSystemWatcher in ASP.NET 9

Leave a Comment

You can track file changes on a disk or local network device with the aid of File System Watcher. Console applications that respond to modifications based on the files that are copied, erased, altered, or generated can use it.

I set up an example to watch PDF files in the OneDrive default user folder. Make a console application with.

dotnet new console --name myConsoleApp

Add the code below to Program.cs, and you will start monitoring the OneDrive folder on Windows machines.

using System;
using System.IO;
using System.Threading;

class Program
{
    static void Main()
    {
        var fw = new FileSystemWatcher
        {
            Filter = "*.pdf",
            Path = Environment.GetEnvironmentVariable("OneDrive") ?? "C:\\",
            IncludeSubdirectories = true,
            EnableRaisingEvents = true
        };

        fw.Changed += MonikerChange;
        fw.Created += MonikerCreated;

        while (true)
        {
            Thread.Sleep(1000);
        }
    }

    static void MonikerChange(object sender, FileSystemEventArgs e)
    {
        // Handle the file change event
        Console.WriteLine($"File changed: {e.FullPath}");
    }

    static void MonikerCreated(object sender, FileSystemEventArgs e)
    {
        // Handle the file created event
        Console.WriteLine($"File created: {e.FullPath}");
    }
}

Inside the events, you can do whatever you need with the files.

static void MonikerCreated(object sender, FileSystemEventArgs e)
{
    // Handle the file created event
    Console.WriteLine($"File created: {e.FullPath}");
}

To prevent the app from starting more than once, create a Mutex to prevent several instances from running at the same time. You need to create a unique name for your application, replacing UniqueApplicationName.

using (var mutex = new Mutex(true, "UniqueApplicationName", out bool createdNew))
{
    if (!createdNew)
    {
        // Application is already running
        return;
    }

    var fw = new FileSystemWatcher
    {
        Filter = "*.pdf",
        Path = Environment.GetEnvironmentVariable("OneDrive") ?? "C:\\",
        IncludeSubdirectories = true,
        EnableRaisingEvents = true
    };

    fw.Changed += MonikerChange;
    fw.Created += MonikerCreated;

    while (true)
    {
        Thread.Sleep(1000);
    }

    static void MonikerChange(object sender, FileSystemEventArgs e)
    {
        // Handle the file change event
        Console.WriteLine($"File changed: {e.FullPath}");
    }

    static void MonikerCreated(object sender, FileSystemEventArgs e)
    {
        // Handle the file created event
        Console.WriteLine($"File created: {e.FullPath}");
    }
}

You can hide the console screen to avoid the use of terminating the application, and add the code below to the top of the Program.cs.

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const bool HIDE = true;

if (HIDE)
{
    var handle = GetConsoleWindow();
    ShowWindow(handle, SW_HIDE);
}
Conclusion

You can create logs or process files that have been modified, created, deleted, or changed; it's up to you and your requirements to monitor file changes on the hard drive.

Use this resource wisely.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

An Explanation of Webgrid and Gridview in ASP.NET Core and.NET Core

Leave a Comment

The idea behind this is to use query string arguments to sort columns and sort order, as well as to pass page numbers. According to the idea, the server will receive the updated URL if you change the query string or URL and assign window.location = modifiedurl. Using JavaScript and JQuery, we change the URL's page numbers and sort its columns.

You can copy the large JavaScript code here to a new JS file and refer to it.

//For paging use below dummy class in <style> tag
<style>
.Paging{}
</style>
<tr>
 <th width="100px" style="background-color: #337ab7; color: #fff; border-color: #2e6da4;">NoSortCol1</th>
 <th width="100px" style="background-color: #337ab7; color: #fff; border-color: #2e6da4;">NoSortCol2</th>
//instead of looping over month, it is up to you how you use sort expressions sent by controller
 @foreach (string month in @ViewBag.ListMonths)
 {
 string sortExp = @"/ReportController/RevActionMethod?PAGE2=1&SORTDIR2=DESC&SORTCOL2=" + month;
 <th width="100px" style="background-color: #337ab7; color: #fff; border-color: #2e6da4;">
 <a style="color:#fff" href="@sortExp">@month</a>
 </th>
 }
 </tr>
//iterate data here.. above is just header
<tr><td colspan="6" class="Paging"></td></tr>
// Here Paging buttons will be inserted in the above <tr> using Paging class
window.onload = function () {
    appendPaging2('@ViewBag.TotalPages');
    // appendSorting2('Q1FY22');
    appendSorting2('@ViewBag.AllColumns');
};

// Here AllColumns is a ';' separated string of all columns.
// They are the same as all sort expressions in the hyperlink.
// There should not be any space in the sort expression.
// These sort expressions are the sort columns that are passed
// to the server each time we click.

Put the below in a separate JavaScript file.

If $.urlParam = function (name) in the below code is not working, put this function code in the named function.

function appendPaging2(totPages) {
    TotalPages = totPages;
    var pageLink = $('.Paging');
    var curPage = $.urlParam("PAGE2");
    if (curPage == '') curPage = 1;

    pageLink.empty();
    pageLink.append();

    var disable5 = "", disableLast = "", disableNext = "";
    var disableDecr5 = "", disablePrev = "", disableFirst = "";

    if (TotalPages < 5) disable5 = "disabled";
    if (curPage == TotalPages) {
        disableLast = "disabled";
        disableNext = "disabled";
        disable5 = "disabled";
    }
    if (curPage == 1) {
        disableDecr5 = "disabled";
        disablePrev = "disabled";
        disableFirst = "disabled";
    }

    pageLink.append('<input type="submit" name="FIRST" onclick="page(event);" style="margin-left:4px;" class="page-link" value="<<"' + disableFirst + ' />');
    pageLink.append('<input type="submit" name="PREV1" onclick="page(event);" style="margin-left:4px;" class="page-link" value="<"' + disablePrev + ' />');
    pageLink.append('<input type="submit" name="PREV5" onclick="page(event);" style="margin-left:4px;" class="page-link" value="<5"' + disableDecr5 + ' />');
    pageLink.append('<input type="submit" name="NEXT5" onclick="page(event);" style="margin-left:4px;" class="page-link" value="5>"' + disable5 + ' />');
    pageLink.append('<input type="submit" name="NEXT1" onclick="page(event);" style="margin-left:4px;" class="page-link" value=">"' + disableNext + ' />');
    pageLink.append('<input type="submit" name="LAST" onclick="page(event);" style="margin-left:4px;" class="page-link" value=">>"' + disableLast + ' />');
    pageLink.append('<input type="submit" class="page-link" style="background-color:#ccc; margin-left:4px;" value="1" disabled />');
    pageLink.append('<input type="submit" class="page-link" style="background-color:#ccc; margin-left:4px;" value="' + TotalPages + '" disabled />');
    pageLink.children().eq(6).val(curPage);
}

function appendSorting2(liColumns) {
    var allColAry = liColumns.split(";");
    for (let i = 0; i < allColAry.length; i++) {
        $('tr > th > a[href*="SORTCOL2=' + allColAry[i].toString().replace(" ", "") + '"]').attr("onclick", 'setSort2(this);');
    }
    var sortCol = $.urlParam("SORTCOL2");
    var sortDir = $.urlParam("SORTDIR2");
    if (sortDir != "") {
        if (sortDir == "DESC") {
            var txt = $('tr > th > a[href*="SORTCOL2=' + sortCol + '"]').attr('href').toString();
            txt = txt.replace("SORTDIR2=DESC", "SORTDIR2=ASC");
            $('tr > th > a[href*="SORTCOL2=' + sortCol + '"]').attr('href', txt);
            $('tr > th > a[href*="SORTCOL2=' + sortCol + '"]').parent().append("▼");
        } else {
            var txt = $('tr > th > a[href*="SORTCOL2=' + sortCol + '"]').attr('href').toString();
            txt = txt.replace("SORTDIR2=ASC", "SORTDIR2=DESC");
            $('tr > th > a[href*="SORTCOL2=' + sortCol + '"]').attr('href', txt);
            $('tr > th > a[href*="SORTCOL2=' + sortCol + '"]').parent().append("▲");
        }
    }
}

function page(event) {
    var txt = window.location.toString();
    switch (event.target.name.toString()) {
        case 'PREV1':
            // Logic for previous page
            break;
        case 'NEXT1':
            // Logic for next page
            break;
        case 'PREV5':
            // Logic for previous 5 pages
            break;
        case 'NEXT5':
            // Logic for next 5 pages
            break;
        case 'LAST':
            // Logic for last page
            break;
        case 'FIRST':
            // Logic for first page
            break;
        default:
            // Default case
    }
}

function setSort2(e) {
    var type = e.text.toString().replace(" ", "").replace("%", "").replace("(", "").replace(")", "");
    var txtHref = $('tr > th > a[href*="SORTCOL2=' + type + '"]').attr('href').toString();
    txtHref = setURLParams(txtHref);
    txtHref = updateQueryStringParameter(txtHref, 'PAGE2', 1);
    $('tr > th > a[href*="SORTCOL2=' + type + '"]').attr('href', txtHref);
}

function setURLParams(txtHref) {
    var urlTxt = window.location.toString();
    var urlAry = urlTxt.split("?");
    if (urlAry.length > 1) {
        urlTxt = urlAry[1];
        const searchParams = new URLSearchParams(urlTxt);
        for (const key of searchParams.keys()) {
            if (key != "SORTCOL2" && key != "SORTDIR2" && key != "PAGE2") {
                var val = $.urlParam(key);
                txtHref = updateQueryStringParameter(txtHref, key, val);
            }
        }
    }
    return txtHref;
}

function updateQueryStringParameter(uri, key, value) {
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
        return uri + separator + key + "=" + value;
    }
}

$.urlParam = function (name) {
    var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.search);
    return results !== null ? results[1] || 0 : false;
};
// we have to use bootstrap and styling of paging is automatically taken care
//add this extra property in bootstrap .page-link
//I copied all styling related to paging in separate file from bootstrap (cut paste)
.page-link {
  float: left;
}
 

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More
Previous PostOlder Posts Home