This document discusses exception handling in C# programming. It explains that exceptions are errors or unexpected problems that occur during program execution. Exceptions can be handled using try-catch blocks to allow programs to continue running even if errors occur. The document provides examples of throwing exceptions and catching them using try-catch blocks. It also discusses how components and libraries can be built in C# using the /t compiler option to specify the output type.
The document discusses exceptions in Java. It defines exceptions as problems that occur during runtime. Checked exceptions must be caught or propagated, while unchecked exceptions extend RuntimeException and do not require catching. Finally blocks ensure code is executed whether or not an exception occurs. Try/catch blocks allow catching specific exceptions, while finally ensures cleanup code runs.
The original Creative JavaScript tutorial, covering loops in JavaScript. This tutorial is aimed at creative people with no programming experience who are interested to learn loops JavaScript.
The document discusses using marble diagrams and marble tests to help understand and test asynchronous code using RxJS Observables. Marble diagrams can depict the output of multiple asynchronous observables over time. Marble tests use mocked observables expressed as marbles to simulate time and test how operators work. Examples are provided of using marble tests to test an Angular component that loads random spoilers and an Angular service that retrieves spoilers from a REST API.
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
[80% OFF Udemy Coupon]. Learn Modern JavaScript Essentials Quickly and save $40 today! with "Quick Course: JavaScript Essentials in 1 Hour (2018). Only $9.99!!
https://www.udemy.com/quick-course-javascript-essentials-in-1-hour-2018/?couponCode=HEM313A
JavaScript Loop: Optimization of Weak TypingJanlay Wu
This document discusses JavaScript loop optimization and the difference in performance between i++ and i-- loops. It shows that i++ and i-- have similar performance in modern browsers. To better measure the performance, it defines test functions that run the loops 10,000 times with 1,000,000 iterations each. The results show minor differences between browsers but no clear winner between i++ and i--. It also discusses the differences between strong/weak and static/dynamic typing in JavaScript compared to languages like C/Java.
This document discusses building hermetic systems without Docker. It defines hermetic systems as airtight and pure, with well-defined inputs and outputs. It discusses sources of non-determinism like external libraries and services that can introduce "leaks". It proposes using Clojure components and embedding services like Elasticsearch to build deterministic, reproducible systems. Components are reusable units with well-defined dependencies and lifecycles. Embedding services isolates the system from external changes. Randomness and time can also introduce non-determinism but may be modeled as reproducible services. The goal is to evaluate systems, identify leaks, and design trade-offs to build robust, hermetic systems.
The document discusses exceptions in Java. It defines exceptions as problems that occur during runtime. Checked exceptions must be caught or propagated, while unchecked exceptions extend RuntimeException and do not require catching. Finally blocks ensure code is executed whether or not an exception occurs. Try/catch blocks allow catching specific exceptions, while finally ensures cleanup code runs.
The original Creative JavaScript tutorial, covering loops in JavaScript. This tutorial is aimed at creative people with no programming experience who are interested to learn loops JavaScript.
The document discusses using marble diagrams and marble tests to help understand and test asynchronous code using RxJS Observables. Marble diagrams can depict the output of multiple asynchronous observables over time. Marble tests use mocked observables expressed as marbles to simulate time and test how operators work. Examples are provided of using marble tests to test an Angular component that loads random spoilers and an Angular service that retrieves spoilers from a REST API.
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
[80% OFF Udemy Coupon]. Learn Modern JavaScript Essentials Quickly and save $40 today! with "Quick Course: JavaScript Essentials in 1 Hour (2018). Only $9.99!!
https://www.udemy.com/quick-course-javascript-essentials-in-1-hour-2018/?couponCode=HEM313A
JavaScript Loop: Optimization of Weak TypingJanlay Wu
This document discusses JavaScript loop optimization and the difference in performance between i++ and i-- loops. It shows that i++ and i-- have similar performance in modern browsers. To better measure the performance, it defines test functions that run the loops 10,000 times with 1,000,000 iterations each. The results show minor differences between browsers but no clear winner between i++ and i--. It also discusses the differences between strong/weak and static/dynamic typing in JavaScript compared to languages like C/Java.
This document discusses building hermetic systems without Docker. It defines hermetic systems as airtight and pure, with well-defined inputs and outputs. It discusses sources of non-determinism like external libraries and services that can introduce "leaks". It proposes using Clojure components and embedding services like Elasticsearch to build deterministic, reproducible systems. Components are reusable units with well-defined dependencies and lifecycles. Embedding services isolates the system from external changes. Randomness and time can also introduce non-determinism but may be modeled as reproducible services. The goal is to evaluate systems, identify leaks, and design trade-offs to build robust, hermetic systems.
Ember applications are built around an MVC model that prescribes Models, Views, Controllers, and Routes for managing persistence, DOM, application state, and URLs. In an ambitious enough app, that model may fail to cover the whole problem space. Fear not, for in this presentation you will learn how to use Ember’s container and dependency features to move beyond MVC, as well as learning how they tie Ember internals together.
Video: http://www.youtube.com/watch?v=iCZUKFNXA0k&feature=youtu.be&t=1h45m59s
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
The document discusses using Javassist, a Java bytecode engineering library, to dynamically generate Java proxies at runtime. It provides examples of using Javassist with a Java agent to transform class files and generate proxies within a ClassFileTransformer. It also summarizes how Javassist is used within the JRebel application reload agent to refresh configurations and notify plugins of class reloading.
The document discusses various looping constructs in Java including for, while, do-while loops as well as decision making statements like if, if-else, switch. It provides the syntax and examples of each. The key loops covered are for, which allows looping a specific number of times, while which checks a condition before running the loop body, and do-while which runs the body at least once. The document also discusses break and continue keywords that can be used within loops. For decision making, it explains if, if-else-if-else for multiple conditions, and switch for equality checks. Nested if statements are also covered.
Loops play an essential role in software development, and they are used to iterate through the arrays or other elements that are iterable. In Javascript, we have a few different types of loops. It sometimes can be confusing which loop we should use in a particular case and which one will be the best in case of our performance. In this article, I’m going to compare the loops in Javascript, describe their pros and cons, test the speed of each of them.
This document discusses JavaScript control statements (loops). It covers the increment and decrement operators, for loops, while loops, and examples of each. The increment operator (i++) increments a variable by 1, and the decrement operator (i--) decrements a variable by 1. A for loop allows initializing a counter variable, testing a condition, and incrementing/decrementing on each iteration. A while loop runs a code block repeatedly as long as a condition is true. Examples demonstrate looping through arrays and incrementing/decrementing variables with for and while loops.
Clean code via dependency injection + guiceJordi Gerona
The document discusses various code smells related to dependency injection and constructor usage, such as constructors doing real work instead of just setting fields, digging into collaborator objects instead of using their interfaces, and relying on global state and singletons. It provides examples of these code smells and proposes fixes using dependency injection and interfaces to make the code more testable and flexible.
Using FakeItEasy allows creating fake objects to use in tests. It is a .NET dynamic fake framework that provides a fluent interface to define fake object behavior and assertions. FakeItEasy fakes objects by creating derived classes, so only virtual, abstract, and interface methods can be faked. It handles default behavior and parameter handling to reduce test code. Dependency injection helps pass fake objects to production code under test.
This document summarizes techniques for writing iterative and parameterized tests in Kotlin using the Spock and Spek testing frameworks. It discusses generating test data, tokenizing test names, nested and tabular iteration, mocking with Mockito, test class hierarchies (TCKs), and proposes diagrammed assertions to visualize test failures. The final section announces an upcoming Bay Area Kotlin User Group meetup on Netflix engineering tools and Kotlin Spring Cloud extensions.
Strict mode helps catch errors and prevents actions that are confusing or unsafe. It is enabled by adding "use strict" to the top of a script or function. Strict mode changes JavaScript behavior by converting mistakes into errors, simplifying variable and function scoping, and securing JavaScript. While strict mode is useful for catching errors, it is important to test code thoroughly when mixing strict and non-strict code before using in production.
Jasmine is a BDD framework for testing JavaScript code. It does not depend on other frameworks and does not require a DOM. Jasmine uses specs, expectations, suites, and matchers to define tests and make assertions. It also supports features for testing asynchronous code and spying on functions. Jasmine provides tools like spies, stubs, fakes, and mocks to help test code behavior.
The document discusses key concepts about JavaScript including:
- JavaScript was created in 10 days by Brendan Eich.
- It is loosely typed, weakly typed, and forgiving with syntax like optional semicolons.
- Variables can contain different types and operations between types perform conversions.
- Conditionals should always use triple equals (===) for comparisons.
- Type conversions occur behind the scenes which can lead to unexpected results.
- Scopes determine where variables are stored and found, with inner scopes having access to outer scopes.
As a guest speaker in NCU, I gave this second talk about some more advanced practices of JavaScript programming. It summarised our experience learned from developing Mozilla/Gaia project, including the way to deal with asynchronous code flow with the event-driven model.
The document summarizes the results of re-analyzing the Umbraco codebase with the PVS-Studio static code analyzer one year after its initial analysis. The re-analysis found several new bugs and issues not present in the previous year, indicating that the Umbraco developers addressed the prior year's findings but new errors were introduced with ongoing development. Several interesting new bugs are described involving potential null reference exceptions, off-by-one errors with substring indexing, and incorrect format string usage. Overall the analysis found the code quality to be improved compared to the previous year.
An overview how to realize code generation of languages on the JVM that implement other class layouts than the Java programming languages. As an example, the inline-mock-maker for Mockito is discussed which supports languages like Kotlin that make any property final by default.
Throttle and Debounce Patterns in Web AppsAlmir Filho
A brief discussion on the Throttle and Debounce Patterns. Where, when and why to use them? They solve some problems that may harm the performance of an entire web app due to misuse of user events.
Con-FESS 2015 - Having Fun With JavassistAnton Arhipov
This document discusses using Javassist, a bytecode manipulation library, for tasks like adding logging to existing code without modifying the source code. It provides examples of using Javassist to inject logging into a method and creating a Java agent to manipulate bytecode. The document also summarizes how Javassist works under the hood to modify class files and how frameworks like JRebel use it to reload configurations without restarts.
One of the most important benefits of automated testing is to ensure a fast and safe code refactoring to evolve our system architecture. The main problem is how to write tests that are easy to write, easy to follow and not time consuming during development nor execution time. In this session, we are going to explore some powerful Java testing libraries that will help you write better (unit) tests focusing on the main Unicorns architecture challenges such as validating microservices endpoints, remote calls to other microservices or just asynchronous/reactive code.
This document discusses using SystemVerilog processes to control concurrent threads. It describes how to fork multiple processes, get handles to each process object, wait for specific processes to complete, and kill processes conditionally based on the status of other processes. An example is provided that forks 5 processes, waits for process 4 to complete, and kills process 2 if it is still running when process 4 finishes.
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
The document describes embedding Ring code in Ring programs without sharing state. It allows quick integration of Ring programs and applications together without conflicts by executing Ring code in isolated environments. Functions like ring_state_init(), ring_state_runcode(), and ring_state_delete() are used to initialize a state, run code in it, and delete it. This prevents variables from one state being accessible from another. Serial execution of Ring applications is also demonstrated using ring_state_main().
This document summarizes key aspects of C# programming, including:
1. C# programs can be split across multiple files, and the compiler does not care if code is in one or many files. File extensions matter to programmers, not compilers.
2. Characters are stored as numbers using ASCII or Unicode encoding schemes. The char data type represents characters.
3. Comments are lines of code ignored by the compiler that provide documentation for programmers.
4. Preprocessor directives like #define, #if, #else control code inclusion/exclusion before compilation. This allows conditional compilation.
The document discusses namespaces in C# and how they help organize code. It begins by explaining that Console is a class in the System namespace, so Console.WriteLine refers to the WriteLine method of the Console class. It then discusses how namespaces help avoid naming collisions and allow logical grouping of classes. Key points include:
- Namespaces are used to logically group related classes and avoid name clashes
- Classes can be organized into hierarchical namespaces (e.g. namespace1.namespace2.Class)
- The using directive allows omitting namespaces when referring to classes
- Classes provide useful functions, so related functions are grouped into classes within namespaces
Ember applications are built around an MVC model that prescribes Models, Views, Controllers, and Routes for managing persistence, DOM, application state, and URLs. In an ambitious enough app, that model may fail to cover the whole problem space. Fear not, for in this presentation you will learn how to use Ember’s container and dependency features to move beyond MVC, as well as learning how they tie Ember internals together.
Video: http://www.youtube.com/watch?v=iCZUKFNXA0k&feature=youtu.be&t=1h45m59s
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
The document discusses using Javassist, a Java bytecode engineering library, to dynamically generate Java proxies at runtime. It provides examples of using Javassist with a Java agent to transform class files and generate proxies within a ClassFileTransformer. It also summarizes how Javassist is used within the JRebel application reload agent to refresh configurations and notify plugins of class reloading.
The document discusses various looping constructs in Java including for, while, do-while loops as well as decision making statements like if, if-else, switch. It provides the syntax and examples of each. The key loops covered are for, which allows looping a specific number of times, while which checks a condition before running the loop body, and do-while which runs the body at least once. The document also discusses break and continue keywords that can be used within loops. For decision making, it explains if, if-else-if-else for multiple conditions, and switch for equality checks. Nested if statements are also covered.
Loops play an essential role in software development, and they are used to iterate through the arrays or other elements that are iterable. In Javascript, we have a few different types of loops. It sometimes can be confusing which loop we should use in a particular case and which one will be the best in case of our performance. In this article, I’m going to compare the loops in Javascript, describe their pros and cons, test the speed of each of them.
This document discusses JavaScript control statements (loops). It covers the increment and decrement operators, for loops, while loops, and examples of each. The increment operator (i++) increments a variable by 1, and the decrement operator (i--) decrements a variable by 1. A for loop allows initializing a counter variable, testing a condition, and incrementing/decrementing on each iteration. A while loop runs a code block repeatedly as long as a condition is true. Examples demonstrate looping through arrays and incrementing/decrementing variables with for and while loops.
Clean code via dependency injection + guiceJordi Gerona
The document discusses various code smells related to dependency injection and constructor usage, such as constructors doing real work instead of just setting fields, digging into collaborator objects instead of using their interfaces, and relying on global state and singletons. It provides examples of these code smells and proposes fixes using dependency injection and interfaces to make the code more testable and flexible.
Using FakeItEasy allows creating fake objects to use in tests. It is a .NET dynamic fake framework that provides a fluent interface to define fake object behavior and assertions. FakeItEasy fakes objects by creating derived classes, so only virtual, abstract, and interface methods can be faked. It handles default behavior and parameter handling to reduce test code. Dependency injection helps pass fake objects to production code under test.
This document summarizes techniques for writing iterative and parameterized tests in Kotlin using the Spock and Spek testing frameworks. It discusses generating test data, tokenizing test names, nested and tabular iteration, mocking with Mockito, test class hierarchies (TCKs), and proposes diagrammed assertions to visualize test failures. The final section announces an upcoming Bay Area Kotlin User Group meetup on Netflix engineering tools and Kotlin Spring Cloud extensions.
Strict mode helps catch errors and prevents actions that are confusing or unsafe. It is enabled by adding "use strict" to the top of a script or function. Strict mode changes JavaScript behavior by converting mistakes into errors, simplifying variable and function scoping, and securing JavaScript. While strict mode is useful for catching errors, it is important to test code thoroughly when mixing strict and non-strict code before using in production.
Jasmine is a BDD framework for testing JavaScript code. It does not depend on other frameworks and does not require a DOM. Jasmine uses specs, expectations, suites, and matchers to define tests and make assertions. It also supports features for testing asynchronous code and spying on functions. Jasmine provides tools like spies, stubs, fakes, and mocks to help test code behavior.
The document discusses key concepts about JavaScript including:
- JavaScript was created in 10 days by Brendan Eich.
- It is loosely typed, weakly typed, and forgiving with syntax like optional semicolons.
- Variables can contain different types and operations between types perform conversions.
- Conditionals should always use triple equals (===) for comparisons.
- Type conversions occur behind the scenes which can lead to unexpected results.
- Scopes determine where variables are stored and found, with inner scopes having access to outer scopes.
As a guest speaker in NCU, I gave this second talk about some more advanced practices of JavaScript programming. It summarised our experience learned from developing Mozilla/Gaia project, including the way to deal with asynchronous code flow with the event-driven model.
The document summarizes the results of re-analyzing the Umbraco codebase with the PVS-Studio static code analyzer one year after its initial analysis. The re-analysis found several new bugs and issues not present in the previous year, indicating that the Umbraco developers addressed the prior year's findings but new errors were introduced with ongoing development. Several interesting new bugs are described involving potential null reference exceptions, off-by-one errors with substring indexing, and incorrect format string usage. Overall the analysis found the code quality to be improved compared to the previous year.
An overview how to realize code generation of languages on the JVM that implement other class layouts than the Java programming languages. As an example, the inline-mock-maker for Mockito is discussed which supports languages like Kotlin that make any property final by default.
Throttle and Debounce Patterns in Web AppsAlmir Filho
A brief discussion on the Throttle and Debounce Patterns. Where, when and why to use them? They solve some problems that may harm the performance of an entire web app due to misuse of user events.
Con-FESS 2015 - Having Fun With JavassistAnton Arhipov
This document discusses using Javassist, a bytecode manipulation library, for tasks like adding logging to existing code without modifying the source code. It provides examples of using Javassist to inject logging into a method and creating a Java agent to manipulate bytecode. The document also summarizes how Javassist works under the hood to modify class files and how frameworks like JRebel use it to reload configurations without restarts.
One of the most important benefits of automated testing is to ensure a fast and safe code refactoring to evolve our system architecture. The main problem is how to write tests that are easy to write, easy to follow and not time consuming during development nor execution time. In this session, we are going to explore some powerful Java testing libraries that will help you write better (unit) tests focusing on the main Unicorns architecture challenges such as validating microservices endpoints, remote calls to other microservices or just asynchronous/reactive code.
This document discusses using SystemVerilog processes to control concurrent threads. It describes how to fork multiple processes, get handles to each process object, wait for specific processes to complete, and kill processes conditionally based on the status of other processes. An example is provided that forks 5 processes, waits for process 4 to complete, and kills process 2 if it is still running when process 4 finishes.
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
The document describes embedding Ring code in Ring programs without sharing state. It allows quick integration of Ring programs and applications together without conflicts by executing Ring code in isolated environments. Functions like ring_state_init(), ring_state_runcode(), and ring_state_delete() are used to initialize a state, run code in it, and delete it. This prevents variables from one state being accessible from another. Serial execution of Ring applications is also demonstrated using ring_state_main().
This document summarizes key aspects of C# programming, including:
1. C# programs can be split across multiple files, and the compiler does not care if code is in one or many files. File extensions matter to programmers, not compilers.
2. Characters are stored as numbers using ASCII or Unicode encoding schemes. The char data type represents characters.
3. Comments are lines of code ignored by the compiler that provide documentation for programmers.
4. Preprocessor directives like #define, #if, #else control code inclusion/exclusion before compilation. This allows conditional compilation.
The document discusses namespaces in C# and how they help organize code. It begins by explaining that Console is a class in the System namespace, so Console.WriteLine refers to the WriteLine method of the Console class. It then discusses how namespaces help avoid naming collisions and allow logical grouping of classes. Key points include:
- Namespaces are used to logically group related classes and avoid name clashes
- Classes can be organized into hierarchical namespaces (e.g. namespace1.namespace2.Class)
- The using directive allows omitting namespaces when referring to classes
- Classes provide useful functions, so related functions are grouped into classes within namespaces
Exception handling in C# involves using try, catch, and finally blocks. The try block contains code that might throw exceptions, the catch block handles any exceptions, and finally contains cleanup code. There are different types of exceptions like OutOfMemoryException and DivideByZeroException. Exceptions can be handled by showing error messages, logging exceptions, or throwing custom exceptions for business rule violations.
This document discusses exception handling in Java. It defines exceptions as errors that occur during runtime and explains how Java uses try, catch, throw, throws and finally keywords to handle exceptions. try blocks contain code that can throw exceptions. catch blocks catch specific exception types. throw manually throws exceptions. throws declares which exceptions a method can throw. finally ensures code is always executed after a try block. The document provides examples of handling different exception types, nested try blocks, and rethrowing exceptions.
This document provides an overview of exception handling in Java. It defines what exceptions are, which are errors that disrupt normal program flow. There are three main types of exceptions: checked exceptions that must be declared, unchecked exceptions that do not need to be declared, and errors. The try-catch block is used to handle exceptions, with catch blocks specifying the exception types to handle. Finally blocks will execute regardless of whether an exception occurred or not and are used for cleanup code. Custom exceptions can also be created by extending the Exception class.
OCJP Samples Questions: Exceptions and assertionsHari kiran G
The document contains sample questions and explanations for the OCP Java SE 8 exam related to exceptions and assertions. It includes multiple choice questions about exception handling, try-catch blocks, and assertion failures. The explanations provide details about which exceptions would be thrown and the output of code snippets.
This document discusses constructors and destructors in C# classes. It explains that objects must be instantiated using the "new" keyword before their methods can be called. Static methods can be called directly on the class without creating an object instance. Instance variables are unique to each object, while static variables are shared among all objects of a class. The document uses several code examples to demonstrate how to properly create object instances and call both static and instance methods and variables.
An exception is an error condition or unexpected behavior encountered during program execution. Exceptions are handled using try, catch, and finally blocks. The try block contains code that might throw an exception, the catch block handles the exception if it occurs, and the finally block contains cleanup code that always executes. Common .NET exception classes include ArgumentException, NullReferenceException, and IndexOutOfRangeException. Exceptions provide a standard way to handle runtime errors in programs and allow the programmer to define specific behavior in error cases.
We have checked the Windows 8 Driver Samples pack with our analyzer PVS-Studio and found various bugs in its samples. There is nothing horrible about it - bugs can be found everywhere, so the title of this article may sound a bit high-flown. But these particular errors may be really dangerous, as it is a usual practice for developers to use demo samples as a basis for their own projects or borrow code fragments from them.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that arise during runtime and disrupt normal program flow. There are three types of exceptions: checked exceptions which must be declared, unchecked exceptions which do not need to be declared, and errors which are rare and cannot be recovered from. The try, catch, and finally blocks are used to handle exceptions, with catch blocks handling specific exception types and finally blocks containing cleanup code.
One of the programs, which allows you to solve the problem of data compression, is a popular file archiver 7-Zip, which I often use myself. Our readers have long asked us to check the code of this application. Well, it's time to look at its source code, and see what PVS-Studio is able to detect in this application.
Q3 GIVEN THE TREND EQUATION NO OF STUDENTS-3000+200 YEAR BASE: 2003-0
1.INTERPRET EQUATION RESULTS 2.FORECAST FOR 2020 3.WHEN WILL THE NO OF
STUDENTS REACH 6000
Solution
x no of years from 2003 y no of students y = 3000+200x 1) The regression
equation has a positive slope of 200 y intercept is 3000 i.e. no of students in the year 2000
Thus for every year 200 students increase 2) For 2020, x = 17, y = 3000+200(17) = 6400
3) When y =6000, 6000 = 3000+200x or x = 15 Hence in year 2018 students reach 6000
B Regression C D. All the above.
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
The document discusses searching source code comments for indications of hidden errors. The author wrote a utility to search C/C++ files for "suspicious" comments containing words like "fuck", "bug", or "stupid". While many lines were found, few revealed actual errors. Two examples are presented where comments hinted at misunderstandings in the code. The method did not find new error patterns, but provided experience investigating alternative defect detection methods. The author plans to improve the utility and continue the research.
Exception Handling In Java Presentation. 2024kashyapneha2809
Exception handling in Java allows programs to handle errors and unexpected conditions gracefully. There are three main types of exceptions: checked exceptions which must be declared, unchecked exceptions which do not need to be declared, and errors which are usually unrecoverable. The try/catch block is used to catch exceptions, with catch blocks handling specific exception types. Finally blocks contain cleanup code and are always executed regardless of exceptions. Methods can declare exceptions they may throw using the throws keyword. Programmers can also create custom exception classes.
in this tutorial we will discuss about
exception handling in C#
Exception class
creating user-defined exception
throw keyword
finally keyword
with examples'
Peter Lawrey is the CEO of Chronicle Software. He has 7 years experience working as a Java developer for investment banks and trading firms. Chronicle Software helps companies migrate to high performance Java code and was involved in one of the first large Java 8 projects in production in December 2014. The company offers workshops, training, consulting and custom development services. The talk will cover reading and writing lambdas, capturing vs non-capturing lambdas, transforming imperative code to streams, mixing imperative and functional code, and taking Q&A.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that arise during runtime due to errors. It describes different types of exceptions like compile-time errors and runtime errors. It explains how to handle exceptions using try, catch, throw, throws and finally keywords. Try blocks contain code that may generate exceptions. Catch blocks catch specific exception types. Finally blocks contain cleanup code that always executes whether an exception occurs or not. The document provides examples to demonstrate exception handling concepts in Java.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
1) The document discusses collection classes in C# and how to implement a class to be used in a foreach loop.
2) A class needs to implement the IEnumerator interface and include methods like GetEnumerator(), MoveNext(), Reset(), and Current.
3) An example class xxx is implemented that iterates through an array, tracking the index with a variable i. It returns strings from the array on each MoveNext() call until i equals the array length.
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.
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 is a table of contents for a guide on C# basics. It lists the sections and chapters that will be covered in the guide, including getting started, namespaces, constructors, components, databases, function overloading, inheritance, modifiers, virtual functions, properties, interfaces, structures, operator overloading, collection objects, attributes, and unsafe code. The guide is split into two main sections that cover the fundamentals and then more advanced topics.
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.
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.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive function. Exercise causes chemical changes in the brain that may help protect against mental illness and improve symptoms.
The document discusses access modifiers in C# classes. It explains that by default, class members are private and can only be accessed within the class. The public modifier allows any code to access the member. The protected modifier allows access from derived classes only. The internal modifier allows access within the same assembly only. Access modifiers control the visibility and accessibility of classes, members, and nested types.
This document discusses properties in C#. It explains that properties are made up of getter and setter methods rather than being stored in memory like variables. Properties allow executing code when getting or setting a value. The document provides examples of creating properties with getters only, setters only, and both getters and setters. It also discusses errors that can occur, such as not having any accessors, having multiple definitions for the same property name, or having a property and variable with the same name. The document explains that properties can be static like variables.
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.
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 for those who already suffer from conditions like depression and anxiety.
The document provides an introduction to getting started with C# programming. It discusses creating a directory to save C# files, naming a file with the ".cs" extension, adding a main method as the program entry point, and using semicolons to terminate statements. The summary hits errors encountered along the way such as missing the main method and semicolons.
The document provides an overview and summary of key features of C# classes, including:
- Class declaration syntax and default access levels
- Constructors and initializing fields
- Static and readonly fields
- Value and reference parameters
- Arrays as reference types that can be initialized with shorthand syntax
It also briefly discusses the System.Array base class and how to safely access elements in multi-dimensional arrays.
This document provides an overview and introduction to C# programming fundamentals such as value types, enums, parameters, control flow, structs, constructors, fields, operators, indexers and properties. It covers basic C# concepts like variables and data types, expressions, operators, flow control, and methods. Examples are provided to demonstrate key features like value types versus reference types, literals, and integer and floating point operators. The document is intended to help readers learn the basics of C# syntax and programming.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
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
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
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
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
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).
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on integration of Salesforce with Bonterra Impact Management.
Interested in deploying an integration with Salesforce for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
1. Components and Database Handling - C# The Basics - Beta2 Page 1 of 17
4
Components and Database
Handling
Exception Handling
Failing to prepare is preparing to fail. Ergo, one is constantly planning and preparing for the future. We often
set a path for ourselves and try to follow it steadily. But then life intervenes. Uncertainties in life result in
unforeseen situations. These are like exceptions in the normal course that we set for ourselves. Similarly,
when you write programs, unforeseen problems may arise during its normal path of execution.
These unforeseen problems are nothing but an euphemism for errors. Just as in life, in the programming
world, these errors can be further classified into Fatal errors and Non-Fatal errors. A Fatal error is an error that
brings the program to a grinding halt. A Non-Fatal error is an error that allows your program to run but with
limited capacity. This can be exemplified by the following.
Let's assume you have a card that is not of a high resolution. Accordingly, your browser displays your page in
a lower resolution. Now, technically, that is an error but it is not a Fatal one. However, if you didn't have a
graphics card at all then it would be a Fatal error. Thus, we may also call an unforeseen problem or error an
Exception. In other words, therefore, the word Exception is used almost synonymously with the word Error.
Earlier, the problem was that we never centralized error handling. Let's assume you have to open three files.
Each time you open a file you have to check whether an error occurred or not. So you have to conduct that
check for every file. Since there are three files, it would mean repeating the same error check thrice. That is
surely a waste of time. Or you could be calling two functions and checking for the same error in both the
functions. One reason that programmers don't write error-handling routines is that they get tired of the
mundane task. It is the same thing repeated over and over again.
Let's consider constructors. Before the constructor gets called, the object has not yet been created. So you ask
the constructor to create an object, to allocate memory and create a file. Now, if it can't do so, how will the
constructor return to tell you that an error occurred! Today constructors carry a lot of code within them and if
you haven't forgotten, constructors cannot return values.
Because of the various reasons discussed above, we don't talk about errors any more; we handle exceptions.
Bearing this in mind let's understand the next program.
a.cs
class zzz
{
public static void Main()
{
yyy a;
a=new yyy();
a.abc();
System.Console.WriteLine(quot;Byequot;);
}
}
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
2. Components and Database Handling - C# The Basics - Beta2 Page 2 of 17
class yyy
{
public void abc()
{
throw new System.Exception();
System.Console.WriteLine(quot;abcquot;);
}
}
Compiler Warning
a.cs(16,1): warning CS0162: Unreachable code detected
Output
Unhandled Exception: System.Exception: Exception of type System.Exception was thrown
at yyy.abc()
at zzz.Main()
Here, a.abc calls the function abc in class yyy. System.Console.WriteLine is used to display 'Bye'. It is of
significance to note that when you run this program the System.Console.WriteLine does not get called. Hence
the word 'Bye' is not displayed. Within the abc function we have a line that says throw new System.Exception
(); The word new indicates that we are creating an object. We are creating an object that looks like
System.Exception. 'throw' is a reserved word, that means it is recognized by C#. Exception is a class in the
System namespace. In other words, we are identifying an exception, creating an object of it, and throwing it.
Then we have a WriteLine statement for printing 'abc'. Note that neither 'Bye' nor 'abc' gets displayed. A
Message Box may appear for debugging the applicaition. Since we are still at the learning stage, we click on
the No button.
The warning says that when you use the 'throw' keyword in your code, no lines of code get called after that.
Since the function abc is throwing an exception no code after the throw in abc will get executed. The throw
acts like the return statement. Everything comes to a stand still! And we get an error at runtime and not at the
time of running the compiler; indicating where the exception occurred. Also no code gets called after function
abc gets called as it throws an exception.
Explicitly declaring exceptions tells the compiler that a particular problem might occur. When the problem
does occur, an exception is thrown; the next step being to catch the exception. Let's see how we can
accomplish this. In our program, the function abc throws an exception. We will now catch the exception.
a.cs
class zzz
{
public static void Main()
{
yyy a;
a=new yyy();
try
{
a.abc();
System.Console.WriteLine(quot;Byequot;);
}
catch (System.Exception e)
{
System.Console.WriteLine(quot;In Exceptionquot;+ e.ToString());
}
System.Console.WriteLine(quot;After Exceptionquot;);
}
}
class yyy {
public void abc()
{
throw new System.Exception();
System.Console.WriteLine(quot;abcquot;);
}
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
3. Components and Database Handling - C# The Basics - Beta2 Page 3 of 17
}
Output
In ExceptionSystem.Exception: Exception of type System.Exception was thrown.
at yyy.abc()
at zzz.Main()
After Exception
Catching exceptions is done within 'try-catch' blocks. Therefore, the code for abc is included within a 'try-
catch' block. a.abc - the function that throws the exception - is included within the try-catch block . The abc
function throws an exception by using the keyword throw. There is no other way of throwing an exception. At
this point all code is skipped in function abc as well as the in the try block and the control moves to the catch
block. As such, neither 'abc' nor 'bye' gets displayed.
Within the catch we have a parameter 'e' that looks like System.Exception. The object e has a method called
ToString. ToString is a very handy function. It tells you where exactly the exception occurred and in which
function, function within function. So, System.Console.Writeline will display the string 'In Exception' along
with the exception.
After the code contained in the catch block is executed, the remaining code after the end of the try - catch
block will be executed. Hence, WriteLine will display 'After Exception'. That means the program will not
come to a stand still, it resumes execution after the catch and not after the function which threw the exception.
If you give a return statement immediately after the catch block, as we have given in the next program, the
program will stop execution there itself. Hence, in this case, 'After Exception' will not be displayed as shown
below.
a.cs
class zzz
{
public static void Main()
{
yyy a;
a=new yyy();
try
{
a.abc();
System.Console.WriteLine(quot;Byequot;);
}
catch (System.Exception e)
{
System.Console.WriteLine(quot;In Exceptionquot;+ e.ToString());
return;
}
System.Console.WriteLine(quot;After Exceptionquot;);
}
}
class yyy
{
public void abc()
{
throw new System.Exception();
System.Console.WriteLine(quot;abcquot;);
}
}
Output
In ExceptionSystem.Exception: Exception of type System.Exception was thrown.
at yyy.abc()
at zzz.Main()
Each time that abc gets called an exception is thrown. But you may not want that to happen. Hence, exception
handling is normally included in an if statement and if an error condition takes place.
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
4. Components and Database Handling - C# The Basics - Beta2 Page 4 of 17
A 'try-catch' block can include a number of functions and whenever an exception occurs for any one of them,
we will catch it. By doing so we are synchronizing all the code to handle errors at one place. Constructors can
also throw exceptions.
Building Components
a.cs
public class zzz {
public void abc() {
System.Console.WriteLine(quot;zzz abcquot;);
}
}
The above program consists of a simple class zzz with one public function. The class has also been tagged
with the modifier public that makes it accessible to everyone. When we run the command csc a.cs, we are
asking the C# compiler to create an executable file for us even though we did not explicitly ask it to. An
executable file will always be created by the C# compiler unless you override it by stating an option to the C#
compiler. Let us start with the /t option.
csc /t:library a.cs
You could use /t or /target. This option specifies what type of output file the compiler should create for you. If
you do not specify a /t option on the command line, C# by default writes /t:exe for you thereby creating an
executable file. The long form of /t is /target and depending upon the time of day, choose the appropriate one.
Not all options have a long and a short form like /t does. The : after the option is mandatory. Then we write
the type of executable output file we want. Library means a dll. When we run the dir command we see a file
named a.dll in the current sub directory. A file with a .dll or a .exe extension are called Windows PE files.
This is the default file format that Windows uses to create executable files. There is a minor difference
between the internal structures of a dll and a exe file. Which is that a dll cannot be executed like an exe
program can. By convention dlls' are used to store code even though an exe could have also be used. What we
have done is created a component.
What if we wanted to change the name of the output file. By default it is the name of our program. Then we
must use the /out option as follows.
csc /t:library /out:bbb.dll a.cs
This will create a file bbb.dll instead of a.dll as earlier. Whether we use the /out option or not, C# does it for
us. If the C# program was called a.cs, then C# wrote /out:a.exe on the command line for us. We can use
the /out option to change the name of the output file. /out does not have a short form /o.
Remember C# uses defaults for command line options to make life easier for us.
Note that we have created a component in a file bbb.dll
a.cs
class yyy
{
public static void Main()
{
zzz a;
}
}
Compiler error
a.cs(5,1): error CS0246: The type or namespace name 'zzz' could not be found (are you missing a
using directive or an assembly reference?)
The only reason we create a component is to allow other programs to call code from it. In the above program,
we are saying that a looks like a class zzz. The C# compiler is telling us in a vague way that it does not know
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
5. Components and Database Handling - C# The Basics - Beta2 Page 5 of 17
that zzz is a class. Though we know zzz is a class as we just created it and it is in a file called bbb.dll, C# is
not aware of the same.
a.cs
class yyy {
public static void Main()
{
zzz a;
}
}
>csc a.cs /r:bbb.dll
Compiler Warning
a.cs(5,5): warning CS0168: The variable 'a' is declared but never used
The /r or reference option tells the C# compiler to look at bbb.dll; in this case for the code of classes it is not
aware of. In our case the error disappears as the file bbb.dll contains the code for the class bbb.dll. Thus in
future, if the C# compiler ever gives you the above error, do not panic. All that you need to do is specify
which dll contains the code for the classes. The help available along with C#, tells you every class and the dll
that contains the code of the class.
a.cs
class yyy
{
public static void Main()
{
zzz a = new zzz();
a.abc();
}
}
Output
zzz abc
We have successfully called the function abc in class zzz. The code of the class zzz resides in bbb.dll.
a.cs
namespace mukhi
{
public class zzz
{
public void abc()
{
System.Console.WriteLine(quot;zzz abcquot;);
}
}
}
>csc /t:library /out:bbb.dll a.cs
The same class zzz is now enclosed in a namespace mukhi and the component recreated.
a.cs
class yyy
{
public static void Main()
{
zzz a = new zzz();
a.abc();
}
}
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
6. Components and Database Handling - C# The Basics - Beta2 Page 6 of 17
csc a.cs /r:bbb.dll
Compiler Error
a.cs(5,1): error CS0246: The type or namespace name 'zzz' could not be found (are you missing a
using directive or an assembly reference?)
a.cs(6,1): error CS0246: The type or namespace name 'a' could not be found (are you missing a
using directive or an assembly reference?)
The error results as the name of the class is not zzz but mukhi.zzz.
a.cs
using mukhi;
class yyy {
public static void Main()
{
zzz a = new zzz();
a.abc();
}
}
Output
zzz abc
All's well that ends well.
Databases
Databases are centralized stores of data. In a database, information from several files (also known as tables) is
accessed, coordinated and operated upon as if in a single file. Thus, the database organizes data independently
from the programs that access it. Large volumes of data are stored in a database.
Computer programs have little meaning when written in isolation. Therefore, it is of importance to have our
programs work with databases. Databases work under the control of a database management system. SQL
Server is an RDBMS; it is one such database management system.
Before we can write programs that communicate with databases we need to have a database. One of the
simplest databases to use is Microsoft Access. As a large number of people use it, we have based our
examples on it. However you could use any RDBMS like Oracle, SQL Server as you wish.
First and foremost, before we can access a database and perform various operations, we need to connect to the
database. Assuming you want to speak to your friend over the phone, you dial your friend's phone number. Its
only when you connect to your friends phone that the both of you can speak to each other. Similarly, if we
want to use a database we first have to connect to it and only then can we speak to it.
a.cs
class zzz
{
public static void Main()
{
System.Data.OleDb.OleDbConnection s;
}}
Compiler warning
a.cs(5,35): warning CS0168: The variable 's' is declared but never used
Let's see how we can connect to a database.
a.cs
class zzz
{
public static void Main()
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
7. Components and Database Handling - C# The Basics - Beta2 Page 7 of 17
{
try
{
System.Data.OleDb.OleDbConnection s;
s = new System.Data.OleDb.OleDbConnection();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
hell
Within the try block we have an object s that looks like System.Data.OleDb.OleDbConnection. You are
already aware that System is a namespace, but what about Data and OleDb? Well, System.Data.OleDb is the
name of the namespace. We can liken this to an earlier example where we created a namespace mukhi.vijay.
Hierarchy in a namespace can go to absurd lengths! The help on C# states that System.Data.OleDb is the
name of a namespace and OleDbConnection is a class within that namespace. By saying s =
System.Data.OleDb.OleDbConnection(); we are creating the object s. When you run this program all that we
see is the word hell, which means that the constructor threw no Exception. If it did then the catch block would
have been executed.
a.cs
class zzz
{
public static void Main()
{
try
{
System.Data.OleDb.OleDbConnection s;
s = new System.Data.OleDb.OleDbConnection();
s.Open();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
System.InvalidOperationException: The ConnectionString property has not been initialized.
at System.Data.OleDb.OleDbConnection.Open()
at zzz.Main()
The class OleDbConnection has a function called Open which opens or connects to our database. When we
run the above the above program, the Open function throws an exception. Now, at this point you must catch
the Exception. The ToString within the catch block displays the Exception message. The error says that the
ConnectionString property has not been initialized.
The reason an exception occurred is that we did not provide certain mandatory information whilst creating the
object. We did not indicate the location of the database server that we want to connect to or the database. It's
like picking up the phone and not dialing a number. How in the world do you expect to connect then!
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
8. Components and Database Handling - C# The Basics - Beta2 Page 8 of 17
We will now provide the constructor with some basic information.
a.cs
class zzz
{
public static void Main()
{
try
{
System.Data.OleDb.OleDbConnection s;
s = new System.Data.OleDb.OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdb;quot;);
s.Open();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
System.Data.OleDb.OleDbException: Could not find file 'c:zzz.mdb'. at
System.Data.OleDb.OleDbConnection.ProcessResults(Int32 hr)
at System.Data.OleDb.OleDbConnection.InitializeProvider()
at System.Data.OleDb.OleDbConnection.Open()
at zzz.Main()
We first specify the database provider as Provider=Microsoft.Jet.OLEDB.4.0, which stands for MS-Access
and then the path as Data Source=c:zzz.mdb separated by semicolon.
When you run the program, an OleDbException is thrown, which says could not find file 'c:zzz.mdb'. This is
because we have not created an MSAccess DataBase called zzz.mdb.
An mdb file stores data from multiple tables. In this file zzz.mdb, create one table abc with 2 fields f1 and f2 ,
both of type text. Add two records to this database. The first record will contain 1,a1 and the second record
will be 2,a2.
Re run the program which now displays hell unlike before where we generated an Exception.
Output
hell
s.Open opens a connection to the database. The 'Provider' and 'Data Source' given in the constructor identify
the database.
As we have given the constructor all the mandatory information, s.Open() will open a connection with the
Access database. The program executes smoothly and once the connection is established WriteLine displays
'hell'.
Now that we have established a connection with the database, let's see how we can communicate with it. More
specifically, let's see how we can execute an SQL command.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
9. Components and Database Handling - C# The Basics - Beta2 Page 9 of 17
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;Create Table a1 ( vno integer , name char(10))quot;,s);
c.ExecuteNonQuery();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
hell
Employing using, we do not have to preface every class with the namespace System.Data.OleDb. The
purpose of this program is to execute an SQL statement. SQL is a short form for Structured Query Language.
It is not a computer programming language like C# but rather a language like English. SQL understands
certain words like Create, which create a table for us in our database. SQL has nothing to do with Oracle or
Access, it works with all the RDBMSs of the world.
Create Table a1 (vno integer, name char(10))
The above SQL statement means that a table called a1 will be created in our database. It will have 2 fields vno
and name. Vno will store numbers and name will store characters subject to a maximum of 10.
A class in any programming language is made up of a collection of variables and functions. These put
together do something for us like solving a particular problem or accomplishing a certain task. We live in a
world of specialization. Just like it is difficult to come across one human being who is a PHD in Nuclear
Science as well as Sociology, classes too are written to focus on one particular task only.
Thus we need one class to handle our connection to a database and another class which understands SQL. We
first create an object that looks like an OleDbConnection, which understands how to connect to a database
using a string attributes 'Provider' and 'Data Source', which it passes as a parameter to the constructor. Then
we create an object c which looks like OleDbCommand as this class understands SQL. The constructor gets
called with 2 parameters, the SQL statement and also the connection object. Thus the object c now comprises
the necessary information regarding the command we want to execute and the connection. Now,
c.ExecuteNonQuery() will actually execute the SQL statement. ExecuteNonQuery() is a function within the
OleDbCommand class that enables us to execute any SQL command. You will now see the word 'hell'
displayed on your screen.
But did the table get created? Let's find out by starting Access and then choosing the database zzz. Here we
will see the table a1 with 2 fields vno and name but with no data at all. We created our table alright, but it is
empty as it has no data in it! So let's start inserting data/records into the table. Before doing so, Quit out of
Access
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
10. Components and Database Handling - C# The Basics - Beta2 Page 10 of 17
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;insert into a1 values(1,'hi')quot;,s);
c.ExecuteNonQuery();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}}
Output
hell
The only difference between this program and the previous one is that this one uses the Insert SQL command.
Earlier, we created a table zzz, now we are inserting records in zzz. To the constructor of OleDbCommand we
are giving two things - the insert command quot;insert into a1 values(1,'hi')quot; and the connection. Insert into and
values are part of the SQL syntax. A1 is the name of the table in which a fresh record will be added. After
values, we write the data separated by commas. The first field will contain 1 and the second hi. As the second
field has the data type of character, it has to be enclosed in single quotes. c.ExecuteNonQuery as usual
executes the SQL command and as no exception gets thrown ,the word 'hell' gets displayed..
Let's cross check to see if the data has been inserted into zzz by running Access. Aha! It displays the record
that you just inserted in the following format-
vno name
1 hi
Now it follows that if we can insert a record then we should be able to remove it too. The following program
uses the delete command to remove all the records from the table zzz.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;delete from a1quot;,s);
c.ExecuteNonQuery();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e) {
System.Console.WriteLine(e.ToString());
}
}
}
Output
hell
Now c.ExecuteNonQuery will execute the delete command. This command deletes all the data from the table.
In Access we will see an empty table. This proves that the delete command was successful!
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
11. Components and Database Handling - C# The Basics - Beta2 Page 11 of 17
Apart from inserting and deleting data another operation that is commonly performed is updating data.
However, you must have data in your table to update it. Our table is empty right now, so let's execute the
insert program once again. You will now have one record in your table zzz. After inserting a record, change
the sql insert command to an update command. This is shown below.
c= new OleDbCommand(quot;update a1 set vno=3,name='bad' where vno=1quot;,s);
Here, we are giving an update statement and our connection to the object is 'c'. The update statement will
change the vno and name to the values specified. It will do so for any record that has vno=1. We have only
one record in our table and it meets this criteria. Now, go back to Access , you will find that the record has
been updated as follows-
vno name
3 bad
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;delete from a11quot;,s);
c.ExecuteNonQuery();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
System.Data.OleDb.OleDbException: The Microsoft Jet database engine cannot find the input table
or query 'a11'. Make sure it exists and that its name is spelled correctly.
at System.Data.OleDb.OleDbCommand.ExecuteCommand
TextErrorHandling(Int32 hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommand
TextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.
ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.
ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.
ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at zzz.Main()
Don't worry, we have simulated this error on purpose. The table a11 does not exist in our database. Thus an
exception got thrown by ExecuteCommandText and not ExecuteNonQuery as seen above. What it means is
that ExecuteNonQuery calls Execute which calls ExecuteCommand which finally calls
ExecuteCommandText. Also the word hell does not get displayed because of the exception thrown.
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
12. Components and Database Handling - C# The Basics - Beta2 Page 12 of 17
We will now execute a simple select statement.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
OleDbDataReader r;
r = c.ExecuteReader();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
hell
We have executed different SQL commands through our earlier programs. We will now try and execute an
SQL select statement. In order to do so, we have given the following select statement to the constructor along
with the connection- 'Select * from abc'. Abc is a table in the database called zzz . Remember, c looks like
OleDbCommand. 'Select' is part of the SQL syntax like insert , update . 'from' is also a reserved word . 'abc' is
the name of the table created earlier in Access and populated by data keyed in by us. The '*' means all fields
in the table. We could have also replaced the * with a comma separating list of field names that we were
interested in.
As OleDbConnection has an Open function, OleDbCommand has a ExecuteReader function. This function
returns an object that looks like OleDbDataReader.
The function ExecuteReader will create an object that looks like OleDbDataReader and initialize r to it. No
exception was thrown, which meant no errors from our side.
What we need to do now is retrieve data from the abc table. The abc table may have ten fields and twenty
records. So we use what is called a 'dataset'. In other words, how do we access data contained in multiple rows
and multiple columns through our program? For example, when we run the select statement it gives us the
data in rows and columns. How can we achieve this through our program? To do that we now need a third
object which looks like OleDbDataReader.
We can almost feel your dismay - Oh no! Another object! Well, there is a very good reason why you need to
have three different objects. Firstly, you need an object that understands a connection. Then you need another
object that understands an SQL statement. This is because somebody has to execute that statement. You now
need a third object that will let you read/retrieve data. That is why we have 'r' an object that looks like
OleDbDataReader. Thereafter, we have c.ExecuteReader. Earlier we used a function call ExecuteNonQuery.
This is because in case of an insert, update or delete we didn't want any data to be retrieved, we didn't want an
answer back!!
As a recap, we are using r to store the value return by ExecuteReader. That means r will be filled up by
ExecuteReader. On executing this program only 'hell' is displayed.
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
13. Components and Database Handling - C# The Basics - Beta2 Page 13 of 17
Now that we have the filled up r, let's see how we can display the data.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
OleDbDataReader r;
r = c.ExecuteReader();
System.Console.WriteLine(quot;{0},{1}quot;,r.GetValue(0),r.GetValue(1));
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
System.InvalidOperationException: No data exists for the row/column.
at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal)
at zzz.Main()
Run this program. Expect the unexpected....an error! The error says 'No data exists for the row/column' But
didn't the function Execute fill up r? It did, but it did not position the record pointer on the first record. A
record pointer is an abstract concept. To start with it appears just before the first record. The function
GetValue will return the value of the fields depending upon where the record pointer is. At the start it is just
before the first record. So r can be also looked at as an array that contains all the fields. We get an error
because we need to read the data into our array first. In order to read data into the fields we must give r.Read.
Without r.Read, the records will not be read into the array, so also the record pointer will not be moved
forward to the first record.
Now that we know the reason why the error occurred let's rectify it by doing the needful. Let's add r.Read() to
our program.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
14. Components and Database Handling - C# The Basics - Beta2 Page 14 of 17
OleDbDataReader r;
r = c.ExecuteReader();
System.Console.WriteLine(r.Read());
System.Console.WriteLine(quot;{0},{1}quot;,r.GetValue(0),r.GetValue(1));
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
True
1,a1
Now that we have added r.Read() the program executes as advertised. r.Read() returns true. Thereafter, the
GetValue() function which needs the field number as a parameter retrieves the data associated with the first
and second column. Remember in C# we start counting from zero and hence zero as a parameter to GetValue
will retrieve the value of field one in the table. The datatype of the first field is numeric and of the second
character. However, the function GetValue does not seem to care.
Read returns true if more data is available to read and false if it is at the last record. Also read positions the
record pointer to the next record.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
OleDbDataReader r;
r = c.ExecuteReader();
while (r.Read())
System.Console.WriteLine(quot;{0},{1}quot;,r.GetValue(0),r.GetValue(1));
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
1,a1
2,a2
(A display of only the first two fields of all the records in the table. )
But now we want to display all the data in the fields. So we are using Read in a loop. while(r.Read()). r.Read()
returns true as long as it can read data. The while loop continues till the condition is true. We are using our
trusted function WriteLine to display the data of the first and second field. Thus the moment r.Read() cannot
read more data it returns false and the while loop terminates. Now all the data in the two fields is displayed
and as such we have a long list of data displayed. To verify further, add some more fields and records to abc.
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
15. Components and Database Handling - C# The Basics - Beta2 Page 15 of 17
Just as we mind our manners in daily life we must do so in programming too. It is a good practice to shut the
door when leaving a room. Similarly, in programs we must close what ever we opened.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
OleDbDataReader r;
r = c.ExecuteReader();
while (r.Read())
System.Console.WriteLine(quot;{0},{1}quot;,r.GetValue(0),r.GetValue(1));
r.Close();
s.Close();
System.Console.WriteLine(quot;hellquot;);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
1,a1
2,a2
We will mind our manners and give r.Close() and s.Close. Note that it is not mandatory to do so. First we are
closing r and then we are closing s i.e. the connection that we opened.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
OleDbDataReader r;
r = c.ExecuteReader();
System.Console.WriteLine(r.FieldCount);
for ( int i = 0 ; i < r.FieldCount ; i++)
System.Console.WriteLine(r.GetName(i));
}
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
16. Components and Database Handling - C# The Basics - Beta2 Page 16 of 17
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
2
f1
f2
An OleDbDataReader has a useful function called FieldCount which tells you how many fields the SQL
statement contained. In our case abc has two fields. We have one more function GetName which will tell us
the name of the function in the table given the field number. Thus r.GetName(1) will give us the name of the
2nd field. In the for statement, the variable i starts at zero. The condition becomes false when the value of i is
one less than r.FieldCount which in this case is 2 i.e. i will take values of 0 and 1. The reason being i starts
from zero as GetName understands zero as the first field. Thus we can now print all the column names using
the for. Now lets print the entire table irrespective of the number of columns or the number of rows.
a.cs
using System.Data.OleDb;
class zzz
{
public static void Main()
{
try
{
OleDbConnection s;
s = new OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:zzz.mdbquot;);
s.Open();
OleDbCommand c;
c=new OleDbCommand(quot;select * from abcquot;,s);
OleDbDataReader r;
r = c.ExecuteReader();
while ( r.Read() )
{
for ( int i = 0 ; i < r.FieldCount ; i++)
System.Console.Write(r.GetValue(i)+quot; quot;);
System.Console.WriteLine();
}
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
Output
1 a1
2 a2
You can modify abc to add more fields and fill in more records. Execute the program and see the
change in output. Whenever we do not know better, we use a for or a while i.e. a looping construct.
However we do not know two things. One, the numbers of rows in the table and two the number of
columns. The first while takes care of the number of rows and the for, the variable number of
columns. Thus the above program will work for any number of columns and rows in the table. All
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007
17. Components and Database Handling - C# The Basics - Beta2 Page 17 of 17
that we do is change the select statement. The difference between Write and WriteLine is that Write
does not add an enter at the end like WriteLine does. Also + is used to join two strings together. We
are adding a space at the end of every field as a separator.
file://E:!KrarCSharpcsharpthebasicschap4.htm 9/29/2007