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

ASP.NET Core Exception Filters

Leave a Comment

An essential component of any application is exception handling. It guarantees that the program can manage failures with grace and give the user insightful feedback. Exception filters in ASP.NET Core offer an effective method of handling exceptions on a global, per-controller, or per-action basis. The idea of exception filters, their implementation, and the best practices for utilizing them in your applications will all be covered in this article.

Exception filters: what are they?
In ASP.NET Core, an exception filter is a kind of filter that is triggered when an unhandled exception happens while a controller or action is being executed. They enable you to identify exceptions, record them, and provide the client with a personalized response. Exception filters can be used on an action-by-action basis, globally, or at the controller level. 

Why Use Exception Filters?
  1. Centralized Error Handling: Exception filters provide a centralized way to handle exceptions, making your code cleaner and easier to maintain.
  2. Custom Responses: They allow you to return custom error responses, enhancing the user experience.
  3. Logging and Monitoring: Exception filters can be used to log exceptions, which is crucial for monitoring and diagnosing issues in your application.
Implementing Exception Filters

To implement an exception filter in ASP.NET Core, you need to create a class that implements the IExceptionFilter or IAsyncExceptionFilter interface. Here's an example of a simple exception filter.

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
public class CustomExceptionFilter : IExceptionFilter
{
    private readonly ILogger<CustomExceptionFilter> _logger;

    public CustomExceptionFilter(ILogger<CustomExceptionFilter> logger)
    {
        _logger = logger;
    }

    public void OnException(ExceptionContext context)
    {
        _logger.LogError(context.Exception, "An unhandled exception occurred.");

        context.Result = new ObjectResult(new
        {
            Error = "An error occurred while processing your request. Please try again later."
        })
        {
            StatusCode = 500
        };

        context.ExceptionHandled = true;
    }
}
Registering Exception Filters

Exception filters can be registered globally, at the controller level, or the action level.

Global Registration

To register an exception filter globally, add it to the MvcOptions in the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =>
    {
        options.Filters.Add<CustomExceptionFilter>();
    });
}
Controller-Level Registration

To apply an exception filter to a specific controller, use the [ServiceFilter] or [TypeFilter] attribute.

[ServiceFilter(typeof(CustomExceptionFilter))]
public class SampleController : ControllerBase
{
    // Controller actions
}
Action-Level Registration

To apply an exception filter to a specific action, use the same [ServiceFilter] or [TypeFilter] attribute at the action level.

public class SampleController : ControllerBase
{
    [ServiceFilter(typeof(CustomExceptionFilter))]
    public IActionResult SampleAction()
    {
        // Action logic
    }
}
Best Practices for Using Exception Filters
  1. Keep Exception Filters Simple: Exception filters should be lightweight and focus on handling exceptions. Avoid adding complex logic.
  2. Use Dependency Injection: Leverage dependency injection to inject dependencies like loggers or services into your exception filters.
  3. Log Exceptions: Always log exceptions to help with monitoring and debugging.
  4. Provide Meaningful Responses: Return user-friendly error messages without exposing sensitive information.
Conclusion

Exception filters in ASP.NET Core provide a robust mechanism for handling exceptions in a centralized manner. They enhance the maintainability of your code, improve user experience by providing custom error responses, and facilitate logging for better monitoring and diagnostics. By following the best practices outlined in this article, you can effectively utilize exception filters to handle exceptions in your ASP.NET Core applications.

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

Choosing the Best DotNetNuke 9.13.3 Hosting in Europe

Leave a Comment
Based on its useful features and easy to use, many developer need powerful web hosting to support their DotNetNuke 9.13.3 site well. Because of that, we will inform you the Best DotNetNuke 9.13.3 Hosting in Europe provider with affordable price and high quality support. After reviewed 20+ DotNetNuke 9.13.3 Hosting in Europe, we had come out with the best DotNetNuke 9.13.3 Hosting in Europe, control libraries, databases, technical support, and web hosting price.


DNN (formerly DotNetNuke) is a web content management system based on Microsoft .NET. The DNN Platform Edition is open source.DNN is written in C#, though it existed for many years as a VB.NET project. It is distributed under both a Community Edition MIT license and commercial proprietary licenses as DNN Evoq Content and DNN Evoq Engage editions. DotNetNuke is an open source web application framework ideal for creating, deploying and managing interactive web, intranet and extranet sites. The combination of an enterprise portal, built-in content management system, elegant skinning engine, and the ability to display static and dynamic content makes DotNetNuke an essential tool for ASP.NET developers.

