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

User Profile Photos are Missing in the PnP People Webpart

Leave a Comment

 If user profile photos are missing in the PnP People Web Part, here are a few things you can check.

  1. User Profile Service: Ensure that the User Profile Service Application is configured correctly and that user photos are uploaded in SharePoint.
  2. Photo URLs: Verify that the photo URLs are correctly set in the user profiles. You can do this by going to the User Profile Service and checking the users' properties.
  3. Permissions: Check if the web part has the necessary permissions to access user profile data.
  4. Web Part Configuration: Ensure that the PnP People Web Part is configured correctly to display photos. You may need to adjust the settings to enable photo display.
  5. Caching Issues: Sometimes, caching can cause issues. Try clearing your browser cache or checking in an incognito window.
  6. Check for Errors: Look at the console logs in your browser's developer tools for any errors that might indicate what's going wrong.

If you've checked all these and still have issues, then try the below steps.

After these steps, the user photo. The aspx process should initiate the photo sync.

  1. Access SharePoint Admin Center: Open your browser and go to the SharePoint Admin Center. You can usually find this in the Microsoft 365 admin center under “Admin centers” > “SharePoint”.
  2. Navigate to User Profiles
    • In the left-hand navigation pane, select “More features”.
    • Under “User profiles”, click on “Open”.
  3. Manage User Properties: In the User Profiles section, click on “Manage User Properties”.
  4. Locate PictureExchangeSyncState: In the list of user properties, find PictureExchangeSyncState. You can use the search function to locate it quickly.
  5. Edit the Property
    • Click on PictureExchangeSyncState to edit its settings.
    • Change the value from 0 to 1 to enable the photo sync process.
  6. Save Changes: Save the changes to ensure the new configuration is applied.
SharePoint Hosting Recommendation
One of the most important things when choosing a good SharePoint hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable SharePoint, their servers are optimized for PHP web applications such as the latest SharePoint version. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast SharePoint hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE.eu guarantees 99.9% uptime for SharePoint. And the engineers do regular maintenance and monitoring works to assure its SharePoint hosting are security and always up. 

http://hostforlifeasp.net

 

Read More

ASP.NET Tutorial: Building an Application by Combining Several Files

Leave a Comment

To do this, multiple files need to be compiled into a single file creating a single application, providing a Programmer to debug the necessary file, recompile only the modified file, and execute the application. 'C' Provides multiple file compilation to facilitate the generation of a single application.

Solution 1. The 'C' Compiler, cc can be used directly to compile multiple files into a single application. All a programmer has to do is to specify the names of the file one after the other as an argument to cc command and a single executable file will be created.

Example

cc file1.c file2.c file3.c file4.c
C

The above command will independently compile all four files, create an object file, and then link all these object files into a single executable file a.out.

The 'C' Compiler can also be used to compile only the files that were modified and attach them to the executable file. The following example illustrates this

Example

cc file1.c file2.o file3.o file4.o
C

In the above example, only file1.c is compiled and is linked with the other three object code files to make a single executable file a.out.

Solution 2. We can use the #include preprocessor directive to instruct the 'C' compiler, to include the different files in which we have created functions that are to be linked with the master file program.

Consider the following source codes.

/* file1.c - Name of the file */
#include "file2.c"
#include "file3.c"
#include "file4.c"

void main() {
    // Executable portion of main program
    // ........
    // ........

    function1();
    function2();
    function3();
}

void function1() {
    // Executable code
    // ........
}

void function2() {
    // Executable code
    // ........
}

void function3() {
    // Executable code
    // ........
}

To compile the above four files into an application, we'll give the following command.

c cfile1.c. the above command will create a single executable file that will contain all the different functions present in different files.

Code Explanation

#include directive, instruct the 'C' compiler to search for the function(s) in the specified files. The function could be the standards 'C' function or the user design function as used above. The compiler automatically picks up all the files specified after the #include directive, complies with them, and creates a single executive file a.out.

Note. When we use the #include directive to include a file containing functions, the file that contains functions, does not have the main() function. Why....? this is because when the #include directive is used, the functions are treated as part of itself, and since only one main() function is allowed in the 'C' program, the file containing functions does not have the main() function.

Precautions

The file used to be #include directive, having a function name instead of the main() cannot be compiled independently. These can be compiled only with the main function containing the main function.

