Content Developer II at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
121504 stories
·
29 followers

Adding state to the update notification pattern, part 3

1 Share

Last time, we developed a stateful but coalescing update notification, and we noted that the code does a lot of unnecessary work because the worker thread calculates all the matches, even if the work has been superseded by another request.

We can add an optimization to abandon the background work if it notices that its efforts are going to waste: Periodically check whether there is any pending text. This will cost us a mutex, however, to protect access to m_pendingText from multiple threads.

class EditControl
{
    ⟦ ... existing class members ... ⟧

    bool m_busy = false;
    std::mutex m_mutex;
    std::optional<string> m_pendingText;
};
winrt::fire_and_forget
EditControl::TextChanged(std::string text)
{
    auto lifetime = get_strong();

    ExchangePendingText(std::move(text));
    if (std::exchange(m_busy, true)) {
        co_return;
    }

    while (auto pendingText = ExchangePendingText(std::nullopt);
           pendingText) {                                       

        co_await winrt::resume_background();

        auto matches = BuildMatches(*pendingText);

        co_await winrt::resume_foreground(Dispatcher());

        if (matches) {                
            SetAutocomplete(*matches);
        }                             

    }
    m_busy = false;
}

template<typename T = std::optional<std::string>>
std::optional<std::string>
    EditControl::ExchangePendingText(T&& pending)
{
    auto lock = std::unique_lock(m_mutex);
    return std::exchange(m_pendingText, std::forward<T>(pending));
}

std::optional<std::vector<std::string>>
    EditControl::BuildMatches(std::string const& text)
{
    std::vector<std::string> matches;
    for (auto&& candidate : FindCandidates(text)) {
        if (candidate.Verify()) {
            matches.push_back(candidate.Text());
        }
        if (auto lock = std::unique_lock(m_mutex);
            m_pendingText) {                      
            return std::nullopt;                  
        }                                         
    }
    return matches;
}

Last time, I noted that the UI thread is doing a lot of work for us, since it is implicitly ensuring that the updates to m_busy and m_pendingText are atomic.

If our background work doesn’t dispatch back to the UI thread, then we will be responsible for our own locking. We’ll look at that next time.

The post Adding state to the update notification pattern, part 3 appeared first on The Old New Thing.

Read the whole story
alvinashcraft
just a second ago
reply
West Grove, PA
Share this story
Delete

Windows CMD Line - Directory listing and opening in notepad in one line working commands

1 Share

DOS Command Line - Directory Listing and open in notepad in one line

Here are common examples on Stack OverFlow to opening a directory listing into notepad, but they don't work. 

dir > notepad 
dir | notepad 

Here's a fully working way to open directory listing into Notepad. You have to create a file. 

dir > dir.txt && notepad dir.txt

Or create file in temp directory (C:\Users\{Username}\AppData\Local\Temp)

dir > %temp%\dir.txt && notepad %temp%\dir.txt


Hacking

Here's a way to create a file and delete it, but it locks the cmd shell, until notepad executable is closed. In other words, you cannot issue command in the cmd shell, because handle is being used by Notepad. Once closed the > (command prompt) will return. 

dir > %1 | notepad %1 && del %1




You automatically close the calling cmd shell using the exit command. 
 
dir > %1 | notepad %1 && del %1 && exit
Read the whole story
alvinashcraft
20 seconds ago
reply
West Grove, PA
Share this story
Delete

A Guide to Serverless Functions

1 Share

Serverless functions have become a popular application development and deployment approach. By abstracting infrastructure management and embracing event-driven architecture, they offer a flexible solution for developers. The main goal of serverless is to eliminate the need for infrastructure management and promote a specific application-building mindset. 

We’ll touch on what gives serverless computing that capability and also cover working principles, benefits, use cases, implementation techniques, and connection to Function-as-a-Service (FaaS). This guide is ideal for developers, architects, and technology enthusiasts seeking to understand the technology behind serverless functions and the implications of adopting them.

What are Serverless Functions?

Serverless functions are cloud computing functions where developers write and deploy code without managing the underlying infrastructure. In a serverless architecture, the cloud provider provisions, scales, and manages the servers required to run the code.

Serverless functions are event-driven, meaning they’re executed in response to specific events or triggers, such as HTTP requests, database changes, file uploads, or scheduled timers. When an event occurs, the cloud provider automatically provisions the necessary resources to run and execute the code. Once the function completes its task, the resources are released, and you only pay for the actual execution time and resources used.

How Do Serverless Functions Work?