Best & Cheap DotNetNuke 9.13.3 Hosting in Europe

Our Best, Cheap DotNetNuke 9.13.3 Hosting in Europe Recommendation goes to HostForLIFEASP.NET, a leading web hosts who is well-known for offering high quality Windows hosting from shared hosting. HostForLIFEASP.NET founded in United Kingdom, and with years’ expansion, HostForLIFEASP.NET has grown into one of top 10 DotNetNuke 9.13.3 Hosting in Europe hosting providers for offers reliable and affordable web hosting services on Windows platforms. HostForLIFEASP.NET a worldwide provider of hosting support the latest release of Microsoft's widely-used DotNetNuke 9.13.3 Hosting in Europe. You can take advantage of the powerful DotNetNuke 9.13.3 Hosting in Europe technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages.

Is Price Affordable ?

HostForLIFEASP.NET Budget Friendly Price – The service includes 4 packages called as HostForLIFE Basic, Budget, Economy and Business with the price starting at Є3.49/mo and now, with 15% OFF you can get only Є3.49/month.
http://hostforlifeasp.net/


  • 30 Days Money Back Guarantee – This means webmasters are allowed to get a refund if they cancel the services because of dissatisfaction within the first 30 days.
  • Satisfactory Uptime – HostForLIFEASP.NET employs state-of-the-art data centers and advanced technologies guaranteeing 99.99% uptime shown by the following chart. 
 

HostForLIFE DotNetNuke 9.13.3 Hosting in Europe Performance

HostForLIFEASP.NET DotNetNuke 9.13.3 web host reliability is absolutely outstanding compared to other comprehensive web hosting companies. HostForLIFEASP.NET is managed by a sophisticated team with lots of Windows server experts. With the correct IIS, website and file system permission configuration, the security of the hosting websites is well isolated. That means, when one website is hacked by improper code, it’s rare opportunity for other websites be affected.

Technical Support

As introduced above, HostForLIFEASP.NET has an experienced team on supporting ASP.NET and DotNetNuke 9.13.3 Hosting in Europe. All of their technical support staffs are kindly, sophisticated and knowledgeable on either Windows platform or SQL Server 2014 databases. HostForLIFEASP.NET provides 24/7 email and ticket system support mainly. Based on our testing, the average of the first response is about 30 minutes, and it could be faster in working time. HostForLIFEASP.NET guarantees to respond each support ticket in 12 hours.

Conclusion – HostForLIFE is Best Option for DotNetNuke 9.13.3 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your DotNetNuke 9.13.3 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest DotNetNuke via their Plesk control panel. We would highly recommend them as your DotNetNuke 9.13.3 Hosting in Europe.
http://hostforlifeasp.net/
Read More

ASP.NET Tutorial : Lazy Initialization in C# .NET

Leave a Comment

Efficiency is a need in the field of software development, not just a desirable end state. Introducing lazy initialization, a potent C#.NET design pattern that enables programmers to postpone resource-intensive tasks until they are absolutely necessary. This approach reduces memory utilization and improves application speed, so your code will continue to function properly even under high-pressure scenarios. Explore the world of lazy initialization and learn how using it might improve your development procedures.

 

Lazy Initialization: What Is It?
A method known as "lazy initialization" waits to instantiate or compute an object or resource until it is needed or accessed for the first time. In contrast, eager initialization allocates resources in advance regardless of whether they are needed right away. The Lazy<T> class in C#.NET offers a thread-safe and effective method of postponing object creation, making the implementation of lazy initialization simpler. 

Benefits of Lazy Initialization
  1. Performance Optimization: By postponing the creation of objects until they are accessed, lazy initialization reduces startup time and improves application responsiveness.
  2. Memory Efficiency: Unnecessary memory allocation is avoided, especially for objects or resources that may not be used throughout the application's lifecycle.
  3. Improved Responsiveness: Applications remain more responsive, as heavy computations or resource-intensive tasks are executed only when necessary.
How to implement Lazy initialization in C# .NET?
Let's explore a practical example of implementing lazy initialization using the Lazy<T> class.