Summary

Compiling multiple files in C allows a programmer to build a single application by combining code from different source files. Using the C compiler (cc), multiple files can be compiled either by listing all files in a single command or by compiling each file separately into object files and linking them together. This method helps in incremental compilation, where only modified files are recompiled, improving efficiency. Another approach involves using the #include preprocessor directive to include additional source files within a main file. This ensures all functions across files are compiled into a single executable. However, only one file should contain the main() function, and the included files should only define additional functions.

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 Umbraco 14.2.0 Hosting in Europe

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

Umbraco CMS is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco is easy to learn and use, making it perfect for web designers, developers and content creators alike.

Umbraco is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco can be used in its free, open-source format with the additional option of professional tools and support if required.

How to Choose the Best Umbraco 14.2.0 Hosting in Europe?

Our Best, Cheap Umbraco 14.2.0 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 Umbraco 14.2.0 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 Umbraco 14.2.0 Hosting in Europe. You can take advantage of the powerful Umbraco 14.2.0 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.
  • 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 Umbraco 14.2.0 Hosting in Europe Performance

HostForLIFEASP.NET Umbraco 14.2.0 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 Umbraco 14.2.0 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 Umbraco 14.2.0 Hosting in Europe

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

Read More

SharePoint 2013 Tutorial: Introduction to SharePoint and Steps Creating Lists

Leave a Comment

Microsoft SharePoint is an online platform for managing documents and collaborating with others. Organizations use it extensively to communicate, store, manage, and retrieve data safely from nearly any device. SharePoint is an essential part of many organizational contexts because it connects easily with Microsoft 365 (previously Office 365) and other Microsoft products.  

Features

  1. Document Management
    • SharePoint allows for secure storage of documents, making it easy for teams to share, edit, and manage files. It includes features like version control, check-in/check-out, and metadata tagging.
  2. Collaboration
    • SharePoint is designed to improve teamwork by enabling real-time collaboration. Multiple users can co-author documents simultaneously, communicate in the context of the document or project, and share updates easily.
  3. Integration with Microsoft Office and Microsoft 365
    • SharePoint is tightly integrated with Microsoft tools such as Word, Excel, Outlook, and Teams, providing a seamless experience for users. Documents stored in SharePoint can be accessed and edited directly in these applications.
  4. Customization and Development
    • SharePoint is highly customizable. Organizations can create custom workflows, web parts, and apps to extend their functionality. Power users can leverage tools like Power Automate and Power Apps for advanced automation and app development.

There are different types of libraries in SharePoint, each designed for specific use cases.

  1. Document Library: The most common type of library used to store, share, and manage documents such as Word, Excel, PowerPoint, PDFs, and other file types.
  2. Picture Library: Designed for storing images and graphics.
  3. Asset Library: Stores media files like audio, video, and other rich media used throughout the site.
  4. Slide Library: Stores PowerPoint slides to enable easy reuse of individual slides.
  5. Users can upload and download individual slides.

List

A list can contain different columns (fields) that define the types of information stored in each list item. These columns help you structure data in a meaningful way. The different types of information (or column types) that can be added and configured within SharePoint List Settings.

  1. Single Line of Text: A simple text field that allows users to enter a short string of text (up to 255 characters). This is useful for names, titles, or brief descriptions.
  2. Multiple Lines of Text: A field that allows for multiple lines of text, including rich text formatting (such as bold, italics, bullet points). It can store longer entries, such as comments, detailed descriptions, or notes.
  3. Choice (Drop-Down Menu): A predefined set of choices from which users can select one or more options. It can be displayed as a dropdown, radio buttons, or checkboxes. Useful for categories, statuses, or any scenario requiring controlled input.
  4. Number: Stores numeric values. This is useful for data such as quantities, costs, or scores. You can set minimum and maximum values and control decimal places.
  5. Currency: A specialized number field that formats values as currency. You can select the currency format (e.g., USD, EUR) and define decimal precision.
  6. Date and Time: A field for storing dates with an optional time component. You can configure it to store only dates or both dates and times. Useful for due dates, project timelines, or event schedules.
  7. Lookup: A field that pulls information from another list on the same site. You can use it to create relationships between lists. For example, a “Project” list could pull data from a “Clients” list to associate a client with each project.
  8. Yes/No (Checkbox): A Boolean field that allows users to select a simple Yes or No value (represented as a checkbox). This is helpful for toggling status or settings, such as "Is Completed?" or "Approved?"
  9. Person or Group: This field allows users to select people or groups from your organization (based on SharePoint’s user directory). It can be useful for assigning tasks, identifying owners, or noting collaborators.
  10. Hyperlink or Picture: A field that stores URLs, which can either be links to external websites or images. The display format can show as a clickable link or an image preview.
  11. Calculated: A field that generates values based on formulas using other columns in the list. For example, you can calculate the total cost of items in a list by multiplying quantity by price.
  12. External Data: A column that links to data from external sources, such as SQL databases or web services, using Business Connectivity Services (BCS). This is useful when you want to integrate data from outside SharePoint into your list.
  13. Managed Metadata: This field allows users to select terms from a predefined taxonomy set in the Term Store (SharePoint’s managed metadata service). It is ideal for applying consistent tagging or categorization across your site, especially in large organizations.

