This document provides instructions for setting up and running a bot project using the Bot Builder SDK v4. It discusses downloading necessary software, creating a project in Visual Studio, implementing a welcome message, and managing state using user profiles and state accessors. The document contains code samples for creating a SampleBot class that inherits from IBot and uses state accessors and user profiles to save and retrieve a user's handle name.
Rhino Mocks is a .NET mocking framework that allows developers to easily create and setup mock objects to test interactions using unit tests. It generates both mocks, which allow expectations to be set and verified, and stubs, which simply return preset values without verification. The document provides examples of using Rhino Mocks to generate mocks and stubs of interfaces, set expectations on mocks, and verify mock interactions using the AAA (Arrange, Act, Assert) syntax. It also distinguishes between mocks and stubs.
Chat application in java using swing and socket programming.Kuldeep Jain
The document provides code for a chat application with client and server functionality. The server runs on port 1004 and handles socket connections from multiple clients. It maintains lists of connected clients and logged in user names. When a new client connects, threads are started to handle message receiving/sending and updating other clients on user name changes. The client GUI allows users to view online users, sent messages and send new messages which are broadcast to all connected clients by the server.
The Ring programming language version 1.3 book - Part 7 of 88Mahmoud Samir Fayed
Ring 1.3 includes improvements to RingQt classes, the Objects library, LibCurl, and other features. Better RingQt classes allow getting event information and enabling/disabling events. The updated Objects library manages GUI objects and provides a natural API for creating windows from classes. RingLibCurl adds functions wrapping LibCurl. Other enhancements include better support for calling methods from object attributes, displaying compiler warnings, and code quality improvements.
Typescript fundamentals document summarized in 3 sentences:
The document discusses Typescript fundamentals including types, classes, interfaces, modules and how to use the Typescript compiler. It explains how Typescript adds type safety and compile time checking to JavaScript by using types for variables, parameters, returns and more. Examples are provided for many Typescript features and how they compile down to equivalent JavaScript.
This document summarizes Spring features for building loosely coupled, maintainable applications. It discusses how Spring promotes loose coupling through dependency injection and application events. It also describes how to implement workflows with jBPM and manage transactions declaratively in Spring.
Description:
This project is an online Chat Room System which is built in Java Swing. The system adopts 3 tier architecture in which the client request server to register itself to the room, server register’s the user to the room and finally the client can share content with other registered client via server.
The system allows the user to connect from different location in a common chat-room where they can broadcast text messages and share drawing with other registered users.
Features:
• Apart from sharing content, the server broadcast entry and exist of the user.
• The chat window of every user is registered with client specific Title.
• Messages from client are pre-pend with their name.
• Cosmetic color change is implemented on-hover, on-active on the chat window, its borders and buttons.
• System allows tracking the user who is currently present in the chat room.
• System has the feature to save text messages/history in a text file from the chat window to the client local system.
The document discusses unit testing using the Spock framework. It begins with an introduction to unit testing and its benefits. It then provides an overview of Spock, explaining that it is a unit testing framework that utilizes Groovy syntax to make tests easy to write and read. The document gives examples of test structure in Spock using sections like given, when, then. It also demonstrates how to create mocks, check interactions with mocks, match invocations, check execution order, manage exceptions, and use features like shared variables and stubbing. Overall, the summary introduces Spock and provides examples of key features to illustrate how to write unit tests using this framework.
Rhino Mocks is a .NET mocking framework that allows developers to easily create and setup mock objects to test interactions using unit tests. It generates both mocks, which allow expectations to be set and verified, and stubs, which simply return preset values without verification. The document provides examples of using Rhino Mocks to generate mocks and stubs of interfaces, set expectations on mocks, and verify mock interactions using the AAA (Arrange, Act, Assert) syntax. It also distinguishes between mocks and stubs.
Chat application in java using swing and socket programming.Kuldeep Jain
The document provides code for a chat application with client and server functionality. The server runs on port 1004 and handles socket connections from multiple clients. It maintains lists of connected clients and logged in user names. When a new client connects, threads are started to handle message receiving/sending and updating other clients on user name changes. The client GUI allows users to view online users, sent messages and send new messages which are broadcast to all connected clients by the server.
The Ring programming language version 1.3 book - Part 7 of 88Mahmoud Samir Fayed
Ring 1.3 includes improvements to RingQt classes, the Objects library, LibCurl, and other features. Better RingQt classes allow getting event information and enabling/disabling events. The updated Objects library manages GUI objects and provides a natural API for creating windows from classes. RingLibCurl adds functions wrapping LibCurl. Other enhancements include better support for calling methods from object attributes, displaying compiler warnings, and code quality improvements.
Typescript fundamentals document summarized in 3 sentences:
The document discusses Typescript fundamentals including types, classes, interfaces, modules and how to use the Typescript compiler. It explains how Typescript adds type safety and compile time checking to JavaScript by using types for variables, parameters, returns and more. Examples are provided for many Typescript features and how they compile down to equivalent JavaScript.
This document summarizes Spring features for building loosely coupled, maintainable applications. It discusses how Spring promotes loose coupling through dependency injection and application events. It also describes how to implement workflows with jBPM and manage transactions declaratively in Spring.
Description:
This project is an online Chat Room System which is built in Java Swing. The system adopts 3 tier architecture in which the client request server to register itself to the room, server register’s the user to the room and finally the client can share content with other registered client via server.
The system allows the user to connect from different location in a common chat-room where they can broadcast text messages and share drawing with other registered users.
Features:
• Apart from sharing content, the server broadcast entry and exist of the user.
• The chat window of every user is registered with client specific Title.
• Messages from client are pre-pend with their name.
• Cosmetic color change is implemented on-hover, on-active on the chat window, its borders and buttons.
• System allows tracking the user who is currently present in the chat room.
• System has the feature to save text messages/history in a text file from the chat window to the client local system.
The document discusses unit testing using the Spock framework. It begins with an introduction to unit testing and its benefits. It then provides an overview of Spock, explaining that it is a unit testing framework that utilizes Groovy syntax to make tests easy to write and read. The document gives examples of test structure in Spock using sections like given, when, then. It also demonstrates how to create mocks, check interactions with mocks, match invocations, check execution order, manage exceptions, and use features like shared variables and stubbing. Overall, the summary introduces Spock and provides examples of key features to illustrate how to write unit tests using this framework.
A code kata in C# to help practice techniques for safely removing dependencies form legacy code and creating unit tests. Questions? Suggestions? Contact @dubmun.
Having trouble wrapping you mind around unit testing in legacy code? Practice this kata and you'll have a good understanding of some basics. Break dependencies, inject stubs, write meaningful tests. Refactor with confidence. Version 2 is a complete overhaul to make the kata more readable and usable.
This document discusses refactoring code to improve its design without changing external behavior. It notes that refactoring involves making small, incremental changes rather than large "big bang" refactorings. Code smells that may indicate a need for refactoring include duplication, long methods, complex conditional logic, speculative code, and overuse of comments. Techniques discussed include extracting methods, removing duplication, using meaningful names, removing temporary variables, and applying polymorphism. The document emphasizes that refactoring is an investment that makes future changes easier and helps avoid bugs, and encourages learning from other programming communities.
The Ring programming language version 1.5.4 book - Part 14 of 185Mahmoud Samir Fayed
Ring 1.2 includes several new features and improvements, such as new functions, better support for natural language programming, improved RingQt and RingNotepad functionality, and the ability to generate and execute Ring object files. Some key changes include new comparison and list functions, enhanced GUI library support, improved syntax flexibility, and overall better quality and stability.
The document discusses unit testing and test-driven development. It introduces the QUnit JavaScript testing framework, describing how to write tests and assertions using its API. Key aspects covered include setting up QUnit, the test and assert functions, asynchronous testing, grouping tests into modules, and integrating automated testing with Node and Grunt.
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
The document provides tips for adding testing to JavaScript projects. It recommends choosing a testing environment and dialect, then setting up the tests by installing dependencies and configuring files. Common issues like testing asynchronous code and methods that call other methods can be addressed with spies, stubs, mocks and promises. Tests should focus on isolated units of code and avoid direct DOM manipulation when possible. Automating testing through build tools like Grunt and Testem helps to easily run and watch tests. Overall, the document emphasizes making testing easy by writing maintainable, modular code and setting up automation.
Auto-GWT : Better GWT Programming with XtendSven Efftinge
Presentation from GWT.create 2015 EU
Auto-GWT (auto-gwt.org) is a library for the Google Web Toolkit, that frees your code from unneccessary and complicated boilerplate and at the same time pushes the IDE capabilities to a new level. Auto-GWT is based on Xtend (xtendlang.org).
Xtend is a modern programming language that is 100% compatibly with existing Java libraries and even translates to readable Java source code. With it's slick syntax and powerful features such as lambdas, operator overloading and compile-time macros you can turn any verbose piece of Java code into a small and elegant piece of expressive Xtend code.
In this session we will show how Xtend can be used to program GWT applications and how well the typical GWT idioms are supported by the language.
Workflow Foundation (WF4) allows visualizing and simplifying complex workflow patterns through a drag-and-drop interface. Key concepts include isolation of workflow instances from the host application and threading of instances separately from the main thread. The document demonstrates creating a simple workflow application in Visual Studio and passing data into and between activities using arguments and a custom activity. It also discusses alternative hosting models and types of workflows as well as services for persistence, tracking, and monitoring of workflow instances.
Everybody knows : Web is the platform of the future. Developing for the browser unfortunately requires us to learn and write JavaScript. Not only that but we also have to integrate the JavaScript client code with the server side, which often runs on the JVM (i.e. is written in Java). So we have to work in two different languages with completely different tools and APIs, and cannot share code between the client and the server.
The Google Web Toolkit (GWT) provides a way to write your client side web application entirely in Java and have it automatically translated to fast and compact JavaScript. It allows you to access all the browser functionality through a statically typed API. You only have to learn and use one language and you can use your code on the client as well as on the server.
The downside : Java is a bad match for the asynchronous programming model required on the browser and generally forces us to write and read a lot of boilerplate code.
In this session you'll see how programming GWT applications with Eclipse Xtend provides the best of both worlds:
Static typing with advanced IDE support meets a powerful and expressive language - right at your finger tips.
Test-driven development (TDD) involves writing unit tests before writing code to help ensure code quality and avoid omitted tests. The document discusses the NUnit testing framework for .NET, which uses attributes to identify test fixtures, methods, and setup/teardown functionality. It also covers how to write tests using assertions and run tests using the NUnit GUI or console applications.
The document discusses how to implement callbacks in Java RMI using remote method invocation. It describes defining a listener interface and event source interface, implementing the event source to notify listeners, implementing a listener client, and registering the listener with the event source. It provides code examples for implementing and registering both the event source and listener.
Since these presentations were spare time hobby - I've decided to share them :)
Hopefully someone will find them useful.
This part continues 1. part with more design patterns like Command, State, NullObject.
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
jQuery is a JavaScript library that simplifies HTML document traversal, event handling, animating, and Ajax interactions. It was created in 2006 with the goal of writing less code to do more. jQuery simplifies tasks like selecting elements, handling events, performing animations and AJAX calls to make web development faster.
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski
The document discusses testing and some common objections to writing tests. It addresses concerns like tests taking too much time, specs changing too often, tests being difficult to understand, and whether there are too many tests or too much code. It provides examples of simple, readable tests and discusses test-driven development principles like writing just enough tests to feel confident in changes without going overboard.
This document discusses various ways to use variables and methods in Groovy scripts in soapUI to interact with and retrieve information from the test runner context, test cases, test steps, message exchanges, and XML responses and requests. It provides examples of using the log, context, testRunner, and messageExchange variables, as well as methods for retrieving test suites, test cases, test steps, and property values. It also demonstrates how to read and write XML using the GroovyUtils class, convert between strings and integers, and read the raw request and response contents.
The Ring programming language version 1.2 book - Part 5 of 84Mahmoud Samir Fayed
Ring 1.2 includes many new features and improvements, including:
1. New functions like PtrCmp() for comparing C pointers and RingVM_FunctionsList() to return a list of Ring functions.
2. Better existing functions like find() and type() updated to support C pointers.
3. An improved Ring Notepad that saves line numbers and prompts to save changes.
4. Enhancements to RingQt like disabling events and getting event information.
5. A new Objects library for RingQt applications to manage GUI objects and events.
6. An expanded RingLibCurl library for powerful LibCurl integration.
7. Support for calling methods from object attributes with
The document provides an overview of SObjectizer, an open source framework for building concurrent and event-driven applications in C++. It describes how SObjectizer was originally developed in the 1990s and has since evolved through several versions. The document then dives into key aspects of how SObjectizer works, including how an application is launched through an SObjectizer environment, how agents are defined and registered in cooperations, and how agents communicate asynchronously via messages. It provides an example of defining ping and pong messages and a simple ponger agent to demonstrate these concepts.
Mocking allows testing components in isolation without dependencies like databases or file systems. It emphasizes single responsibility by allowing classes to behave consistently regardless of dependency implementations. Mockito provides mocking capabilities like stubbing mock methods to return values or exceptions and verifying mock method calls and arguments. It supports argument matchers, verifying call order and number of invocations, and spying to selectively mock certain methods of real objects.
The document discusses upcoming web standards like HTML5 and WebSockets. It provides examples of using local storage, handling errors with window.onerror, and the Same Origin Policy. It also demonstrates how to access device sensors and use the webcam with getUserMedia. The document promotes Opera's developer tools like Dragonfly and extensions to aid web development.
The document discusses using annotations in Java, providing examples of annotations for servlets, EJBs, web services, CDI, and using frameworks like JUnit, Spring, Javassist, and ASM. It presents code samples to define servlets, session beans, RESTful and SOAP web services, and component injection using annotations instead of XML configurations. The document also demonstrates how to programmatically read annotation values and metadata using reflection, Javassist, and ASM.
A code kata in C# to help practice techniques for safely removing dependencies form legacy code and creating unit tests. Questions? Suggestions? Contact @dubmun.
Having trouble wrapping you mind around unit testing in legacy code? Practice this kata and you'll have a good understanding of some basics. Break dependencies, inject stubs, write meaningful tests. Refactor with confidence. Version 2 is a complete overhaul to make the kata more readable and usable.
This document discusses refactoring code to improve its design without changing external behavior. It notes that refactoring involves making small, incremental changes rather than large "big bang" refactorings. Code smells that may indicate a need for refactoring include duplication, long methods, complex conditional logic, speculative code, and overuse of comments. Techniques discussed include extracting methods, removing duplication, using meaningful names, removing temporary variables, and applying polymorphism. The document emphasizes that refactoring is an investment that makes future changes easier and helps avoid bugs, and encourages learning from other programming communities.
The Ring programming language version 1.5.4 book - Part 14 of 185Mahmoud Samir Fayed
Ring 1.2 includes several new features and improvements, such as new functions, better support for natural language programming, improved RingQt and RingNotepad functionality, and the ability to generate and execute Ring object files. Some key changes include new comparison and list functions, enhanced GUI library support, improved syntax flexibility, and overall better quality and stability.
The document discusses unit testing and test-driven development. It introduces the QUnit JavaScript testing framework, describing how to write tests and assertions using its API. Key aspects covered include setting up QUnit, the test and assert functions, asynchronous testing, grouping tests into modules, and integrating automated testing with Node and Grunt.
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
The document provides tips for adding testing to JavaScript projects. It recommends choosing a testing environment and dialect, then setting up the tests by installing dependencies and configuring files. Common issues like testing asynchronous code and methods that call other methods can be addressed with spies, stubs, mocks and promises. Tests should focus on isolated units of code and avoid direct DOM manipulation when possible. Automating testing through build tools like Grunt and Testem helps to easily run and watch tests. Overall, the document emphasizes making testing easy by writing maintainable, modular code and setting up automation.
Auto-GWT : Better GWT Programming with XtendSven Efftinge
Presentation from GWT.create 2015 EU
Auto-GWT (auto-gwt.org) is a library for the Google Web Toolkit, that frees your code from unneccessary and complicated boilerplate and at the same time pushes the IDE capabilities to a new level. Auto-GWT is based on Xtend (xtendlang.org).
Xtend is a modern programming language that is 100% compatibly with existing Java libraries and even translates to readable Java source code. With it's slick syntax and powerful features such as lambdas, operator overloading and compile-time macros you can turn any verbose piece of Java code into a small and elegant piece of expressive Xtend code.
In this session we will show how Xtend can be used to program GWT applications and how well the typical GWT idioms are supported by the language.
Workflow Foundation (WF4) allows visualizing and simplifying complex workflow patterns through a drag-and-drop interface. Key concepts include isolation of workflow instances from the host application and threading of instances separately from the main thread. The document demonstrates creating a simple workflow application in Visual Studio and passing data into and between activities using arguments and a custom activity. It also discusses alternative hosting models and types of workflows as well as services for persistence, tracking, and monitoring of workflow instances.
Everybody knows : Web is the platform of the future. Developing for the browser unfortunately requires us to learn and write JavaScript. Not only that but we also have to integrate the JavaScript client code with the server side, which often runs on the JVM (i.e. is written in Java). So we have to work in two different languages with completely different tools and APIs, and cannot share code between the client and the server.
The Google Web Toolkit (GWT) provides a way to write your client side web application entirely in Java and have it automatically translated to fast and compact JavaScript. It allows you to access all the browser functionality through a statically typed API. You only have to learn and use one language and you can use your code on the client as well as on the server.
The downside : Java is a bad match for the asynchronous programming model required on the browser and generally forces us to write and read a lot of boilerplate code.
In this session you'll see how programming GWT applications with Eclipse Xtend provides the best of both worlds:
Static typing with advanced IDE support meets a powerful and expressive language - right at your finger tips.
Test-driven development (TDD) involves writing unit tests before writing code to help ensure code quality and avoid omitted tests. The document discusses the NUnit testing framework for .NET, which uses attributes to identify test fixtures, methods, and setup/teardown functionality. It also covers how to write tests using assertions and run tests using the NUnit GUI or console applications.
The document discusses how to implement callbacks in Java RMI using remote method invocation. It describes defining a listener interface and event source interface, implementing the event source to notify listeners, implementing a listener client, and registering the listener with the event source. It provides code examples for implementing and registering both the event source and listener.
Since these presentations were spare time hobby - I've decided to share them :)
Hopefully someone will find them useful.
This part continues 1. part with more design patterns like Command, State, NullObject.
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
jQuery is a JavaScript library that simplifies HTML document traversal, event handling, animating, and Ajax interactions. It was created in 2006 with the goal of writing less code to do more. jQuery simplifies tasks like selecting elements, handling events, performing animations and AJAX calls to make web development faster.
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski
The document discusses testing and some common objections to writing tests. It addresses concerns like tests taking too much time, specs changing too often, tests being difficult to understand, and whether there are too many tests or too much code. It provides examples of simple, readable tests and discusses test-driven development principles like writing just enough tests to feel confident in changes without going overboard.
This document discusses various ways to use variables and methods in Groovy scripts in soapUI to interact with and retrieve information from the test runner context, test cases, test steps, message exchanges, and XML responses and requests. It provides examples of using the log, context, testRunner, and messageExchange variables, as well as methods for retrieving test suites, test cases, test steps, and property values. It also demonstrates how to read and write XML using the GroovyUtils class, convert between strings and integers, and read the raw request and response contents.
The Ring programming language version 1.2 book - Part 5 of 84Mahmoud Samir Fayed
Ring 1.2 includes many new features and improvements, including:
1. New functions like PtrCmp() for comparing C pointers and RingVM_FunctionsList() to return a list of Ring functions.
2. Better existing functions like find() and type() updated to support C pointers.
3. An improved Ring Notepad that saves line numbers and prompts to save changes.
4. Enhancements to RingQt like disabling events and getting event information.
5. A new Objects library for RingQt applications to manage GUI objects and events.
6. An expanded RingLibCurl library for powerful LibCurl integration.
7. Support for calling methods from object attributes with
The document provides an overview of SObjectizer, an open source framework for building concurrent and event-driven applications in C++. It describes how SObjectizer was originally developed in the 1990s and has since evolved through several versions. The document then dives into key aspects of how SObjectizer works, including how an application is launched through an SObjectizer environment, how agents are defined and registered in cooperations, and how agents communicate asynchronously via messages. It provides an example of defining ping and pong messages and a simple ponger agent to demonstrate these concepts.
Mocking allows testing components in isolation without dependencies like databases or file systems. It emphasizes single responsibility by allowing classes to behave consistently regardless of dependency implementations. Mockito provides mocking capabilities like stubbing mock methods to return values or exceptions and verifying mock method calls and arguments. It supports argument matchers, verifying call order and number of invocations, and spying to selectively mock certain methods of real objects.
The document discusses upcoming web standards like HTML5 and WebSockets. It provides examples of using local storage, handling errors with window.onerror, and the Same Origin Policy. It also demonstrates how to access device sensors and use the webcam with getUserMedia. The document promotes Opera's developer tools like Dragonfly and extensions to aid web development.
The document discusses using annotations in Java, providing examples of annotations for servlets, EJBs, web services, CDI, and using frameworks like JUnit, Spring, Javassist, and ASM. It presents code samples to define servlets, session beans, RESTful and SOAP web services, and component injection using annotations instead of XML configurations. The document also demonstrates how to programmatically read annotation values and metadata using reflection, Javassist, and ASM.
This talk will explain the Google Web Toolkit (GWT), GWT architecture, and why you would want to use GWT. In addition, it will include a demo of GWT and the recently released GWT Designer (a tool that makes GWT development easy and that makes it fast to generate a complicated UI).
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo Ali Parmaksiz
This document summarizes a presentation about developing a MVP application using GWT, Spring Roo, and deploying it to CloudFoundry. The presentation covers MVP pattern in GWT, using activities and places for navigation, using Spring Roo for rapid development, and deploying the application to CloudFoundry. It provides code examples for implementing MVP using views, presenters, activities and places. It also outlines the steps to deploy an application to CloudFoundry including installing the vmc CLI and pushing the application.
Le temps est révolu où Java EE ne serait qu’à développer des applications de mise à jour de données, avec JSF / EJB / JPA. Aujourd’hui Java EE s’est assoupli et s’est ouvert sur le monde, avec CDI comme clé de voûte et a repoussé nos limites grâce à des capacités d’extension puissantes et faciles d’utilisation comme JCA.
Dans un premier temps, nous reviendrons rapidement sur la place de CDI dans JavaEE 7 et sur ses mécanismes d’extension. Dans un deuxième temps, nous verrons les techniques de connecteurs JCA et comment ils peuvent aussi constituer une possibilité d’ouverture simple à mettre en œuvre. JCA fournit des techniques pour gérer des connexions sortantes ou entrantes, sur des formats ou protocoles variés.
How to build twitter bot using golang from scratchKaty Slemon
This document provides a tutorial on how to build a Twitter bot using Golang from scratch. It covers setting up a Twitter developer account, installing prerequisites like Golang and ngrok, configuring the .env file, implementing CRC validation, registering and subscribing webhooks, listening for events, sending tweets in response, and setting up the server. The full source code for the Twitter bot project is provided in a GitHub repository for reference. The tutorial aims to help readers develop their own Twitter bot application from start to finish without using any third-party libraries.
The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
This document provides an overview of Google Web Toolkit (GWT), including its architecture, key features, and how to implement common tasks. GWT is a development toolkit that allows web applications to be written in Java and compiled into JavaScript for better cross-browser compatibility. It discusses topics like building user interfaces with widgets, event handling, styling with CSS, making remote procedure calls, and accessing native JavaScript methods. Examples and demos are provided to illustrate concepts like creating custom widgets, handling events, and making asynchronous server calls. Resources for learning more about GWT are also listed.
1. The runbook grants a user VPN access by making changes to their Active Directory profile after their request is approved.
2. It runs .NET scripts to extract the user's SAM account name and grant VPN access by setting the msnpallowdialin property to true.
3. It then gets information on the user and their manager from Active Directory to notify them by email that VPN access was granted.
The document provides an overview of key Android app development concepts including activities, services, broadcast receivers, content providers, the activity lifecycle, asynchronous tasks, SQLite database usage, and Google Maps integration. It discusses how activities represent screens, services run in the background, broadcast receivers respond to system broadcasts, and content providers share data between apps. It also covers the activity lifecycle, asynchronous tasks, SQLite database implementation using SQLiteOpenHelper, and steps to add a map with markers to an app using the Google Maps Android API.
The document discusses using Hibernate for database persistence in layered Java applications. It describes using Hibernate with servlet engines and the thread-local session pattern to share a single database session across request processing. It also discusses implementing data access with DAOs and a session facade pattern to provide coarse-grained services. Finally, it briefly mentions implementing audit logging for persistent objects by marking classes, defining log fields, and using a Hibernate interceptor.
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageabilityDaniel Fisher
The document profiles two software architects and CTOs at devocach, Daniel Fisher and Michael Willers. It lists their extensive experience in areas like development, architecture, consulting, and community events. It also outlines some of devocach's expertise, including service orientation, agile methods, web and data access, and security. The document emphasizes that devocach works on real projects, not just demonstrations.
Sample JavaScript Code Laurence Svekis
JavaScript Closure
A closure in JavaScript is a function that has access to the variables in its parent scope, even after the parent function has completed execution. This allows for data to be “closed over” or remembered by the inner function, even after the outer function has returned.
Here, the makeCounter function returns an inner function that has access to the count variable declared in its parent scope, and can “remember” the current count value even after the makeCounter function has completed execution. Each time the inner function is called, it returns the current value of count and increments it by 1.
JavaScript Closure Advanced
In this example, the makeAdder function takes in a single argument x and returns an inner function that takes in a second argument y. The inner function has access to the x variable declared in the parent scope and uses it to add x and y together and return the result.
We can see here that the outer function makeAdder has been executed twice and it returns two different inner functions which are assigned to different variables add5 and add10 and these inner functions are able to remember their respective parent scope values of x.
The document discusses test-driven development (TDD). It states that TDD relies on short development cycles where the developer first writes an automated test case that defines a new function or improvement. Then the developer produces code to pass that test, and refactors the new code to acceptable standards.
The document discusses annotation processing in Java. Annotation processing allows annotations to be inspected at compile time and to generate code. It works by having an annotation processor implement the Processor interface and process annotations. The processor can find annotated elements, generate Java code using APIs like JavaPoet, and write the generated code files so they are available to the compiler. An example project called HolyFragment is described that uses annotation processing to generate helper code for fragments annotated with a custom @Holy annotation.
Azure Active Directory - Secure and GovernCheah Eng Soon
Azure Active Directory helps secure and govern authentication with features like conditional access and privileged identity management. It allows organizations to mitigate admin risk, govern identities, and set terms of use policies for authentication and access across cloud and on-premises environments.
Zero Trust is a security concept that requires strict identity verification for anyone or anything trying to access applications, data, and infrastructure inside or outside the network. It assumes there is no implicit trust granted to assets and users inside the network, and that verification is required for every access. The goal of Zero Trust is to minimize risk from both external and internal threats by preventing lateral movement and only allowing access based on least-privilege user roles and asset usage.
Microsoft Endpoint Manager provides comprehensive device management capabilities for on-premises environments. It allows IT administrators to deploy, update, protect and monitor Windows, macOS, Linux and IoT devices from a single console. Endpoint Manager combines the capabilities of Configuration Manager and Intune to help businesses securely manage all types of devices across locations.
Microsoft Threat Protection Automated Incident Response Cheah Eng Soon
Microsoft Defender provides automated threat protection including zero-hour and auto purge features to respond to incidents. It also has automated incident response capabilities for user reported phishing attacks and URL verdict changes that help address threats.
The document discusses Azure penetration testing. It provides an agenda that covers an overview of common Azure services attacked, tools used for testing, and guidelines. It describes how Microsoft's blue and red teams work together on testing. Policies prohibit attacks on other customers or social engineering. Encouraged tests include using trial accounts and informing Microsoft of any vulnerabilities found. Steps outlined include identifying attack surfaces, data collection, vulnerability scanning, and penetration testing public-facing Azure services using tools like MicroBurst. Securing databases and using encryption are also addressed. A demo of vulnerability identification is promised.
You'll understand how hackers can attack resources hosted in the Azure and protect Azure infrastructure by identifying vulnerabilities, along with extending your pentesting tools and capabilities.
Microsoft Threat Protection Automated Incident Response DemoCheah Eng Soon
A user reported a phishing attack in their Office 365 organization. The Office 365 Threat Protection service investigated the report and found a malicious URL distributing malware. The URL was blocked for all users in the organization to prevent further infection from this phishing attempt.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive functioning. Exercise causes chemical changes in the brain that may help protect against mental illness and improve symptoms.
This document outlines demo scenarios for Microsoft Cloud App Security including discovering cloud apps used by an organization, protecting information from connected apps, detecting anomalous user behavior and threats across applications, and automating alert management with Power Automate. The scenarios cover exploring snapshot and continuous reports of discovered apps and risk scores, investigating connected apps and activity logs, detecting anonymous access, and integrating Microsoft Cloud App Security with Microsoft Threat Protection and Power Automate.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive functioning. Exercise causes chemical changes in the brain that may help protect against mental illness and improve symptoms.
This document summarizes three Microsoft cloud security products: Azure Security Center, Azure Defender, and Microsoft Cloud App Security. Azure Security Center strengthens multi-cloud security posture through dashboards, connectors, secure scores, recommendations, and inventory. Azure Defender protects cloud workloads through vulnerability assessment and security for SQL, storage, and Kubernetes. Microsoft Cloud App Security discovers cloud apps, protects access to connected apps, and detects anomalous user behavior and threats.
Azure Active Directory - External Identities Demo Cheah Eng Soon
The document discusses configuring external identities in Azure Active Directory. It mentions partner authentication with Azure AD and consumer identity providers. It also discusses verifying identities with IDology and lists several organization names, addresses, and contact emails.
Azure WAF is a cloud-native web application firewall service that provides powerful protection for web apps with simple deployment, low maintenance costs, and automatic updates. It acts as a content delivery network and can defend against common attacks like command execution, SQL injection, cross-site scripting, and more, as demonstrated in a presentation where custom rules were set up to create an Azure WAF.
Azure Weekend 2020 Build Malaysia Bus Uncle ChatbotCheah Eng Soon
Thank you for the informative presentation on conversational AI and natural language processing. I learned about key concepts like QnA Maker, Azure Bot Service, and various NLP capabilities in Azure Cognitive Services like text analytics, speech, and translation. The demo was very helpful to see these services in action.
20 common security vulnerabilities and misconfiguration in AzureCheah Eng Soon
This document outlines 20 common security vulnerabilities and misconfigurations in Microsoft Azure. It discusses issues such as storage accounts being publicly accessible, lack of multi-factor authentication, insecure guest user settings, and features like Azure Security Center and Network Watcher being disabled by default. The document is intended to educate users on important security best practices for securing resources and configurations in Azure.
Integrate Microsoft Graph with Azure Bot ServicesCheah Eng Soon
The document discusses 4 steps to integrate Microsoft Graph with Azure Bot Services by registering an application in Azure AD, making queries to Microsoft Graph to retrieve data like documents from SharePoint, implementing code snippets to retrieve the data, and extending the bot to Microsoft Teams. It provides an overview of conversational AI and Azure Bot Services and demonstrates using Microsoft Graph Explorer.
This document provides an overview of Azure Sentinel and how it can be used with Office 365. It discusses the challenges of security operations and how Azure Sentinel uses AI and automation to help. It then summarizes Azure Sentinel's key capabilities including visibility, analytics, hunting, incidents, and automation. It also includes demonstrations of these capabilities and steps to set up Azure Sentinel with an Office 365 connection.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Infrastructure Challenges in Scaling RAG with Custom AI modelsZilliz
Building Retrieval-Augmented Generation (RAG) systems with open-source and custom AI models is a complex task. This talk explores the challenges in productionizing RAG systems, including retrieval performance, response synthesis, and evaluation. We’ll discuss how to leverage open-source models like text embeddings, language models, and custom fine-tuned models to enhance RAG performance. Additionally, we’ll cover how BentoML can help orchestrate and scale these AI components efficiently, ensuring seamless deployment and management of RAG systems in the cloud.
Infrastructure Challenges in Scaling RAG with Custom AI models
Bot builder v4 HOL
1. Bot Builder v4 HOL
Chapter 1: Preparation
• Visual Studio 2017
• .Net Core 2.x ( https://www.microsoft.com/net/download )
• Bot Builder V4 SDK Template for Visual Studio
( https://marketplace.visualstudio.com/items?itemName=BotBuilder.botb
uilderv4 )
• Bot Emulator ( https://github.com/Microsoft/BotFramework-
Emulator/releases )
• Ngrok (https://ngrok.com/ )
Or
You can use Azure Bot Services .
After Download the Ngrok, please launch your Bot Emulator and go to
Emulator Settings and Setup as below.
2. Chapter 2: Create Project
1. Launch your Visual Studio.
2. Create a New Project, File > New > Project
3. Select Multi-Project and Select Bot Builder Echo Bot v4 and Name
your project, HandsonBot . Lastly , click OK button.
4. Make sure your bot template update to the v4.0.7
3. 5. Test Run your project. Go to dropdownlist of IIS Express and Select
HandsonBot , which is your project name and Press F5 for Debug your
project.
6. After Debug, you will see the localhost as below.
7. Launch your Bot Framework Emulator and Click Open Bot and Select
BotConfiguration.Bot that in your project.
4. Chapter 3: Implementation of welcome message
1. Go to your project, right click > add new folder “SampleBot”.
2. After create the folder , right click > add class > name the class as
“SampleBot”.
3. Implement the code as below.
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace HandsonBot.SampleBot
{
public class SampleBot : IBot
{
private const string WelcomeText = "Welcome to Sample Bot";
private readonly ILogger _logger;
private readonly SampleBotAccessors _accessors; // Added
private readonly DialogSet _dialogs; // Added
public SampleBot(SampleBotAccessors accessors, ILoggerFactory
loggerFactory) // Updated
{
_accessors = accessors ?? throw new
ArgumentException(nameof(accessors)); // Added
_dialogs = new DialogSet(accessors.ConversationDialogState); // Added
_dialogs.Add(new TextPrompt("name", ValidateHandleNameAsync));
_logger = loggerFactory.CreateLogger<SampleBot>();
_logger.LogInformation("Start SampleBot");
}
private Task<bool> ValidateHandleNameAsync(PromptValidatorContext<string>
promptContext, CancellationToken cancellationToken)
{
var result = promptContext.Recognized.Value;
if (result != null && result.Length >= 3)
{
var upperValue = result.ToUpperInvariant();
promptContext.Recognized.Value = upperValue;
return Task.FromResult(true);
}
return Task.FromResult(false);
}
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken
cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
// We will exchange normal messages here.
5. await SendMessageActivityAsync(turnContext, cancellationToken); //
updated
}
else if (turnContext.Activity.Type ==
ActivityTypes.ConversationUpdate)
{
await SendWelcomeMessageAsync(turnContext, cancellationToken);
}
else
{
_logger.LogInformation($"passed:{turnContext.Activity.Type}");
}
await _accessors.ConversationState.SaveChangesAsync(turnContext,
false, cancellationToken);
await _accessors.UserState.SaveChangesAsync(turnContext, false,
cancellationToken);
}
private static async Task SendWelcomeMessageAsync(ITurnContext
turnContext, CancellationToken cancellationToken)
{
foreach (var member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(WelcomeText,
cancellationToken: cancellationToken);
}
}
}
private async Task SendMessageActivityAsync(ITurnContext turnContext,
CancellationToken cancellationToken)
{
var dialogContext = await _dialogs.CreateContextAsync(turnContext,
cancellationToken);
var dialogTurnResult = await
dialogContext.ContinueDialogAsync(cancellationToken);
var userProfile = await _accessors.UserProfile.GetAsync(turnContext,
() => new UserProfile(), cancellationToken);
// If the handle name is not registered in UserState
if (userProfile.HandleName == null)
{
await GetHandleNameAsync(dialogContext, dialogTurnResult,
userProfile, cancellationToken);
}
else
{
await turnContext.SendActivityAsync($"Hello
{userProfile.HandleName}", cancellationToken: cancellationToken);
}
}
private async Task GetHandleNameAsync(DialogContext dialogContext,
DialogTurnResult dialogTurnResult, UserProfile userProfile, CancellationToken
cancellationToken)
{
if (dialogTurnResult.Status is DialogTurnStatus.Empty)
{
6. await dialogContext.PromptAsync(
"name",
new PromptOptions
{
Prompt = MessageFactory.Text("Please tell me your handle
name first."),
RetryPrompt = MessageFactory.Text("The handle name must be
at least 3 words long."),
},
cancellationToken);
}
else if (dialogTurnResult.Status is DialogTurnStatus.Complete)
{
// Register your handle name with UserState
userProfile.HandleName = (string)dialogTurnResult.Result;
_logger.LogInformation($"Handle Name registration:
{userProfile.HandleName}");
}
}
}
}
4. Go to Startup.cs
Change near line 57
From
services.AddBot<EchoWithCounterBot>(options =>
to
services.AddBot<SampleBot.SampleBot>(options =>
&
Change near line 78
From
ILogger logger = _loggerFactory.CreateLogger<EchoWithCounterBot>();
to
ILogger logger = _loggerFactory.CreateLogger<SampleBot.SampleBot>();
7. Chapter 4: State Management
1. Right Click “SampleBot” Folder > right click > Add > Create
UserProfile.class and Implement the code as below.
namespace HandsonBot.SampleBot
{
public class UserProfile
{
public string HandleName { get; set; }
}
}
2. Install the Microsoft.Bot.Builder.Dialogs Nuget Package.
Go to Tools> Nuget Package Manager> Package Manager Console and
type the command as below.
Install-Package Microsoft.Bot.Builder.Dialogs
3. Implement of State management Accessor
Right Click “SampleBot” Folder > right click > Add > Create
SampleBotAccessors.class and Implement the code as below.
using System;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
namespace HandsonBot.SampleBot
{
public class SampleBotAccessors
{
public IStatePropertyAccessor<DialogState> ConversationDialogState { get;
set; }
public IStatePropertyAccessor<UserProfile> UserProfile { get; set; }
public ConversationState ConversationState { get; }
public UserState UserState { get; }
public SampleBotAccessors(ConversationState conversationState, UserState
userState)
{
ConversationState = conversationState ?? throw new
ArgumentNullException(nameof(conversationState));
UserState = userState ?? throw new ArgumentException(nameof(userState));
}
}
}
8. 4. Change Startup.cs near line 111, to implement Application of UserState
Class
From
var conversationState = new ConversationState(dataStore);
options.State.Add(conversationState);
To
var conversationState = new ConversationState(dataStore);
options.State.Add(conversationState);
var userState = new UserState(dataStore);
options.State.Add(userState);
5. Implement of SampleBotAccessors class in Startup.cs , add the following
code as below.
using System;
using System.Linq;
using HandsonBot.SampleBot;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Integration;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HandsonBot
{
/// <summary>
/// The Startup class configures services and the request
pipeline.
/// </summary>
public class Startup
{
private ILoggerFactory _loggerFactory;
private bool _isProduction = false;
public Startup(IHostingEnvironment env)
{
_isProduction = env.IsProduction();
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true,
reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json"
, optional: true)
.AddEnvironmentVariables();
9. Configuration = builder.Build();
}
/// <summary>
/// Gets the configuration that represents a set of key/value
application configuration properties.
/// </summary>
/// <value>
/// The <see cref="IConfiguration"/> that represents a set of
key/value application configuration properties.
/// </value>
public IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to
add services to the container.
/// </summary>
/// <param name="services">The <see
cref="IServiceCollection"/> specifies the contract for a collection of
service descriptors.</param>
/// <seealso cref="IStatePropertyAccessor{T}"/>
/// <seealso cref="https://docs.microsoft.com/en-
us/aspnet/web-api/overview/advanced/dependency-injection"/>
/// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-
service/bot-service-manage-channels?view=azure-bot-service-4.0"/>
public void ConfigureServices(IServiceCollection services)
{
services.AddBot<SampleBot.SampleBot>(options =>
{
var secretKey =
Configuration.GetSection("botFileSecret")?.Value;
var botFilePath =
Configuration.GetSection("botFilePath")?.Value;
// Loads .bot configuration file and adds a singleton
that your Bot can access through dependency injection.
var botConfig = BotConfiguration.Load(botFilePath ??
@".BotConfiguration.bot", secretKey);
services.AddSingleton(sp => botConfig ?? throw new
InvalidOperationException($"The .bot config file could not be loaded.
({botConfig})"));
// Retrieve current endpoint.
var environment = _isProduction ? "production" :
"development";
var service = botConfig.Services.Where(s => s.Type ==
"endpoint" && s.Name == environment).FirstOrDefault();
if (!(service is EndpointService endpointService))
{
throw new InvalidOperationException($"The .bot
file does not contain an endpoint with name '{environment}'.");
}
options.CredentialProvider = new
SimpleCredentialProvider(endpointService.AppId,
endpointService.AppPassword);
// Creates a logger for the application to use.
ILogger logger =
_loggerFactory.CreateLogger<SampleBot.SampleBot>();
10. // Catches any errors that occur during a conversation
turn and logs them.
options.OnTurnError = async (context, exception) =>
{
logger.LogError($"Exception caught :
{exception}");
await context.SendActivityAsync("Sorry, it looks
like something went wrong.");
};
// The Memory Storage used here is for local bot
debugging only. When the bot
// is restarted, everything stored in memory will be
gone.
IStorage dataStore = new MemoryStorage();
// For production bots use the Azure Blob or
// Azure CosmosDB storage providers. For the Azure
// based storage providers, add the
Microsoft.Bot.Builder.Azure
// Nuget package to your solution. That package is
found at:
//
https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
// Uncomment the following lines to use Azure Blob
Storage
// //Storage configuration name or ID from the .bot
file.
// const string StorageConfigurationId = "<STORAGE-
NAME-OR-ID-FROM-BOT-FILE>";
// var blobConfig =
botConfig.FindServiceByNameOrId(StorageConfigurationId);
// if (!(blobConfig is BlobStorageService
blobStorageConfig))
// {
// throw new InvalidOperationException($"The .bot
file does not contain an blob storage with name
'{StorageConfigurationId}'.");
// }
// // Default container name.
// const string DefaultBotContainer = "<DEFAULT-
CONTAINER>";
// var storageContainer =
string.IsNullOrWhiteSpace(blobStorageConfig.Container) ?
DefaultBotContainer : blobStorageConfig.Container;
// IStorage dataStore = new
Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.Connect
ionString, storageContainer);
// Create Conversation State object.
// The Conversation State object is where we persist
anything at the conversation-scope.
var conversationState = new
ConversationState(dataStore);
options.State.Add(conversationState);
var userState = new UserState(dataStore);
options.State.Add(userState);
});
11. // Create and register state accesssors.
// Acessors created here are passed into the IBot-derived
class on every turn.
services.AddSingleton<EchoBotAccessors>(sp =>
{
var options =
sp.GetRequiredService<IOptions<BotFrameworkOptions>>().Value;
if (options == null)
{
throw new
InvalidOperationException("BotFrameworkOptions must be configured
prior to setting up the state accessors");
}
var conversationState =
options.State.OfType<ConversationState>().FirstOrDefault();
if (conversationState == null)
{
throw new
InvalidOperationException("ConversationState must be defined and added
before adding conversation-scoped state accessors.");
}
// Create the custom state accessor.
// State accessors enable other components to read and
write individual properties of state.
var accessors = new
EchoBotAccessors(conversationState)
{
CounterState =
conversationState.CreateProperty<CounterState>(EchoBotAccessors.Counte
rStateName),
};
return accessors;
});
// Create and register state accesssors.
// Acessors created here are passed into the IBot-derived
class on every turn.
services.AddSingleton<SampleBotAccessors>(sp =>
{
var options =
sp.GetRequiredService<IOptions<BotFrameworkOptions>>().Value
?? throw new
InvalidOperationException("BotFrameworkOptions must be configured
prior to setting up the state accessors");
var conversationState =
options.State.OfType<ConversationState>().FirstOrDefault()
?? throw new
InvalidOperationException("ConversationState が ConfigureServices で設
定されていません。");
var userState =
options.State.OfType<UserState>().FirstOrDefault()
12. ?? throw new
InvalidOperationException("UserState が ConfigureServices で設定されてい
ません。");
var accessors = new
SampleBotAccessors(conversationState, userState)
{
ConversationDialogState =
conversationState.CreateProperty<DialogState>(nameof(DialogState)),
UserProfile =
userState.CreateProperty<UserProfile>(nameof(UserProfile)),
};
return accessors;
});
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
app.UseDefaultFiles()
.UseStaticFiles()
.UseBotFramework();
}
}
}
6. Go back to SampleBot.cs added the following code with comment and
Waterfallsteps.
//Added: Part where code is added
//Updated: Changing parts
13. using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace HandsonBot.SampleBot
{
public class SampleBot : IBot
{
private const string WelcomeText = "Welcome to Sample Bot";
private readonly ILogger _logger;
private readonly SampleBotAccessors _accessors; // Added
private readonly DialogSet _dialogs; // Added
public SampleBot(SampleBotAccessors accessors, ILoggerFactory
loggerFactory)
{
_accessors = accessors ?? throw new
ArgumentException(nameof(accessors));
_dialogs = new DialogSet(accessors.ConversationDialogState);
var waterfallSteps = new WaterfallStep[]
{
ConfirmAgeStepAsync,
ExecuteAgeStepAsync,
ExecuteFinalConfirmStepAsync,
ExecuteSummaryStepAsync,
};
_dialogs.Add(new TextPrompt("name", ValidateHandleNameAsync));
_dialogs.Add(new ConfirmPrompt("confirm"));
_dialogs.Add(new NumberPrompt<int>("age"));
_dialogs.Add(new WaterfallDialog("details", waterfallSteps));
_logger = loggerFactory.CreateLogger<SampleBot>();
_logger.LogInformation("Start SampleBot");
}
private async Task GetHandleNameAsync(DialogContext dialogContext,
DialogTurnResult dialogTurnResult, UserProfile userProfile,
CancellationToken cancellationToken)
{
if (dialogTurnResult.Status is DialogTurnStatus.Empty)
{
await dialogContext.PromptAsync(
"name",
new PromptOptions
{
Prompt = MessageFactory.Text("Please tell me your
handle name first."),
RetryPrompt = MessageFactory.Text("The handle name
must be at least 3 words long."),
},
cancellationToken);
14. }
// If you enter a handle name
else if (dialogTurnResult.Status is DialogTurnStatus.Complete)
{
if (dialogTurnResult.Result != null)
{
// Register your handle name with UserState
userProfile.HandleName =
(string)dialogTurnResult.Result;
await dialogContext.BeginDialogAsync("details", null,
cancellationToken); // added
}
}
}
private Task<bool>
ValidateHandleNameAsync(PromptValidatorContext<string> promptContext,
CancellationToken cancellationToken)
{
var result = promptContext.Recognized.Value;
if (result != null && result.Length >= 3)
{
var upperValue = result.ToUpperInvariant();
promptContext.Recognized.Value = upperValue;
return Task.FromResult(true);
}
return Task.FromResult(false);
}
public async Task OnTurnAsync(ITurnContext turnContext,
CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
// We will exchange normal messages here.
await SendMessageActivityAsync(turnContext,
cancellationToken); // updated
}
else if (turnContext.Activity.Type ==
ActivityTypes.ConversationUpdate)
{
await SendWelcomeMessageAsync(turnContext,
cancellationToken);
}
else
{
_logger.LogInformation($"passed:{turnContext.Activity.Type}");
}
await
_accessors.ConversationState.SaveChangesAsync(turnContext, false,
cancellationToken);
await _accessors.UserState.SaveChangesAsync(turnContext, false,
cancellationToken);
}
15. private static async Task SendWelcomeMessageAsync(ITurnContext
turnContext, CancellationToken cancellationToken)
{
foreach (var member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(WelcomeText,
cancellationToken: cancellationToken);
}
}
}
public async Task SendMessageActivityAsync(ITurnContext
turnContext, CancellationToken cancellationToken)
{
var dialogContext = await
_dialogs.CreateContextAsync(turnContext, cancellationToken);
var dialogTurnResult = await
dialogContext.ContinueDialogAsync(cancellationToken);
var userProfile = await
_accessors.UserProfile.GetAsync(turnContext, () => new UserProfile(),
cancellationToken);
// If the handle name is not registered in UserState
if (userProfile.HandleName == null)
{
await GetHandleNameAsync(dialogContext, dialogTurnResult,
userProfile, cancellationToken);
}
// If you have a handle name registered with UserState
else
{
// added
if (dialogTurnResult.Status == DialogTurnStatus.Empty)
{
await dialogContext.BeginDialogAsync("details", null,
cancellationToken);
}
}
}
//----------------------------------------------
//Lab
private async Task<DialogTurnResult>
ConfirmAgeStepAsync(WaterfallStepContext stepContext, CancellationToken
cancellationToken)
{
var userProfile = await
_accessors.UserProfile.GetAsync(stepContext.Context, () => new
UserProfile(), cancellationToken);
return await stepContext.PromptAsync(
"confirm",
new PromptOptions
{
Prompt = MessageFactory.Text($"{userProfile.HandleName}
May I ask your age?"),
16. RetryPrompt = MessageFactory.Text("Answer yes or No."),
},
cancellationToken);
}
private async Task<DialogTurnResult>
ExecuteAgeStepAsync(WaterfallStepContext stepContext, CancellationToken
cancellationToken)
{
if ((bool)stepContext.Result)
{
return await stepContext.PromptAsync(
"age",
new PromptOptions
{
Prompt = MessageFactory.Text("What is your age?"),
RetryPrompt = MessageFactory.Text("Enter the age in
numbers."),
},
cancellationToken);
}
else
{
return await stepContext.NextAsync(-1, cancellationToken);
}
}
private async Task<DialogTurnResult>
ExecuteFinalConfirmStepAsync(WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
var userProfile = await
_accessors.UserProfile.GetAsync(stepContext.Context, () => new
UserProfile(), cancellationToken);
userProfile.Age = (int)stepContext.Result;
var message = GetAgeAcceptedMessage(userProfile);
await stepContext.Context.SendActivityAsync(message,
cancellationToken);
return await stepContext.PromptAsync(
"confirm",
new PromptOptions { Prompt = MessageFactory.Text("Is this
the registration information you want?") },
cancellationToken);
}
private static IActivity GetAgeAcceptedMessage(UserProfile
userProfile)
{
return MessageFactory.Text(userProfile.Age == -1 ? "Age is
private, isn't it?" : $"I'm {userProfile.Age} year old.");
}
private async Task<DialogTurnResult>
ExecuteSummaryStepAsync(WaterfallStepContext stepContext, CancellationToken
cancellationToken)
{
if ((bool)stepContext.Result)
{
17. var userProfile = await
_accessors.UserProfile.GetAsync(stepContext.Context, () => new
UserProfile(), cancellationToken);
var summaryMessages = GetSummaryMessages(userProfile);
await
stepContext.Context.SendActivitiesAsync(summaryMessages,
cancellationToken);
// End of Detail dialog
return await stepContext.EndDialogAsync(cancellationToken:
cancellationToken);
}
else
{
// Redo the Details dialog.
await
stepContext.Context.SendActivityAsync(MessageFactory.Text("I will visit you
again."), cancellationToken);
return await stepContext.ReplaceDialogAsync("details",
cancellationToken: cancellationToken);
}
}
private static IActivity[] GetSummaryMessages(UserProfile
userProfile)
{
IActivity summaryMessage = MessageFactory.Text(userProfile.Age
== -1
? $"{userProfile.HandleName} Your age is private."
: $"{userProfile.HandleName} , {userProfile.Age} year
old.");
IActivity thanksMessage = MessageFactory.Text("Thank you for
your input.");
return new[] { summaryMessage, thanksMessage };
}
//---------------------------
}
}
18. Chapter 5: Implementation Age Property
1. Go to UserProfile.cs , implement Age Property as shown below.
namespace HandsonBot.SampleBot
{
public class UserProfile
{
public string HandleName { get; set; }
public int Age { get; set; }
}
}
2. Debug your application again.
Happy Coding !!!