using System;
public class ExpensiveResource
{
    public ExpensiveResource()
    {
        Console.WriteLine("ExpensiveResource created.");
    }
    public void DoWork()
    {
        Console.WriteLine("Doing work...");
    }
}
class Program
{
    private static Lazy<ExpensiveResource> _lazyResource = new Lazy<ExpensiveResource>(() => new ExpensiveResource());
    static void Main()
    {
        Console.WriteLine("Program started.");
        // The ExpensiveResource is not created until this line is executed
        _lazyResource.Value.DoWork();
        Console.WriteLine("Program ended.");
    }
}
Output
Program started.
ExpensiveResource created.
Doing work...
Program ended.
Explanation
  • In this example, ExpensiveResource is instantiated lazily using _lazyResource.Value.
  • The ExpensiveResource object is only created when _lazyResource.Value is accessed for the first time, ensuring efficient resource usage.
Thread-Safe Initialization

The Lazy<T> class ensures thread safety by default, making it suitable for use in multithreaded environments. This means that even if multiple threads attempt to access _lazyResource.Value simultaneously, the initialization logic is executed only once.

Here’s an example demonstrating thread-safe lazy initialization.

using System;
using System.Threading;
using System.Threading.Tasks;
public class ExpensiveResource
{
    public ExpensiveResource()
    {
        Console.WriteLine("ExpensiveResource created.");
    }
    public void DoWork()
    {
        Console.WriteLine("Doing work...");
    }
}
class Program
{
    private static Lazy<ExpensiveResource> _lazyResource = new Lazy<ExpensiveResource>(() => new ExpensiveResource(), LazyThreadSafetyMode.ExecutionAndPublication);

    static async Task Main()
    {
        Console.WriteLine("Program started.");
        var tasks = new Task[5];
        for (int i = 0; i < 5; i++)
        {
            tasks[i] = Task.Run(() => _lazyResource.Value.DoWork());
        }
        await Task.WhenAll(tasks);
        Console.WriteLine("Program ended.");
    }
}
Output
Program started.
ExpensiveResource created.
Doing work...
Doing work...
Doing work...
Doing work...
Doing work...
Program ended.
Custom Initialization Logic

You can also provide custom initialization logic using a method or lambda expression:

private static Lazy<ExpensiveResource> _lazyResource = new Lazy<ExpensiveResource>(InitializeResource);
private static ExpensiveResource InitializeResource()
{
    // Custom initialization logic
    return new ExpensiveResource();
}
Practical Applications
  • Database Connections: Delay connecting to a database until the first query is executed.
  • Complex Calculations: Compute results on demand rather than precomputing them all upfront.
  • Resource-Heavy Objects: Instantiate objects only when they are actually needed in the application flow.
Conclusion

In C#.NET, lazy initialization is an effective way to maximize performance, boost memory efficiency, and improve responsiveness of applications. Delaying the creation of objects until they are needed allows developers to create scalable and more effective programs. The efficiency and performance of your codebase can be greatly improved by incorporating lazy initialization, regardless of whether you're developing desktop applications, online services, or mobile apps. In your C#.NET projects, embrace lazy initialization to achieve new heights of responsiveness and efficiency right now.

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

SQL: Formulating Effective Inquiries

Leave a Comment

Relational databases are managed and worked with using Structured Query Language (SQL). Optimizing SQL queries is essential for optimal database performance. Some advice on crafting effective SQL queries is provided in this article.


 Tips

  1. Use Indexes: Indexes improve the speed of data retrieval. Ensure that indexes are created on columns frequently used in WHERE clauses.
  2. Avoid SELECT *: Instead of using SELECT *, specify only the columns you need. This reduces the amount of data transferred.
  3. Use Joins Appropriately: Use the appropriate join type (INNER, LEFT, RIGHT, FULL) based on your needs. Ensure that join conditions are correct to avoid Cartesian products.
  4. Use WHERE Clauses: Filter data as early as possible using WHERE clauses. This reduces the number of rows processed in later stages.
  5. Limit Results: Use the LIMIT clause to restrict the number of rows returned by a query, especially in large datasets.
Conclusion

Following these tips can help you write more efficient SQL queries, leading to better database performance.

SQL Server 2022 Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest SQL Server 2022 Hosting. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2012 R2, SQL Server 2014, ASP.NET 4.5.2, ASP.NET MVC 6.0, 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

ASP.NET Tutorial : Design Driven by Domain