How to create a List in SharePoint?

  1. Open SharePoint
  2. Click on Create on the left side of the screen.
  3. Click on the “+ Add Column” button in the list view to add different types of columns (e.g., text, number, date, choice, person, etc.).
  4. Configure the column by specifying the column name, data type, and any optional settings such as default values or required fields.



Click on the gear icon and choose List Settings to access more advanced options like versioni
ng, permissions, validation settings, and workflows.

Create custom views to display data in different formats. Click on All Items (default view) > Create a new view, and customize filters, sorting, and grouping to organize list items.

SharePoint Hosting Recommendation
One of the most important things when choosing a good SharePoint hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable SharePoint, their servers are optimized for PHP web applications such as the latest SharePoint version. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast SharePoint hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE.eu guarantees 99.9% uptime for SharePoint. And the engineers do regular maintenance and monitoring works to assure its SharePoint hosting are security and always up. 

http://hostforlifeasp.net

Read More

How to Choose the Best nopCommerce 4.70.5 Hosting in Australia?

Leave a Comment
Choosing the Best nopCommerce 4.70.5 Hosting in Australia, we'll offer you with the answer.  nopCommerce is the best open-source e-commerce shopping cart. nopCommerce is available for free. Today it's the best and most popular ASP.NET ecommerce software. It has been downloaded more than 1.8 million times! nopCommerce is a fully customizable shopping cart. It's stable and highly usable. nopCommerce is an open source ecommerce solution that is ASP.NET (MVC) based with a MS SQL 2008 (or higher) backend database. Our easy-to-use shopping cart solution is uniquely suited for merchants that have outgrown existing systems, and may be hosted with your current web host or our hosting partners. It has everything you need to get started in selling physical and digital goods over the internet.

https://ukwindowshostasp.net/UK-PrestaShop-Web-hosting

How to Choose the Best nopCommerce 4.70.5 Hosting in Australia?

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 nopCommerce 4.70.5 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 nopCommerce 4.70.5 websites, so our editors conduct a comprehensive review on the company in price, features, usability, uptime, speed and technical support.

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 nopCommerce 4.70.5, or any number ventures beyond those mentioned above, our Windows ASP.NET Web Hosting plans are exactly what you’ve been looking for.
 
http://discountservice.biz/Australia-Moodle-1704-Hosting

DiscountService.biz nopCommerce 4.70.5 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.

http://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 their 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.

Support Service for Customers
DiscountService.biz has been committed to providing 24/7 qualified, experienced and patient customer supports via multitudes of supporting ways, like helpdesk, support ticket and email. It is proved that any issue can be handled as soon as possible. Furthermore, nopCommerce 4.70.5 customers can solve their problems by themselves via the guidance of NopCommerceTutorial & Articles, Discussion Board and Blog.

DiscountService.biz nopCommerce 4.70.5 Hosting is the Best Hosting in Australia
In short, DiscountService.biz offer nopCommerce 4.70.5 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 nopCommerce 4.70.5 site.
Read More

A Comprehensive Description of COUNT in SQL Server

Leave a Comment

Counting rows is a frequent task that many SQL developers come into when working with SQL Server. It is essential to comprehend the distinctions between DISTINCT COUNT, COUNT(1), and COUNT(*) when crafting effective and optimized queries. We will delve further into these SQL counting techniques in this post, comprehend their subtleties, and look at performance issues.