Serverless functions work by following a specific execution flow within a serverless computing environment. Here’s a general overview:

    1. Trigger Event: Serverless functions are event-driven, meaning they’re triggered by specific events or conditions. As discussed earlier, events can be HTTP requests, database changes, file uploads, timers, etc. It depends on the platform and integrations available.
    2. Resource Provisioning: When an event occurs, the serverless platform automatically provisions the necessary resources to execute the function. These resources include computational power, memory, and any required dependencies.
    3. Function Execution: Once the resources are provisioned, the serverless platform invokes and executes the function code. The function code performs the desired task or implements the business logic defined by the developer.
    4. Data Processing: The function code can access and process the input data associated with the trigger event. This can include data passed through function parameters, event payloads, or integration with other services or databases.
    5. Scalability: Serverless platforms handle autoscaling transparently. If there’s a high volume of concurrent events or a sudden spike in traffic, the platform dynamically allocates additional resources.
    6. Function Completion: Once the function code completes its execution or reaches a return statement, the serverless platform collects the function’s output or return value.
    7. Resource Deallocation: After the function execution, the serverless platform releases the allocated resources. This ensures that you only pay for the actual execution time and resources used, minimizing costs during idle periods.
    8. Logging and Monitoring: Serverless platforms typically provide logging and monitoring capabilities to help developers troubleshoot issues, track function performance, and gather insights into function behavior.
    9. Billing: The cost of serverless functions is typically based on the execution time and the resources consumed during function execution. The pricing model varies across cloud providers, with factors such as memory allocation, execution duration, and the number of invocations affecting the cost.

It’s important to note that serverless functions can be part of a larger serverless architecture, where multiple functions work together to build complex applications. These functions can be orchestrated and integrated using various tools and services provided by the serverless platform or third-party solutions.

Why Use Serverless Functions?

Several notable companies have adopted serverless functions as part of their technology stack. Here are a few examples:

Netflix

Netflix uses serverless functions extensively in their architecture. They leverage serverless functions for tasks such as media encoding, thumbnail generation, and content recommendation algorithms. With serverless functions, Netflix can handle large-scale media processing and deliver personalized recommendations to millions of users worldwide.

Airbnb

Airbnb employs serverless functions to power parts of their infrastructure. They use serverless functions to handle user authentication, process booking requests, and manage notifications. By utilizing serverless functions, Airbnb can seamlessly scale their backend systems to accommodate high traffic and provide a reliable user experience.

Coca-Cola

Coca-Cola has embraced serverless functions for their marketing campaigns and customer engagement. They leverage serverless functions to handle event-driven tasks, such as dynamic content generation, user interactions, and personalized promotions. By utilizing serverless functions, Coca-Cola can create interactive and personalized customer experiences while efficiently managing campaign resources.

These companies demonstrate the diverse applications of serverless functions across different industries. From media processing and recommendation systems to user authentication and marketing campaigns, serverless functions provide the scalability, flexibility, and cost efficiency necessary to meet the demands of modern applications. By leveraging serverless functions, businesses can optimize their operations, enhance user experiences, and efficiently manage resources.

When to Use Serverless Functions

Serverless functions offer a range of advantages, but they may not be the optimal choice for every application scenario. Here’s what you should consider when determining whether to use serverless functions:



Event-Driven Workloads

Serverless functions are well suited for event-driven workloads. If your application needs to respond to events such as HTTP requests, database changes, file uploads, or scheduled tasks, serverless functions provide an efficient and scalable solution. They can handle bursts of events and scale automatically, ensuring that your application responds quickly and reliably.

Sporadic or Variable Workloads

Serverless functions are cost effective for applications with sporadic or variable workloads. With traditional server-based architectures, you need to provision and pay for idle resources to handle peak loads, which can be wasteful and expensive. Serverless functions eliminate this issue by scaling resources based on demand, allowing you to pay only for the actual execution time of your functions.

Bursty Workloads

If your application experiences sudden spikes in traffic or workload, serverless functions are well suited to handle these bursty scenarios. They can quickly scale up to accommodate the increased demand and then scale back down when the traffic subsides. This elasticity ensures that your application remains responsive and available during peak periods without over provisioning resources during quieter periods.

Microservices Architecture

Serverless functions align well with a microservices architecture. They enable you to break down your application into smaller, decoupled functions that can be developed, deployed, and scaled independently. This modular approach promotes agility, scalability, and easier maintenance. Each function can focus on a specific task or microservice, allowing for better code organization, flexibility, and scalability.

Rapid Prototyping and Development

Serverless functions provide a rapid prototyping and development environment. They abstract away much of the infrastructure management, allowing developers to focus on writing business logic. With pre-built integrations and deployment frameworks, developers can quickly iterate and experiment with ideas, reducing time to market. Serverless functions enable a faster feedback loop and facilitate agile development practices.

Cost Optimization