Leave a Comment

Domain-Driven Design (DDD) is a paradigm shift in.NET development that provides a methodical way to create reliable, domain-specific solutions. Let's take a thorough look at each of the fundamental DDD tenets, from creating the domain model to applying key patterns and making use of potent frameworks.

1. Domain, the Center of Your Request

The domain model, where business logic flourishes in pure C# code, is the foundation of DDD. Take a deep dive into defining value objects, entities, and aggregates to create a domain model that captures the core of your business needs.

2. Integrating EF Core, Swagger, Kafka, and Other Tools to Implement Infrastructure
Examine the foundational elements of the infrastructure of your application. Use Entity Framework Core to easily persist data, use Swagger to make your API documentation clear and easy to read, and use Kafka to create event-driven architecture.

3. Managing Business Logic: The Functions of Mediators, AutoMappers, and Handlers

Now enter the world of handlers and mediators, the people who make business logic work. Discover how to use AutoMapper for effective mapping between your domain objects and data transfer objects (DTOs), and how to use MediatR to coordinate instructions and queries. 

4. Crafting APIs with Presenter Pattern in ASP.NET Core
Elevate your API development with the Presenter pattern in ASP.NET Core. Build clean and maintainable API endpoints that present data in the desired format, separating concerns for enhanced scalability and readability.

5. Ensuring Code Quality Testing, Validation, and Best Practices

Maintaining code quality is paramount in DDD applications. Explore the importance of unit testing to validate business rules, implement domain validation techniques for data integrity, and adopt best practices to keep your codebase clean and maintainable.

6. Scaling for Success Strategies for Scalability and Resilience

As your application grows, scalability becomes crucial. Discover strategies for scaling your DDD application, including handling concurrency with Unit of Work patterns, distributing workloads with DI containers, and ensuring resilience in the face of failures.

7. Embracing the DDD Mindset Continuous Learning and Community Engagement
Embrace the DDD mindset of continuous learning and improvement. Engage with the vibrant DDD community, participate in discussions, and stay updated on emerging trends and best practices in domain-driven design.

Ready to Dive into the World of DDD in .NET?

Equip yourself with the knowledge and tools to build scalable, maintainable, and domain-centric applications in C#. Let's unlock the full potential of Domain-Driven Design together and pave the way for a future of innovation and excellence.


 

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

ASP.NET Tutorial : When to Utilize Path and Query String Parameters?

Leave a Comment

The industry standard for developing and using web services is now RESTful APIs. Selecting how to organize the URLs and parameters is a crucial step in the architecture of REST APIs. Path parameters and query string parameters are the two most used methods for passing parameters to APIs. This blog will outline the distinctions between the two approaches, suggest situations in which to apply each, and offer examples to support each.


Parameters for Query Strings
Query String Parameters: What Are They?

Key-value pairs that are added to the end of a URL after a question mark (?) are known as query string parameters. An ampersand (&) is used to separate multiple parameters. They are frequently applied to paginate, sort, and filter data.

Example of Query String Parameters

Here’s a simple example of a query string parameter used to filter results:

GET /api/products?category=electronics&sort=price

In this example.

  • category is a query parameter used to filter products by the electronics category.
  • sort is a query parameter used to sort products by price.

When to use Query String Parameters?

  1. Filtering: When you need to filter a list of items based on certain criteria.
  2. Sorting: When you need to sort a list of items.
  3. Pagination: When you need to paginate through a list of items (e.g., page=2&limit=20).
  4. Optional Parameters: When parameters are optional and may not always be provided.

Example in .NET Core

Here’s an example of how you might handle query string parameters in an ASP.NET Core controller:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts([FromQuery] string category, [FromQuery] string sort)
    {
        // Example logic to filter and sort products
        var products = GetProductsFromDatabase();
        if (!string.IsNullOrEmpty(category))
        {
            products = products.Where(p => p.Category == category).ToList();
        }
        if (!string.IsNullOrEmpty(sort))
        {
            products = sort switch
            {
                "price" => products.OrderBy(p => p.Price).ToList(),
                _ => products
            };
        }
        return Ok(products);
    }
    private List<Product> GetProductsFromDatabase()
    {
        // Placeholder method to get products from a database
        return new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Category = "electronics", Price = 1000 },
            new Product { Id = 2, Name = "Phone", Category = "electronics", Price = 500 },
            // More products...
        };
    }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