COUNT(*)

The COUNT(*) function is used to count all rows in a table or the result set of a query. It includes NULL values and duplicates. This is the most commonly used COUNT function due to its simplicity and broad applicability.

USE [AdventureWorks2022]
GO

SELECT COUNT(*) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
COUNT(1)

The COUNT(1) function operates similarly to COUNT(*) but counts the number of rows by evaluating the constant value 1 for each row. This can sometimes be seen as a trick to improve performance, although in most cases, there is no significant difference.

USE [AdventureWorks2022]
GO

SELECT COUNT(1) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
COUNT(column_name)

The COUNT(column_name) function counts the number of non-NULL values in a specified column. This is useful when you need to count entries in a column while ignoring NULL values.

USE [AdventureWorks2022]
GO

SELECT COUNT(BusinessEntityID) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
COUNT(DISTINCT column_name)

The COUNT(DISTINCT column_name) function counts the number of distinct non-NULL values in a specified column. This is useful for identifying the number of unique entries in a dataset.

USE [AdventureWorks2022]
GO

SELECT COUNT(LoginID) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
SQL

Performance Considerations
 

COUNT(*) COUNT(1) COUNT(column_name) COUNT(DISTINCT column_name)
The COUNT(*) function is efficient because it does not need to evaluate any specific column values. Instead, it counts rows at the storage level. SQL Server optimizes this operation by utilizing the table's metadata, making it faster than counting specific columns, especially when those columns are large or contain complex data types. From a performance perspective, COUNT(1) and COUNT(*) are typically equivalent. The SQL Server optimizer treats them the same way and generates similar execution plans. Therefore, choosing between COUNT(1) and COUNT(*) is mostly a matter of preference or coding standards rather than performance. COUNT(column_name) can be less efficient than COUNT(*) or COUNT(1) because it requires evaluating each value in the specified column to determine if it is NULL. However, if the column is indexed, SQL Server can leverage the index to improve performance. It is important to consider the size and complexity of the column when using this function. COUNT(DISTINCT column_name) can be significantly more resource-intensive than COUNT(*) or COUNT(column_name) because it requires sorting and deduplicating the values in the specified column. The performance impact is more pronounced for large datasets or columns with many distinct values. Using indexes on the column can help, but it may not completely mitigate the overhead.

Use Cases

COUNT(*) COUNT(1) COUNT(column_name) COUNT(DISTINCT column_name)
Counting all rows in a table or result set Similar to COUNT(*), often used interchangeably Counting non-NULL values in a specific column Counting unique non-NULL values in a specific column