If cost optimization is a priority, serverless functions can be a viable option. With pay-per-use pricing, you only pay for the actual execution time and resources consumed by your functions. This cost model can result in significant savings, especially for applications with unpredictable or variable workloads. However, it’s essential to carefully monitor and optimize your function’s resource usage to maximize cost efficiency.

It’s important to reiterate that serverless functions may not be suitable for all application scenarios. Long-running or computationally intensive tasks may incur higher costs or face execution time limitations imposed by the serverless platform. Additionally, if your application requires low-latency real-time processing or extensive control over the underlying infrastructure, a serverless approach may not be the best fit.

Benefits of Serverless Functions

Serverless functions offer a range of advantages that make them an attractive choice for modern application development. Let’s explore some of the key benefits:

    • Scalability: Serverless functions allow for automatic and seamless scalability. They can handle sudden spikes in traffic or varying workloads without manual intervention. Cloud providers handle the scaling and resource allocation, ensuring that your application can scale up or down based on demand. This scalability eliminates the need for capacity planning and allows your application to handle any level of traffic efficiently.
    • Cost Efficiency: Serverless functions follow a pay-per-use pricing model, resulting in cost savings. You only pay for the actual execution time and resources consumed by your functions rather than paying for idle server time. This cost optimization makes serverless functions particularly beneficial for applications with unpredictable or varying workloads. You can significantly reduce costs by paying only for the resources you require during function execution.
    • Reduced Operational Complexity: Serverless functions abstract away infrastructure management, allowing developers to focus solely on writing code. You no longer need to worry about server provisioning, operating system maintenance, or infrastructure scaling. Cloud providers handle these operational tasks, including updates, patches, and monitoring. This simplified operations model frees up developers’ time and resources, enabling them to focus on application logic and innovation.
    • Rapid Development and Iteration: Serverless functions facilitate faster development cycles. Developers can focus on writing business logic without the need for infrastructure configuration. The serverless ecosystem provides pre-built integrations, libraries, and deployment frameworks, enabling developers to build applications more quickly and efficiently. The modular and decoupled nature of serverless functions also allows for easier maintenance and updates, making iterative development easier.
    • Event-Driven Architecture: Serverless functions excel in event-driven architectures, enabling reactive and responsive applications. They can be triggered by various events such as HTTP requests, database changes, or timer-based schedules. This event-driven nature allows developers to design systems that react to events in real time, enabling near-instantaneous response and decision making. Serverless functions enable the creation of scalable and resilient applications that can handle complex workflows.

These benefits, including scalability, cost efficiency, reduced operational complexity, rapid development, and event-driven architecture, make serverless functions an attractive choice for building modern applications. They empower developers to focus on delivering value and innovation while leveraging the scalability and cost optimization provided by serverless computing.

How to Implement and Monitor Serverless Functions

To implement and monitor serverless functions effectively, follow these steps:

  1. Implementation:
      • Choose a FaaS provider based on your requirements, programming language support, and ecosystem.
      • Write your function code using the supported language and framework provided by the FaaS platform.
      • Define triggers to specify the events or conditions invoking your functions (e.g., HTTP requests, database changes, scheduled triggers).
      • Configure runtime settings and dependencies, such as environment variables, access permissions, and external resource connections.
      • Package your function code and any necessary dependencies into a deployment package.
      • Deploy the package to the FaaS platform using the provided deployment mechanisms or tools.
  2. Monitoring:
      • Enable logging to capture relevant logs generated by your functions. Use log management solutions or cloud monitoring to centralize and analyze logs for troubleshooting and auditing purposes.
      • Monitor key metrics such as invocation counts, execution duration, error rates, and resource utilization. Leverage the FaaS platform’s monitoring and observability features to collect and analyze these metrics.
      • Implement distributed tracing to trace the flow of requests and events across your functions and any external services they interact with. This helps identify performance bottlenecks and diagnose issues.
      • Establish effective error-handling mechanisms within your functions and configure alerts or notifications to receive real-time notifications about critical errors or exceptions.
      • Continuously optimize the performance and scalability of your serverless functions by analyzing monitoring data, adjusting scaling thresholds, and making architectural improvements as needed.

Remember to refer to the documentation and monitoring features provided by your specific FaaS platform for detailed instructions and best practices. Additionally, consider utilizing third-party monitoring tools that integrate with your FaaS provider to enhance visibility and streamline monitoring processes.

What is Function-as-a-Service (FaaS)?

Function-as-a-Service (FaaS) is a cloud computing service that lets developers build and run specific pieces of code without managing the servers or infrastructure themselves. FaaS is a type of serverless computing, so it’s often referred to as “serverless functions”.