Path Parameters

What are Path Parameters?

Path parameters are part of the URL path itself and are used to identify a specific resource. They are embedded directly into the URL and are often used to retrieve, update, or delete a specific resource.

Example of Path Parameters

Here’s an example of a path parameter used to retrieve a specific product by its ID:

GET /api/products/123

In this example.

123 is a path parameter used to specify the ID of the product to retrieve.

When to Use Path Parameters?

  1. Resource Identification: When the parameter is needed to identify a specific resource.
  2. Mandatory Parameters: When the parameter is required to complete the request.

Example in .NET Core

Here’s an example of how you might handle path parameters in an ASP.NET Core controller.

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProductById(int id)
    {
        // Example logic to retrieve a product by ID
        var product = GetProductFromDatabase(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
    private Product GetProductFromDatabase(int id)
    {
        // Placeholder method to get a product from a database
        var products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Category = "electronics", Price = 1000 },
            new Product { Id = 2, Name = "Phone", Category = "electronics", Price = 500 },
            // More products...
        };
        return products.FirstOrDefault(p => p.Id == id);
    }
}

Combining Query String and Path Parameters

It’s often useful to combine both query string and path parameters in a single API. For example, you might use a path parameter to identify a specific resource and query string parameters to filter or sort related data.

Example

Here’s an example of an API that retrieves orders for a specific customer (identified by a path parameter) and supports filtering by order status (using a query string parameter).

GET /api/customers/123/orders?status=shipped

Example in .NET Core

Here’s how you might implement this in an ASP.NET Core controller.

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet("{customerId}/orders")]
    public IActionResult GetCustomerOrders(int customerId, [FromQuery] string status)
    {
        // Example logic to retrieve orders for a specific customer and filter by status
        var orders = GetOrdersFromDatabase(customerId);

        if (!string.IsNullOrEmpty(status))
        {
            orders = orders.Where(o => o.Status == status).ToList();
        }
        return Ok(orders);
    }
    private List<Order> GetOrdersFromDatabase(int customerId)
    {
        // Placeholder method to get orders from a database
        return new List<Order>
        {
            new Order { Id = 1, CustomerId = 123, Status = "shipped", Total = 50.00m },
            new Order { Id = 2, CustomerId = 123, Status = "processing", Total = 100.00m },
            // More orders...
        };
    }
}
public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public string Status { get; set; }
    public decimal Total { get; set; }
}

Conclusion

Understanding when to use query string parameters and path parameters is crucial for designing intuitive and effective REST APIs. Query string parameters are ideal for filtering, sorting, and pagination, while path parameters are used for resource identification. Combining both can provide a flexible and powerful way to interact with your APIs.

By following the guidelines and examples provided in this blog, you can design well-structured REST APIs that are easy to use and maintain.

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

Microsoft Entra ID Application Secret Expiration Notification

Leave a Comment

Microsoft Entra ID is a cloud-based identity and access management service. It offers features like single sign-on (SSO), multifactor authentication, and automated user provisioning to enhance organizational security. 

 

In my last blog, I used Microsoft Graph API to get a Microsoft Entra ID application. Now, we are trying to extend the functionality to get the application expiry date so that we can send the notification to the application owner before it expires. 

Send alert on Microsoft Entra ID application secret expiry

DateTime currentDate = DateTime.Now;
TimeSpan duration = new TimeSpan(7, 0, 0, 0); // 7 days
DateTime resultDate = currentDate.Add(duration);
var result = await _graphServiceClient.Applications.Request().GetAsync();
var appList=new List<Models.Application>();
foreach(var app in result.CurrentPage)
{
      var isToBeExpired= app.PasswordCredentials.Where(e => e.EndDateTime <= resultDate).Count()>0?true:false;
        appList.Add(new Models.Application
        {
            Id = app.Id,
            ApplicationId = app.AppId,
            ApplicationName = app.DisplayName,
            SecretToBeExpired=isToBeExpired,
            Owner = app.Owners.FirstOrDefault().ToString()
        });
    if (isToBeExpired)
    {
        //send email to owner
    }
}

The above function will get the client's secret end date time. It checks for each application's client secret to be expired within 7 days anpreparesre the list; we can add one more function to send an email as a notification to the application owner.

Read More
Previous PostOlder Posts Home