Advanced Scenarios

  • Counting with Conditions: Sometimes, you may need to count rows based on specific conditions. This can be achieved using the CASE statement within the COUNT function.
    USE [AdventureWorks2022]
    GO
    
    SELECT
        COUNT(CASE WHEN OrganizationLevel = 1 THEN 1 END) AS VicePresident,
        COUNT(CASE WHEN OrganizationLevel = 2 THEN 1 END) AS EngineeringManager
    FROM [HumanResources].[Employee] WITH(NOLOCK)
  • Combining COUNT with Other Aggregate Functions: You can combine COUNT with other aggregate functions like SUM, AVG, MAX, and MIN to derive more complex insights.
    USE [AdventureWorks2022]
    GO
    
    SELECT
        COUNT(*) AS TotalEmployees,
        AVG(Rate) AS AverageSalary,
        MAX(Rate) AS HighestSalary,
        MIN(Rate) AS LowestSalary
    FROM [HumanResources].[EmployeePayHistory] WITH(NOLOCK)
  • Conclusion

    Understanding the differences between COUNT(*), COUNT(1), COUNT(column_name), and COUNT(DISTINCT column_name) is crucial for SQL developers, data engineers, and DBAs. Each function serves specific purposes and has unique performance characteristics. By selecting the appropriate COUNT function and optimizing your queries, you can efficiently derive insights from your data and ensure optimal performance in SQL Server.

    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: Use of Action Delegate in C# in Detail

    Leave a Comment

    The Action delegate type in C# represents a method that can be called, but as its return type is void, it does not produce a value. It can take in one or more parameters as input.



    Action exists in the System namespace and can be accessed in multiple overloads to support varying numbers of parameters. It's commonly used to create event handlers, callbacks, and functions to pass as arguments.

    Action Syntax
    • No Parameters: An Action can be defined as a method that does not accept any parameters and returns no value.
      Action myAction = () => Console.WriteLine("Hello, World!");
      myAction();  // Output: Hello, World!
    One or More Parameters: It is possible to create an Action that accepts one or more parameters while still returning no value.
    Action<string> greetAction = (name) => Console.WriteLine($"Hello, {name}!");
    greetAction("Alice");  // Output: Hello, Alice!
    
    Action<int, int> addAction = (x, y) => Console.WriteLine(x + y);
    addAction(5, 10);  // Output: 15

    Key Features

    • Absence of Return Value: In contrast to Func<T>, the Action delegate does not yield a return value; it consistently returns void.
    • Capability for Multiple Parameters: Action<T1, T2, ..., T16> allows for the definition of a delegate that can accept as many as 16 parameters.
    • Utilization of Anonymous Methods and Lambda Expressions: Action is frequently employed alongside lambda expressions or anonymous methods, promoting more succinct code.
    • Application in Event Handlers: Action proves beneficial when it is necessary to transfer methods (including parameters), particularly for callbacks or event-handling scenarios.

    Comparison with Func

    • Action<T>: Used when the method returns void and can take zero or more parameters.
    • Func<T, TResult>: Used when the method returns a value (TResult) and can take zero or more input parameters.

    For example

    • Func<int, int, int> could represent a method that takes two integers and returns an integer (like an addition function).
    • Action<int, int> could represent a method that takes two integers and performs an action (like printing the sum), but doesn't return a value.
    The appropriate context for utilizing Action
    1. Action is a delegate type used for methods that don't return values.
    2. It is useful for passing methods as parameters or defining callbacks.
    3. You can use Action for methods with zero to 16 input parameters.
    Examples of different types of Action delegates
    • Action with No Parameters
      Action action = () => Console.WriteLine("Action with no parameters!");
      action();
      // Output: Action with no parameters!
    Action with One Parameter
    Action<string> printMessage = (message) => Console.WriteLine(message);
    printMessage("Hello!");
    
    // Output: Hello!
    Action with Multiple Parameters
    Action<int, int> multiplyNumbers = (a, b) => Console.WriteLine(a * b);
    multiplyNumbers(4, 5);
    
    // Output: 20
    Passing Action as a Parameter to a Method: You can pass an Action as a method parameter to be executed later.
    public void PerformAction(Action action)
    {
        Console.WriteLine("Before action.");
        action();
        Console.WriteLine("After action.");
    }
    // Usage:
    PerformAction(() => Console.WriteLine("Executing action..."));
    // Output:
    // Before action.
    // Executing action...
    // After action
    Using Action with Event Handling
    public class Button
    {
        public Action Click { get; set; }
    
        public void OnClick()
        {
            Click?.Invoke(); // Invoke the Action if it's not null
        }
    }
    Button button = new Button();
    button.Click = () => Console.WriteLine("Button clicked!");
    button.OnClick();
    // Output: Button clicked!
    Execution of all previously mentioned actions within the application

    Step 1. I have developed a WPF user interface, as illustrated below. You may select any application type that aligns with your specific requirements.


    MainWindow.Xaml code

    <Window
        x:Class="ActionDelegateExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ActionDelegateExample"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="450"
        Width="800">
    
        <Grid>
            <StackPanel Orientation="Vertical">
                <Button
                    x:Name="BtnNoParameter"
                    Content="Action with no Parameter"
                    Click="BtnNoParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnWithSingleParameter"
                    Content="Action with single Parameter"
                    Click="BtnWithSingleParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnMultipleParameter"
                    Content="Action with multiple Parameter"
                    Click="BtnMultipleParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnCallbackParameter"
                    Content="Action with call back"
                    Click="BtnCallbackParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnCallEvenHandlingParameter"
                    Content="Action with CallEvenHandling"
                    Click="BtnCallEvenHandlingParameter_Click"
                    Height="40"
                    Margin="20"/>
            </StackPanel>
        </Grid>
    </Window>

    MainWindow.Xaml.cs code

    using System.Windows;
    
    namespace ActionDelegateExample
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                EventHandlerManager.OnEventRaised += EventHandlerManager_OnEventRaised;
            }
            private void EventHandlerManager_OnEventRaised()
            {
                MessageBox.Show("Event handled by Subscriber");
            }
            private void BtnNoParameter_Click(object sender, RoutedEventArgs e)
            {
                ActionMethods.NoParameterActionVariable();
            }
            private void BtnWithSingleParameter_Click(object sender, RoutedEventArgs e)
            {
                // Create a RequestMessage
                RequestMessageWithParameter message = new RequestMessageWithParameter
                {
                    Content = "This is a single parameter request."
                };
                ActionMethods.ActionWithOneParameter(message);
            }
            private void BtnMultipleParameter_Click(object sender, RoutedEventArgs e)
            {
                // Create a RequestMessage
                RequestMessageWithParameter message = new RequestMessageWithParameter
                {
                    Content = "This is a multiple parameter request."
                };
    
                // Invoke the Action with RequestMessage and an integer
                ActionMethods.ActionWithTwoParameters(message, 42);
            }
            private void BtnCallEvenHandlingParameter_Click(object sender, RoutedEventArgs e)
            {
                EventHandlerManager.RaiseOnEventRaised();
            }
            private void BtnCallbackParameter_Click(object sender, RoutedEventArgs e)
            {
                MessageHandler handler = new MessageHandler();
    
                // Define the callback action that will handle the RequestMessage after processing
                Action<RequestMessageWithParameter> callback = (request) =>
                {
                    MessageBox.Show($"Callback executed. Message content: {request.Content}");
                };
                // Call the method with a message and the callback action
                handler.ProcessRequest("Hello, this is a sample request!", callback);
            }
        }
    }

    Step 2. Establish a class titled "ActionMethods.cs" as illustrated below. It has been used to define action delegates

    using System.Windows;
    
    namespace ActionDelegateExample
    {
        public class ActionMethods
        {
            public static Action NoParameterActionVariable = () => NoParameterAction();
            private static void NoParameterAction()
            {
                MessageBox.Show("Action without parameters executed.");
            }
            // Action that accepts one parameter of type RequestMessage
            public static Action<RequestMessageWithParameter> ActionWithOneParameter = (request) =>
            {
                MessageBox.Show(request.Content);
            };
            // Action that accepts two parameters: RequestMessage and an integer
            public static Action<RequestMessageWithParameter, int> ActionWithTwoParameters = (request, count) =>
            {
                MessageBox.Show($"Action with two parameters executed. Message: {request.Content}, Count: {count}");
            };
        }
    }

    Step 3. Create a class named “MessageHandler.cs” as shown below. It will be used to manage an event of action type.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ActionDelegateExample
    {
        public class MessageHandler
        {
            // Method that accepts an Action<RequestMessage> callback
            public void ProcessRequest(string messageContent, Action<RequestMessageWithParameter> callback)
            {
                // Create the RequestMessage
                RequestMessageWithParameter requestMessage = new RequestMessageWithParameter { Content = messageContent };
    
                // Simulate some processing
                Console.WriteLine("Processing the message...");
                System.Threading.Thread.Sleep(10000);
    
                // After processing, invoke the callback with the request message
                callback?.Invoke(requestMessage);
            }
        }
    }

    Step 4. Create a class by the name of ‘EventHandlerManager.cs” to handle the event.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ActionDelegateExample
    {
        public class EventHandlerManager
        {
            public static event Action OnEventRaised;
            // Method to raise the event
            public static void RaiseOnEventRaised()
            {
                Action onEventRaised = OnEventRaised;
                if (onEventRaised != null)
                {
                    onEventRaised();
                }
            }
        }
    }
    A detailed description of the aforementioned code
    • RaiseOnEventRaised(): A static method that triggers the OnEventRaised event.
    • Action onEventRaised = OnEventRaised: Creates a local copy of the event delegate. This is done to avoid the potential issues of the event being null while invoking it.
    • if (onEventRaised != null): Checks if there are any subscribers to the event. If there are, it proceeds to invoke the event.
    • onEventRaised(): Invokes the event. This calls all methods that have subscribed to OnEventRaised.

    Step 6. The results obtained from testing are. 

    Action with No Parameters


    Action with One Parameter


     
    Action with Multiple Parameters


     
    Passing Action as a Parameter to a Method(Callback)


    Using Action with Event Handling

     


    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