FaaS offers key advantages for application development, including: 

    • Event-Driven Execution: Functions are invoked as events occur, enabling dynamic and responsive application architectures.
    • Pay-Per-Use Billing: You only pay for the actual execution time and resources used by the functions, making it cost efficient for applications with sporadic or variable workloads.
    • Automatic Scaling: FaaS dynamically allocates resources to handle varying workloads, eliminating the need for manual intervention and capacity planning.

In summary, FaaS provides event-driven execution, cost efficiency, and automatic scaling, making it a flexible and scalable choice for application development.

FaaS Providers

Several cloud providers offer Function-as-a-Service (FaaS) platforms. Some of the prominent FaaS providers include:

    • AWS Lambda: Amazon Web Services (AWS) Lambda is a popular FaaS offering. It supports multiple programming languages, provides seamless integration with other AWS services, and offers flexible scaling options. Lambda functions can be triggered by a wide range of events and can be used to build serverless applications.
    • Azure Functions: Microsoft Azure Functions is a FaaS offering within the Azure cloud platform. It supports multiple programming languages and integrates well with other Azure services and event sources. Azure Functions provides automatic scaling, pay-per-use pricing, and robust developer tooling.
    • Google Cloud Functions: Google Cloud Functions is the FaaS offering from Google Cloud. It supports multiple languages, enables seamless integration with other Google Cloud services, and can be triggered by various events. Google Cloud Functions offers autoscaling, pay-per-use pricing, and tight integration with the broader Google Cloud ecosystem.
    • IBM Cloud Functions: IBM Cloud Functions, formerly known as OpenWhisk, is a serverless computing platform provided by IBM Cloud. It supports multiple programming languages, provides event-driven execution, and integrates with other IBM Cloud services. IBM Cloud Functions offers flexible scaling options and billing based on actual resource usage.
    • Alibaba Cloud Function Compute: Alibaba Cloud Function Compute is the FaaS offering from Alibaba Cloud. It supports multiple programming languages, provides automatic scaling, and integrates with other Alibaba Cloud services. Function Compute allows developers to build event-driven applications and pay only for the resources consumed during function execution.
    • Oracle Functions: Oracle Functions is a serverless compute offering within the Oracle Cloud Infrastructure (OCI). It supports multiple languages, integrates with other Oracle Cloud services, and provides automatic scaling and pay-per-use pricing. Oracle Functions allows developers to build event-driven applications and focus on writing code without infrastructure management.

These are just a few examples of FaaS providers, each with unique features, pricing models, and an ecosystem of services. Your choice of FaaS provider should depend on factors like programming language support, integration requirements, scalability needs, and overall cloud platform preferences.

Key Takeaways

Serverless functions have become a popular way to develop and deploy applications. They offer benefits like scalability, cost savings, and simplified management. Developers can focus on writing code for specific functions triggered by events. Serverless functions have various use cases, such as media processing, user authentication, booking processing, and marketing campaigns. They are ideal for applications with varying workloads due to their cost efficiency and automatic scaling. Implementing and monitoring serverless functions involves choosing a provider like AWS Lambda, Azure Functions, or Google Cloud Functions. These providers offer the necessary infrastructure and services. Function-as-a-Service (FaaS) powers serverless functions, allowing developers to write and deploy event-driven functions. Understanding serverless functions and FaaS helps developers and businesses take advantage of scalability, cost savings, and simplified application development.



The post A Guide to Serverless Functions appeared first on The Couchbase Blog.

Read the whole story
alvinashcraft
32 seconds ago
reply
West Grove, PA
Share this story
Delete

CTO Andrew Brown Passed Dozens of Cloud Certification Exams [freeCodeCamp Podcast Episode #120]

1 Share
On this week's episode of the podcast, I interview Andrew Brown, a CTO-turned co-founder of ExamPro.co. Andrew created this cloud certification exam prep website with another Andrew – also from Canada, who also loves Star Trek. We talk about Andrew's early career fixing computers in the 90s, and his early

Read the whole story
alvinashcraft
40 seconds ago
reply
West Grove, PA
Share this story
Delete

Adding and Sharing Annotations across Document Types using the Document Viewer in ASP.NET Core C#

1 Share

Learn how to add and share annotations across different document types using the Document Viewer in ASP.NET Core C#. This article shows how to create a simple web application that allows users to view and annotate documents in a collaborative environment.

Read more



Read the whole story
alvinashcraft
52 seconds ago
reply
West Grove, PA
Share this story
Delete

How to Create a Trial Version for a C# Windows Forms application

1 Share
Offering trial versions of applications is a common strategy to attract users by allowing them to evaluate the software before purchasing. However, designing a secure and user-friendly trial functionality can be challenging. [...]
Read the whole story
alvinashcraft
4 hours ago
reply
West Grove, PA
Share this story
Delete
Next Page of Stories