Here are the key points about .NET:
- .NET is a software development platform from Microsoft that runs primarily on Windows. It introduces a new virtual machine called the Common Language Runtime (CLR) which compiles code into an intermediate language (IL) that can be executed on any operating system that supports .NET.
- Major languages supported include C#, Visual Basic .NET, and C++/CLI. These compile to IL rather than native machine code.
- The .NET Framework provides a large class library called Framework Class Library (FCL) which includes functionality for common tasks like database access, XML, networking, graphics etc.
- Major versions include 1.0 (released 2002), 1.1 (
This document provides a summary of 75 SQL interview questions organized into different sections. It begins with 20 basic SQL questions, followed by 30 more complex SQL query questions and 15 advanced SQL questions. The final section contains 10 PL/SQL interview questions. The questions cover a wide range of SQL topics including data definition language statements, data manipulation language, joins, aggregates, views, stored procedures and more. The detailed answers explain key SQL concepts and provide code examples to help interview candidates demonstrate their SQL skills.
This document describes a micro project to create a simple Oracle database to store course enrollment data for a university. It involves designing tables to model student, class, enrollment and other data; populating the tables with sample data; writing SQL queries to retrieve and analyze the data; and creating PL/SQL functions and procedures to generate reports on departments, students, and faculty. Key tasks include creating tables with primary keys and foreign keys, inserting records, writing queries to retrieve aggregated data on departments and their faculty/students, creating views to display related data, and procedures to output formatted reports.
FOR MORE CLASSES VISIT
www.cis336.com
CIS 336 Final Exam
Question 1. 1. (TCO 1) A DBMS performs several important functions that guarantee the integrity and consistency of the data in the database. Which of the following is NOT one of those functions?
The document discusses SQL database concepts including:
- The SQL data definition language allows specification of schemas, integrity constraints, and other metadata.
- Relations are defined using CREATE TABLE statements which specify attributes and their data types.
- Basic queries use SELECT, FROM, and WHERE clauses to retrieve and filter tuples from one or more relations.
- Integrity constraints like PRIMARY KEY and NOT NULL can be defined to enforce data validity.
- SQL supports operations like JOIN, aggregation, sorting, and more.
This document outlines the contents of a manual for a database management systems laboratory course. It covers 5 chapters on different lab programs involving creating database tables, inserting data, and writing queries. Chapter 1 provides an introduction to basic SQL commands including DDL, DML, TCL, and DCL commands. It describes commands like CREATE TABLE, ALTER TABLE, DROP TABLE, SELECT, INSERT, UPDATE, DELETE. Subsequent chapters provide the problem statements, ER diagrams, schema diagrams, code for creating tables and inserting sample data, and solutions to queries for 5 different database domains - library, orders, movies, college, and company.
The document discusses various methods for retrieving data from a SQL database, including using SELECT statements to select columns and rows, the WHERE clause to filter results, LIKE to match strings, DISTINCT to remove duplicates, GROUP BY to group results, and ORDER BY to sort results.
MySQL optimization involves understanding the entire system to be optimized. The query optimizer attempts to determine the most efficient way to execute a query by considering possible query plans. Key aspects of optimization include data types and schema design, indexing, and query optimization. Smaller data types, simpler schemas, and indexes on commonly used columns can improve performance.
This document provides a summary of 75 SQL interview questions organized into different sections. It begins with 20 basic SQL questions, followed by 30 more complex SQL query questions and 15 advanced SQL questions. The final section contains 10 PL/SQL interview questions. The questions cover a wide range of SQL topics including data definition language statements, data manipulation language, joins, aggregates, views, stored procedures and more. The detailed answers explain key SQL concepts and provide code examples to help interview candidates demonstrate their SQL skills.
This document describes a micro project to create a simple Oracle database to store course enrollment data for a university. It involves designing tables to model student, class, enrollment and other data; populating the tables with sample data; writing SQL queries to retrieve and analyze the data; and creating PL/SQL functions and procedures to generate reports on departments, students, and faculty. Key tasks include creating tables with primary keys and foreign keys, inserting records, writing queries to retrieve aggregated data on departments and their faculty/students, creating views to display related data, and procedures to output formatted reports.
FOR MORE CLASSES VISIT
www.cis336.com
CIS 336 Final Exam
Question 1. 1. (TCO 1) A DBMS performs several important functions that guarantee the integrity and consistency of the data in the database. Which of the following is NOT one of those functions?
The document discusses SQL database concepts including:
- The SQL data definition language allows specification of schemas, integrity constraints, and other metadata.
- Relations are defined using CREATE TABLE statements which specify attributes and their data types.
- Basic queries use SELECT, FROM, and WHERE clauses to retrieve and filter tuples from one or more relations.
- Integrity constraints like PRIMARY KEY and NOT NULL can be defined to enforce data validity.
- SQL supports operations like JOIN, aggregation, sorting, and more.
This document outlines the contents of a manual for a database management systems laboratory course. It covers 5 chapters on different lab programs involving creating database tables, inserting data, and writing queries. Chapter 1 provides an introduction to basic SQL commands including DDL, DML, TCL, and DCL commands. It describes commands like CREATE TABLE, ALTER TABLE, DROP TABLE, SELECT, INSERT, UPDATE, DELETE. Subsequent chapters provide the problem statements, ER diagrams, schema diagrams, code for creating tables and inserting sample data, and solutions to queries for 5 different database domains - library, orders, movies, college, and company.
The document discusses various methods for retrieving data from a SQL database, including using SELECT statements to select columns and rows, the WHERE clause to filter results, LIKE to match strings, DISTINCT to remove duplicates, GROUP BY to group results, and ORDER BY to sort results.
MySQL optimization involves understanding the entire system to be optimized. The query optimizer attempts to determine the most efficient way to execute a query by considering possible query plans. Key aspects of optimization include data types and schema design, indexing, and query optimization. Smaller data types, simpler schemas, and indexes on commonly used columns can improve performance.
This document provides information about SQL queries and joins. It begins by introducing SQL (Structured Query Language) which is used to communicate with databases and retrieve required information. It describes the basic CRUD (Create, Read, Update, Delete) functions of SQL. It then discusses different types of SQL queries - aggregate function queries, scalar function queries, and join queries. It provides the syntax and explanation of inner joins, outer joins (left, right, full) which are used to query data from multiple tables based on relationships between columns. The document is presented by Hammad, Bilal and Awais.
This document defines SQL data definition statements and basic SQL query structure. It discusses DDL statements like CREATE, ALTER, and DROP that are used to define and manage database structures. It also explains the typical components of an SQL query including the SELECT, FROM, and WHERE clauses. Finally, it outlines several set operations in SQL like UNION, UNION ALL, INTERSECT, and MINUS.
The document summarizes topics that will be covered in an advanced SQL training seminar, including SQL statement types, data types, aggregate functions, NULL handling, comparison operators, mathematical functions, joins, subqueries, views, materialized views, inline views, and optimizing SQL queries. Techniques for data sharing between databases are also mentioned. The seminar aims to provide in-depth knowledge of SQL concepts through explanations, examples, exercises and discussion.
A foreign key is a column that references the primary key of another table. It must match a value in the referenced primary key. Unlike primary keys, foreign keys can contain null values. Primary keys uniquely identify rows in a table, while foreign keys reference primary keys to link data between tables.
The document provides an introduction to MySQL and relational database management systems. It discusses what a database and RDBMS are, common RDBMS terminology like tables, columns, rows, keys, and indexes. It also covers how to install and use MySQL, including creating databases and tables, and performing basic CRUD (create, read, update, delete) operations using SQL statements. The document is aimed at getting readers started with the MySQL database system.
Sql Server 2014 Course Content consists Course 20461-Querying Microsoft SQL Server. It discusses editions, versions, tools used to query, documentation sources, and the logical structure of databases.
The document discusses various SQL integrity constraints and authorization commands. It describes primary key, foreign key, not null, check, unique, and default constraints that can be applied during table creation. It also covers the GRANT and REVOKE commands used to manage user permissions to tables. Examples are provided for each constraint and command to illustrate their proper syntax.
This document contains a CIS 336 final exam with multiple choice questions covering database concepts like DBMS functions, relational databases, entity relationship modeling, normalization, SQL, constraints, and security. It begins with a header stating it is the CIS 336 final from April 2019 and provides a website for course tutorials. It then lists 10 multiple choice questions on database topics, followed by another 10 questions, then concludes with a header and 9 additional questions for another final exam.
This document discusses advanced SQL topics including joins, subqueries, and ensuring transaction integrity. It provides examples of different types of joins like equi-joins, natural joins, outer joins, and union joins. It also discusses using subqueries in WHERE clauses, FROM clauses, and HAVING clauses, and differentiates between correlated and noncorrelated subqueries. The document concludes by defining transactions and describing SQL commands like BEGIN TRANSACTION, COMMIT, and ROLLBACK that are used to ensure transaction integrity.
Michael Joseph is giving a presentation on database normalization. He begins by explaining the importance of properly structuring data across database tables and the problems that can arise from poor database design, such as redundancy, inaccuracy, and consistency issues. He then describes database normalization as a process that organizes data to minimize redundancy by decomposing relations and isolating data in separate, well-defined tables connected through relationships. Different levels of normalization are discussed, with third normal form being sufficient for most applications. Examples are provided to illustrate how normalization progresses from first to third normal form. Potential issues with highly normalized databases are also outlined.
a) More SQL: Aggregates - Write queries in SQL using aggregates, grouping and ordering.
b) Nested sub queries and SQL updates: Write queries in SQL using concept of nested sub
queries and SQL update commands.
I am Susan C. I am an Instant DBMS Homework Expert at databasehomeworkhelp.com. I hold a Master’s Degree in Programming, from Leeds, UK. I have been helping students with their homework for the past 9 years. I solve homework related to Instant DBMS.
Visit databasehomeworkhelp.com or email info@databasehomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with Instant DBMS Homework.
The document discusses referential integrity in relational databases. It explains that referential integrity requires primary keys and foreign keys to be consistent, so that foreign keys always match existing primary keys in linked tables. This prevents issues like orphaned records or adding records that reference nonexistent keys. Referential integrity guarantees consistency between linked tables and helps maintain data integrity.
A database is a collection of organized data that can be manipulated and accessed using DBMS. DBMS allows users to interact with databases through data definition, update, retrieval, and administration functions. Some key points covered include that Edgar Codd proposed the relational database model, SQL is the standard language for accessing and updating databases, and normalization organizes data to reduce redundancy and inconsistencies.
The document discusses SQL DML commands like INSERT, UPDATE, and DELETE. It provides the syntax for these commands and examples of how to use them to manipulate data in database tables. Domain types in SQL like CHAR, VARCHAR, INT and DATE are also outlined. The document contains examples of creating tables, inserting data, updating and deleting rows with the DML commands in Oracle SQL.
The physical data model includes tables, columns, relationships, and database properties to implement the logical data model in a database. It considers performance, indexing, storage, and denormalization. The transformation from logical to physical model imposes database rules, referential integrity, and other aspects. DDL scripts are used to create the required database objects like tables, columns, constraints, indexes, sequences, and triggers.
This document provides an introduction to SQL and the Oracle database system. It includes sections on SQL queries, data definition and modification, views, stored procedures and functions using PL/SQL, embedded SQL, integrity constraints, triggers, and database architecture. The document also references additional recommended literature for further learning about Oracle and SQL. It aims to provide a detailed overview of the core concepts for working with Oracle databases using SQL.
This document provides an overview and goals for a book on advanced SQL tips and tricks. It discusses topics covered in the book such as scalar functions, analytic functions, complex subqueries, common table expressions, and XML tricks. The document also provides examples of SQL code snippets demonstrating various techniques, including finding values containing percentages, combining values into a single row, correlating vs simple subqueries, and using common table expressions.
This document discusses key concepts in database management systems including:
1. It defines schema, sub-schema, instances, entities, attributes, and domains.
2. It explains different types of attributes such as simple, composite, single-valued, multi-valued, and derived attributes with examples.
3. It discusses mapping constraints including one-to-one, one-to-many, many-to-one, and many-to-many relationships and provides examples.
Collections of CS Multiple Choice QuestionsShusil Baral
Here are the collections of sets of Multiple Choice Questions -MCQ of the different subjects related to Computer Science or Information Technology along with the answer of each question below the questions set. It may help for the preparation of your exams, tests or interviews.
Previous question papers of Database Management System (DBMS) By SHABEEBShabeeb Shabi
The document discusses different data models used to design databases, including hierarchical, network, and relational models. It also covers SQL constraints like NOT NULL, UNIQUE, PRIMARY KEY, DEFAULT and CHECK. Additionally, it defines the differences between a database schema and instance, advantages of views, different types of keys, and the purpose and uses of normalization, GROUP BY, and HAVING clauses.
This document provides information about SQL queries and joins. It begins by introducing SQL (Structured Query Language) which is used to communicate with databases and retrieve required information. It describes the basic CRUD (Create, Read, Update, Delete) functions of SQL. It then discusses different types of SQL queries - aggregate function queries, scalar function queries, and join queries. It provides the syntax and explanation of inner joins, outer joins (left, right, full) which are used to query data from multiple tables based on relationships between columns. The document is presented by Hammad, Bilal and Awais.
This document defines SQL data definition statements and basic SQL query structure. It discusses DDL statements like CREATE, ALTER, and DROP that are used to define and manage database structures. It also explains the typical components of an SQL query including the SELECT, FROM, and WHERE clauses. Finally, it outlines several set operations in SQL like UNION, UNION ALL, INTERSECT, and MINUS.
The document summarizes topics that will be covered in an advanced SQL training seminar, including SQL statement types, data types, aggregate functions, NULL handling, comparison operators, mathematical functions, joins, subqueries, views, materialized views, inline views, and optimizing SQL queries. Techniques for data sharing between databases are also mentioned. The seminar aims to provide in-depth knowledge of SQL concepts through explanations, examples, exercises and discussion.
A foreign key is a column that references the primary key of another table. It must match a value in the referenced primary key. Unlike primary keys, foreign keys can contain null values. Primary keys uniquely identify rows in a table, while foreign keys reference primary keys to link data between tables.
The document provides an introduction to MySQL and relational database management systems. It discusses what a database and RDBMS are, common RDBMS terminology like tables, columns, rows, keys, and indexes. It also covers how to install and use MySQL, including creating databases and tables, and performing basic CRUD (create, read, update, delete) operations using SQL statements. The document is aimed at getting readers started with the MySQL database system.
Sql Server 2014 Course Content consists Course 20461-Querying Microsoft SQL Server. It discusses editions, versions, tools used to query, documentation sources, and the logical structure of databases.
The document discusses various SQL integrity constraints and authorization commands. It describes primary key, foreign key, not null, check, unique, and default constraints that can be applied during table creation. It also covers the GRANT and REVOKE commands used to manage user permissions to tables. Examples are provided for each constraint and command to illustrate their proper syntax.
This document contains a CIS 336 final exam with multiple choice questions covering database concepts like DBMS functions, relational databases, entity relationship modeling, normalization, SQL, constraints, and security. It begins with a header stating it is the CIS 336 final from April 2019 and provides a website for course tutorials. It then lists 10 multiple choice questions on database topics, followed by another 10 questions, then concludes with a header and 9 additional questions for another final exam.
This document discusses advanced SQL topics including joins, subqueries, and ensuring transaction integrity. It provides examples of different types of joins like equi-joins, natural joins, outer joins, and union joins. It also discusses using subqueries in WHERE clauses, FROM clauses, and HAVING clauses, and differentiates between correlated and noncorrelated subqueries. The document concludes by defining transactions and describing SQL commands like BEGIN TRANSACTION, COMMIT, and ROLLBACK that are used to ensure transaction integrity.
Michael Joseph is giving a presentation on database normalization. He begins by explaining the importance of properly structuring data across database tables and the problems that can arise from poor database design, such as redundancy, inaccuracy, and consistency issues. He then describes database normalization as a process that organizes data to minimize redundancy by decomposing relations and isolating data in separate, well-defined tables connected through relationships. Different levels of normalization are discussed, with third normal form being sufficient for most applications. Examples are provided to illustrate how normalization progresses from first to third normal form. Potential issues with highly normalized databases are also outlined.
a) More SQL: Aggregates - Write queries in SQL using aggregates, grouping and ordering.
b) Nested sub queries and SQL updates: Write queries in SQL using concept of nested sub
queries and SQL update commands.
I am Susan C. I am an Instant DBMS Homework Expert at databasehomeworkhelp.com. I hold a Master’s Degree in Programming, from Leeds, UK. I have been helping students with their homework for the past 9 years. I solve homework related to Instant DBMS.
Visit databasehomeworkhelp.com or email info@databasehomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with Instant DBMS Homework.
The document discusses referential integrity in relational databases. It explains that referential integrity requires primary keys and foreign keys to be consistent, so that foreign keys always match existing primary keys in linked tables. This prevents issues like orphaned records or adding records that reference nonexistent keys. Referential integrity guarantees consistency between linked tables and helps maintain data integrity.
A database is a collection of organized data that can be manipulated and accessed using DBMS. DBMS allows users to interact with databases through data definition, update, retrieval, and administration functions. Some key points covered include that Edgar Codd proposed the relational database model, SQL is the standard language for accessing and updating databases, and normalization organizes data to reduce redundancy and inconsistencies.
The document discusses SQL DML commands like INSERT, UPDATE, and DELETE. It provides the syntax for these commands and examples of how to use them to manipulate data in database tables. Domain types in SQL like CHAR, VARCHAR, INT and DATE are also outlined. The document contains examples of creating tables, inserting data, updating and deleting rows with the DML commands in Oracle SQL.
The physical data model includes tables, columns, relationships, and database properties to implement the logical data model in a database. It considers performance, indexing, storage, and denormalization. The transformation from logical to physical model imposes database rules, referential integrity, and other aspects. DDL scripts are used to create the required database objects like tables, columns, constraints, indexes, sequences, and triggers.
This document provides an introduction to SQL and the Oracle database system. It includes sections on SQL queries, data definition and modification, views, stored procedures and functions using PL/SQL, embedded SQL, integrity constraints, triggers, and database architecture. The document also references additional recommended literature for further learning about Oracle and SQL. It aims to provide a detailed overview of the core concepts for working with Oracle databases using SQL.
This document provides an overview and goals for a book on advanced SQL tips and tricks. It discusses topics covered in the book such as scalar functions, analytic functions, complex subqueries, common table expressions, and XML tricks. The document also provides examples of SQL code snippets demonstrating various techniques, including finding values containing percentages, combining values into a single row, correlating vs simple subqueries, and using common table expressions.
This document discusses key concepts in database management systems including:
1. It defines schema, sub-schema, instances, entities, attributes, and domains.
2. It explains different types of attributes such as simple, composite, single-valued, multi-valued, and derived attributes with examples.
3. It discusses mapping constraints including one-to-one, one-to-many, many-to-one, and many-to-many relationships and provides examples.
Collections of CS Multiple Choice QuestionsShusil Baral
Here are the collections of sets of Multiple Choice Questions -MCQ of the different subjects related to Computer Science or Information Technology along with the answer of each question below the questions set. It may help for the preparation of your exams, tests or interviews.
Previous question papers of Database Management System (DBMS) By SHABEEBShabeeb Shabi
The document discusses different data models used to design databases, including hierarchical, network, and relational models. It also covers SQL constraints like NOT NULL, UNIQUE, PRIMARY KEY, DEFAULT and CHECK. Additionally, it defines the differences between a database schema and instance, advantages of views, different types of keys, and the purpose and uses of normalization, GROUP BY, and HAVING clauses.
This document contains multiple choice questions and answers about computer networking topics. It is divided into sets with 20 questions each and covers topics like network topologies, protocols, network standards, and network layers. The questions are meant to test knowledge of fundamental concepts in computer networking.
This document contains two sample question papers for an Operating Systems exam for a 4th semester BTech course in IT/CSE. Each paper has three sections - Section A contains 10 short answer questions worth 2 marks each, Section B contains 4 long answer questions worth 5 marks each, and Section C contains 2 long answer questions worth 10 marks each. The questions cover topics like virtual memory, processes, threads, CPU scheduling algorithms, deadlocks, memory management techniques like paging, segmentation, swapping etc.
Here you can find 1000's of Multiple Choice Questions(MCQs) of Database Management System(DBMS) includes the MCQs of fundamental of Database Management System(DBMS), introduction of Database Model, Relational Database Model, Constrants, Relational Algebra, Definition and types of Structured Query Language(SQL), Embedded SQL, Database Normalization (1NF, 2NF, 3NF, BCNF, 4NF, 5NF and DKNF) and Data Storage Devices, Architecture of DBMS and Database Security, Integrity and Quality
This document contains a question bank on various topics in operating systems including:
1. Process synchronization questions focusing on critical section problems, semaphores, and solutions for two processes.
2. Memory management questions on paging and segmentation.
3. Deadlock questions on safe/unsafe states, bankers algorithm, prevention/avoidance strategies, and recovery from deadlocks.
4. CPU scheduling questions on algorithms like FCFS, RR, SJF and characteristics like short term, long term and medium term schedulers.
5. Process management questions on states, control blocks, creation/termination, and interprocess communication.
The questions provided are meant to help students study notes
The document is a final exam for an Operating Systems course taken on January 13, 2013 at Cairo University. It contains 8 multiple choice questions testing concepts related to threads, CPU scheduling, process synchronization, deadlocks, virtual memory, and memory management. The exam covers a range of operating system topics including threads, scheduling algorithms, semaphores, the dining philosophers problem, safety algorithms, logical vs physical addressing, and shared memory.
Operating System Multiple Choice QuestionsShusil Baral
Here you can find 1000's of Multiple Choice Questions(MCQs) of Operating System(OS) includes the MCQs of fundamental of Operating System and core Operating System.
This document contains questions from 5 units on the topic of database management systems. The questions cover a wide range of topics including DBMS architecture, data models, relational algebra, normalization, concurrency control, transaction management, distributed databases, data warehousing, and decision support systems. Specifically, some of the questions ask about ER modeling, functional dependencies, transaction processing, concurrency control protocols, ACID properties, client-server architecture, and OLAP.
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdfSkillCertProExams
• For a full set of 420+ questions. Go to
https://skillcertpro.com/product/oracle-database-administration-i-1z0-082-exam-questions/
• SkillCertPro offers detailed explanations to each question which helps to understand the concepts better.
• It is recommended to score above 85% in SkillCertPro exams before attempting a real exam.
• SkillCertPro updates exam questions every 2 weeks.
• You will get life time access and life time free updates
• SkillCertPro assures 100% pass guarantee in first attempt.
Database questions and answers document containing:
1. SQL queries for fetching data from tables using SELECT and WHERE clauses.
2. Joins to retrieve data from multiple tables using SELECT, FROM, and WHERE clauses.
3. Differences between unique key and primary key including allowing null values and number allowed per table.
4. Uses and types of indexes to improve query performance including on single or multiple columns.
5. Purpose and examples of foreign key constraints to maintain referential integrity.
6. Aggregate functions like AVG, COUNT, MAX used in queries.
This document provides 75 SQL interview questions organized into different sections. The first section contains 20 basic SQL questions that cover topics like what SQL is, the NVL function, unique keys vs primary keys, data types, and joins. The second section has 30 complex SQL query questions involving concepts like retrieving the second highest salary or duplicate rows. The third section covers 15 advanced SQL questions about Oracle versions, database environments, sequences, and more.
Database object, sub query, Join Commands & Lab AssignmentArun Sial
The document discusses database objects like tables, views, sequences, synonyms and indexes. It also discusses subqueries and different types of joins like equi joins, non-equi joins, outer joins and self joins. Examples are provided to demonstrate the creation and usage of views, sequences, synonyms and different types of joins. An assignment on these topics is also provided requiring students to create tables, views, sequences and perform various types of joins on sample data.
This document discusses various topics related to enterprise resource planning (ERP) systems and technologies. It defines ERP as business process management software that integrates applications to manage business functions. It describes the typical lifecycle of an ERP implementation project, including pre-evaluation, evaluation, project planning, gap analysis, reengineering, training, testing, and post-implementation. It also discusses ERP-related technologies like business intelligence, supply chain management, and customer relationship management.
The document provides answers to common questions asked in SAS interviews or for SAS certification. Key points:
- The OUTPUT statement overrides automatic output in DATA steps and writes observations only when executed.
- The STOP statement stops processing the current DATA step and resumes after.
- DROP= in the SET statement drops variables from processing, while DROP= in the DATA statement drops them from the output dataset.
- The END= option reads the last observation of a dataset to a new dataset.
Ben Finkel- Using the order by clause.pptxStephenEfange3
The document discusses using the ORDER BY clause in SQL to sort query results. It explains that the ORDER BY clause allows sorting data by one or more columns in ascending or descending order. By default, results are sorted in ascending order but the DESC keyword can be used to specify descending order. Expressions can also be used in the ORDER BY clause to sort by values calculated from multiple columns rather than just existing columns. Aliases can help make column names more readable in ORDER BY clauses containing expressions. The WHERE clause is also discussed as a way to filter query results and limit the number of rows returned.
The document provides answers to common questions asked during SAS interviews or for SAS certification. Key points:
- The OUTPUT statement overrides automatic output in DATA steps and writes observations only when executed.
- The STOP statement stops processing the current DATA step and resumes after.
- There are differences between using the DROP= option in SET vs DATA statements and between reading from an external file vs existing dataset.
- Functions operate across observations while procedures operate within.
The document discusses various components and concepts related to database management systems (DBMS). It defines a database as a collection of related data organized for easy access, management, and updating. It describes the main components of a DBMS as hardware, software, data, procedures, and database access language. It also discusses key DBMS concepts like data definition language, data manipulation language, functions, constraints, and having clause.
A subquery is a SELECT statement embedded within another SQL statement. It allows queries to retrieve data from multiple tables or queries. There are two types of subqueries: single-row and multiple-row. Single-row subqueries return only one row of data and use single-row comparison operators like =. Multiple-row subqueries return more than one row of data and use operators like IN, ANY, ALL that can handle multiple values. Subqueries are useful for solving problems that require performing multiple related queries by nesting one query within another.
This document provides an introduction and tutorial to SQL and the Oracle relational database system. It covers the basics of SQL, including defining and querying tables, modifying data, and more advanced queries using views, joins, and subqueries. It also introduces PL/SQL for database programming and covers other Oracle-specific topics like integrity constraints, triggers, and system architecture. The tutorial is intended to provide a detailed overview of the Oracle database and SQL.
This document provides an introduction and tutorial to SQL and the Oracle relational database system. It covers the basics of SQL, including defining and querying tables, modifying data, and more advanced query techniques. It also discusses additional Oracle topics like PL/SQL, integrity constraints, triggers, and the overall Oracle system architecture. The tutorial is intended to provide a detailed overview of SQL and how to work with Oracle databases.
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
Common table expressions (CTEs) allow users to define temporary result sets within a single SQL statement that can be referenced within that statement, making complex queries easier to read and maintain by breaking them down into simpler components, while subqueries return data from a nested SQL query to filter the results of the outer query. Joins combine data from two or more tables by linking common columns between them and come in various types like inner, left, right, full, and cross joins.
This document provides instructions for completing Project 2 of the CS348 database course. Students are asked to:
1. Create five Oracle database tables based on a given schema using the CREATE statement.
2. Populate the tables with sample data using a provided data.sql file.
3. Write seven SQL queries to answer questions about the data, such as finding the faculty teaching the most classes or students enrolled in the most classes taught by a specific department.
Set operators - derived tables and CTEsSteve Stedman
A free training provided by Steve Stedman and Aaron Buma at Emergency Reporting to prepare for the Microsoft 70-461 SQL Queries exam. This session covers Set Operators, Derived Tables and Common Table Expressions (CTE’s). This is provided free of charge to give back to the SQL community.
SQL Database Performance Tuning for DevelopersBRIJESH KUMAR
1. The document provides SQL performance tuning techniques for developers, including proper use of indexes, avoiding coding loops, and temporary tables.
2. It also discusses how developers and database administrators (DBAs) can work together effectively through improved communication, understanding different roles, and establishing processes for testing and changes.
3. Tips for both parties include being patient, providing database status updates, helping with testing, and planning for future migrations.
The document discusses various database concepts including:
1. DBMS, RDBMS, SQL, fields, records, tables, transactions, locks, normalization, primary keys, foreign keys, joins, views, stored procedures, triggers, and index types are discussed.
2. Key topics covered include the components and functions of a DBMS and RDBMS, the structure and purpose of SQL, database objects like tables and records, ensuring data integrity through transactions and locks, and optimizing database design through normalization.
3. Common operations on data like queries, inserts, updates, and deletes are explained along with advanced topics like views, stored procedures, triggers, and indexes.
evaluation of statistical expression, materialised views, evaluation plansHarsh Kotwani
The document discusses database management systems and how they evaluate statistical expressions, materialized views, and evaluation plans. It discusses how the optimizer checks the data dictionary for table statistics to determine the ideal query evaluation plan. It also explains how different evaluation plans are generated and how the optimizer selects the optimal plan. Finally, it describes how materialized views can improve query performance by pre-computing query results and storing them to reduce accessing large tables each time a query runs. Materialized views must be refreshed when the underlying tables are updated.
The document provides examples of SQL commands for:
1. Selecting data from tables including top rows, random rows, joins, outer joins, and grouping.
2. Creating views and stored procedures.
3. Differences between functions and stored procedures.
4. Using triggers, cursors, and retrieving the second highest/lowest value from a column.
5. Common DDL commands like creating, copying, deleting, and altering tables.
So in summary, it covers the basics of SQL including queries, views, stored procedures, functions, triggers and DDL commands.
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
How to Add Chatter in the odoo 17 ERP ModuleCeline George
In Odoo, the chatter is like a chat tool that helps you work together on records. You can leave notes and track things, making it easier to talk with your team and partners. Inside chatter, all communication history, activity, and changes will be displayed.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
Azure Interview Questions and Answers PDF By ScholarHat
Dbms question
1. ==========================================================================
INFOGAIN
=========
> the infogain paper consists of two papers
> 1. quantitative ability
> 2. technical
>
> quantitative ability paper consists of purly
> numerical questions
> based on profit-loss,time and work,avereges,time and
> distance,speed
> and other such questions based on CAT pattern. I
> advice u to solve
> R.S.Agarwal Quantitative ability questions.Speed
> matters a lot in
> this question paper
>
> technical paper consists of two sections
> 1.c/c++ 30 ques
> 2. dbms 20 ques
> the c/c++ questions were not very tough ....make ur
> concepts strong
> the company lay enphasis on strong dbms concepts so
> study well for
> dbms..for c i advice u to read "test your c skills"
> by Y.K
2. Question: What are the wildcards used for pattern matching.
Answer: _ for single character substitution and % for multi-character substitution.
Question: How can I hide a particular table name of our schema?
Answer: you can hide the table name by creating synonyms.
e.g) you can create a synonym y for table x
create synonym y for x;
Question: When we give SELECT * FROM EMP; How does oracle respond:
Answer: When u give SELECT * FROM EMP;
the server check all the data in the EMP file and it displays the data of the EMP file
Question: What is the use of CASCADE CONSTRAINTS?
Answer: When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.
Question: There are 2 tables, Employee and Department. There are few records in employee table,
for which, the department is not assigned. The output of the query should contain all th
employees names and their corresponding departments, if the department is assigned otherwise
employee names and null value in the place department name. What is the query?
Answer: What you want to use here is called a left outer join with Employee table on the left side.
A left outer join as the name says picks up all the records from the left table and based on the
joint column picks the matching records from the right table and in case there are no matching
records in the right table, it shows null for the selected columns of the right table. E.g. in this
query which uses the key-word LEFT OUTER JOIN. Syntax though varies across databases. In
DB2/UDB it uses the key word LEFT OUTER JOIN, in case of Oracle the connector is
Employee_table.Dept_id *= Dept_table.Dept_id
SQL Server/Sybase :
Employee_table.Dept_id(+) = Dept_table.Dept_id
Question: on index
why u need indexing? Where that is stored
and what u mean by schema object?
For what purpose we are using view
Answer: We can?t create an Index on Index. Index is stored in user_index table. Every object that
has been created on Schema is Schema Object like Table, View etc. If we want to share the
particular data to various users we have to use the virtual table for the Base table...So that is a
view.
Question: How to store directory structure in a database?
Answer: We can do it by the following command: create or replace directory as 'c: tmp'
Question: Why does the following command give a compilation error?
DROP TABLE &TABLE_NAME;
Answer: Variable names should start with an alphabet. Here the table name starts with an '&'
3. symbol.
Question: Difference between VARCHAR and VARCHAR2?
Answer: Varchar means fixed length character data (size) i.e., min size-1 and max-2000
Varchar2 means variable length character data i.e., min-1 to max-4000
Question: Which command displays the SQL command in the SQL buffer, and then executes it
Answer: You set the LIST or L command to get the recent one from SQL Buffer
Question: Which system table contains information on constraints on all the tables created?
Answer: USER_CONSTRAINTS.
Question: How do I write a program which will run a SQL query and mail the results to a group?
Answer: Use DBMS_JOB for scheduling a program job and DBMS_MAIL to send the results
through email.
Question: There is an Eno. & gender in a table. Eno. has primary key and gender has a check
constraints for the values 'M' and 'F'.
While inserting the data into the table M was misspelled as F and F as M.
What is the update?
Answer: update <TableName> set gender=
case where gender='F' Then 'M'
where gender='M' Then 'F'
Question: What the difference between UNION and UNIONALL?
Answer: union will return the distinct rows in two select s, while union all return all rows.
Question: How can we backup the sql files & what is SAP?
Answer: You can backup the sql files through backup utilities or some backup command in sql.
SAP is ERP software for the organization to integrate the software.
Question: What is the difference between TRUNCATE and DELETE commands?
Answer: TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE
operation can be rolled back, but TRUNCATE operation cannot be rolled back.
WHERE clause can be used with DELETE and not with TRUNCATE.
Question: State true or false. !=, <>, ^= all denote the same operation.
Answer: True.
Question: State true or false. EXISTS, SOME, ANY are operators in SQL.
Answer: True.
Question: What will be the output of the following query?
SELECT REPLACE (TRANSLATE (LTRIM (RTRIM ('!! ATHEN!!','!'), '!'), 'AN', '**'),'*','TROUBLE')
FROM DUAL;
Answer: TROUBLETHETROUBLE.
4. Question: What is the advantage to use trigger in your PL?
Answer: Triggers are fired implicitly on the tables/views on which they are created. There are
various advantages of using a trigger. Some of them are:
- Suppose we need to validate a DML statement (insert/Update/Delete) that modifies a table then
we can write a trigger on the table that gets fired implicitly whenever DML statement is executed
on that table.
- Another reason of using triggers can be for automatic updation of one or more tables whenever
a DML/DDL statement is executed for the table on which the trigger is created.
- Triggers can be used to enforce constraints. For eg: Any insert/update/ Delete statements should
not be allowed on a particular table after office hours. For enforcing this constraint Triggers
should be used.
- Triggers can be used to publish information about database events to subscribers. Database
event can be a system event like Database startup or shutdown or it can be a user even like User
login in or user logoff.
Question: How write a SQL statement to query the result set and display row as columns and
columns as row?
Answer: TRANSFORM Count (Roll_no) AS Count of Roll_no
SELECT Academic_Status
FROM tbl_enr_status
GROUP BY Academic_Status
PIVOT Curnt_status;
Question: Cursor Syntax brief history
Answer: To retrieve data with SQL one row at a time you need to use cursor processing. Not all
relational databases support this, but many do. Here I show this in Oracle with PL/SQL, which is
Procedural Language SQL .Cursor processing is done in several steps:1. Define the rows you
want to retrieve. This is called declaring the cursor.2. Open the cursor. This activates the cursor
and loads the data. Note that declaring the cursor doesn't load data, opening the cursor does.3.
Fetch the data into variables.4. Close the cursor.
Question: What is the data type of the surrogate key?
Answer: Data type of the surrogate key is either integer or numeric or number
Question: How to write a sql statement to find the first occurrence of a non zero value?
Answer: There is a slight chance the column "a" has a value of 0 which is not null. In that case,
you?ll loose the information. There is another way of searching the first not null value of a
column:
select column_name from table_name where column_name is not null and rownum<2;
Question: What is normalazation, types with e.g.'s. _ with queries of all types
Answer: There are 5 normal forms. It is necessary for any database to be in the third normal form
5. to maintain referential integrity and non-redundancy.
First Normal Form: Every field of a table (row, col) must contain an atomic value
Second Normal Form: All columns of a table must depend entirely on the primary key column.
Third Normal Form: All columns of a table must depend on all columns of a composite primary
key.
Fourth Normal Form: A table must not contain two or more independent multi-valued facts. This
normal form is often avoided for maintenance reasons.
Fifth Normal Form: is about symmetric dependencies.
Each normal form assumes that the table is already in the earlier normal form.
Question: Given an unnormalized table with columns:
Answer: The query will be: delete from tabname where rowid not in (select max (rowid) from
tabname group by name) Here tabname is the table name.
Question: How to find second maximum value from a table?
Answer: select max (field1) from tname1 where field1= (select max (field1) from tname1 where
field1<(select max(field1) from tname1);
Field1- Salary field
Tname= Table name.
Question: What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
Answer: The privilege receiver can further grant the privileges he/she has obtained from the
owner to any other user.
Question: What is the main difference between the IN and EXISTS clause in sub queries??
Answer: The main difference between the IN and EXISTS predicate in sub query is the way in
which the query gets executed.
IN -- The inner query is executed first and the list of values obtained as its result is used by the
outer query. The inner query is executed for only once.
EXISTS -- The first row from the outer query is selected, then the inner query is executed and, the
outer query output uses this result for checking. This process of inner query execution repeats as
many no .of times as there are outer query rows. That is, if there are ten rows that can result from
outer query, the inner query is executed that many no. of times.
Question: TRUNCATE TABLE EMP;
DELETE FROM EMP;
Will the outputs of the above two commands differ
Answer: The difference is that the TRUNCATE call cannot be rolled back and all memory space for
that table is released back to the server. TRUNCATE is much faster than DELETE and in both
cases only the table data is removed, not the table structure.
Question: What is table space?
Answer: Table-space is a physical concept. It has pages where the records of the database are
6. stored with a logical perception of tables. So table space contains tables.
Question: How to find out the 10th highest salary in SQL query?
Answer: Table - Tbl_Test_Salary
Column - int_salary
select max (int_salary)
from Tbl_Test_Salary
where int_salary in
(select top 10 int_Salary from Tbl_Test_Salary order by int_salary)
Question: Which command executes the contents of a specified file?
Answer: START <filename> or @<filename>.
Question: What is the difference between SQL and SQL SERVER?
Answer: SQL Server is an RDBMS just like oracle, DB2 from Microsoft
whereas
Structured Query Language (SQL), pronounced "sequel", is a language that provides an interface
to relational database systems. It was developed by IBM in the 1970s for use in System R. SQL is
a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various
operations on RDBMS.
Question: What is the difference between Single row sub-Query and Scalar Sub-Query?
Answer: SINGLE ROW SUBQUERY RETURNS A VALUE WHICH IS USED BY WHERE CLAUSE,
WHEREAS SCALAR SUBQUERY IS A SELECT STATEMENT USED IN COLUMN LIST CAN BE
THOUGHT OF AS AN INLINE FUNCTION IN SELECT COLUMN LIST.
Question: What does the following query do?
Answer: SELECT SAL + NVL (COMM, 0) FROM EMP;
It gives the added value of sal and comm for each employee in the emp table.
NVL (null value) replaces null with 0.
Question: How to find second maximum value from a table?
Answer: select max (field1) from tname1 where field1= (select max (field1) from tname1 where
field1< (select max (field1) from tname1);
Field1- Salary field
Tname= Table name.
Question: I have a table with duplicate names in it. Write me a query which returns only duplicate
rows with number of times they are repeated.
Answer: SELECT COL1 FROM TAB1
WHERE COL1 IN
(SELECT MAX (COL1) FROM TAB1
GROUP BY COL1
HAVING COUNT (COL1) > 1)
Question: How to find out the database name from SQL*PLUS command prompt?
Answer: Select * from global_name;
7. This will give the data base name which u r currently connected to.....
Question: How to display duplicate rows in a table?
Answer: select * from emp
group by (empid)
having count (empid)>1
Question: What is the value of comm and sal after executing the following query if the initial value
of ?sal? is 10000
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
Answer: sal = 11000, comm = 1000.
Question: 1) What is difference between Oracle and MS Access?
2) What are disadvantages in Oracle and MS Access?
2) What are features & advantages in Oracle and MS Access?
Answer: Oracle's features for distributed transactions, materialized views and replication are not
available with MS Access. These features enable Oracle to efficiently store data for multinational
companies across the globe. Also these features increase scalability of applications based on
Oracle.
Dot Net - C#.Net
1 . Does C# support multiple-inheritance?
No.
2 . Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).
3 . Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the
class interface, they are inherited.
4 . Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the
specified base class.
5 . What’s the top .NET class that everything is derived from?
System.Object.
6 . What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the
original immutable data value was discarded and a new data value was created in
8. memory.
7 . What’s the difference between System.String and System.Text.StringBuilder
classes?
System.String is immutable. System.StringBuilder was designed with the purpose of
having a mutable string where a variety of operations can be performed.
8 . What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string
manipulation. Strings are immutable, so each time a string is changed, a new instance
in memory is created.
9 . Can you store multiple data types in System.Array?
No.
10 . What’s the difference between the System.Array.CopyTo() and
System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the
elements in the original array. The CopyTo() method copies the elements into another
existing array. Both perform a shallow copy. A shallow copy means the contents
(each array element) contains references to the same object as the elements in the
original array. A deep copy (which neither of these methods performs) would create a
new instance of each element's object, resulting in a different, yet identacle object.
Dot Net - .Net Basic , Framework and Advanced
1 . What is .NET?
.NET is a general-purpose software development platform, similar to Java. At its core is a
virtual machine that turns intermediate language (IL) into machine code. High-level
language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C#
is a new programming language, very similar to Java. An extensive class library is
included, featuring all the functionality one might expect from a contempory development
platform - windows GUI development (Windows Forms), database access (ADO.NET), web
development (ASP.NET), web services, XML etc
See also Microsoft's definition
2 . When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET
'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates
were given CDs containing a pre-release version of the .NET framework/SDK and Visual
Studio.NET.
9. 3 . What versions of .NET are there?
The final versions of the 1.0 SDK and runtime were made publicly available around &6pm
PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made
available to MSDN subscribers.
.NET 1.1 was released in April 2003, and was mostly bug fixes for 1.0.
.NET 2.0 was released to MSDN subscribers in late October 2005, and was officially
launched in early November.
4 . What operating systems does the .NET Framework run on?
The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6a and
Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work
on all platforms - for example, ASP.NET is only supported on XP and Windows 2000/2003.
Windows 98/ME cannot be used for development
IIS is not supported on Windows XP Home Edition, and so cannot be used to host
ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home
The .NET Compact Framework is a version of the .NET Framework for mobile devices,
running Windows CE or Windows Mobile.
The Mono project has a version of the .NET Framework that runs on Linux.
5 . What tools can I use to develop .NET applications?
There are a number of tools, described here in ascending order of cost:
The .NET Framework SDK is free and includes command-line compilers for C++, C#,
and VB.NET and various other utilities to aid development.
SharpDevelop is a free IDE for C# and VB.NET.
Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for
hobbyist or novice developers.There are different versions for C#, VB, web
development etc. Originally the plan was to charge $49, but MS has decided to offer
them as free downloads instead, at least until November 2006.
Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade
At the top end of the price range are the Microsoft Visual Studio Team Edition for
Software Developers 2005 with MSDN Premium and Team Suite editions.
You can see the differences between the various Visual Studio versions here.
6 . Why did they call it .NET?
I don't know what they were thinking. They certainly weren't thinking of people using
search tools. It's meaningless marketing nonsense.
10. 7 . What is the CLI? Is it the same as the CLR?
The CLI (Common Language Infrastructure) is the definiton of the fundamentals of the
.NET framework - the Common Type System (CTS), metadata, the Virtual Execution
Environment (VES) and its use of intermediate language (IL), and the support of multiple
programming languages via the Common Language Specification (CLS). The CLI is
documented through ECMA - see http://msdn.microsoft.com/net/ecma/ for more details.
The CLR (Common Language Runtime) is Microsoft's primary implementation of the CLI.
Microsoft also have a shared source implementation known as ROTOR, for educational
purposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLI
implementations include Mono and DotGNU Portable.NET.
8 . What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or
CIL (Common Intermediate Language). All .NET source code (of any language) is compiled
to IL during development. The IL is then converted to machine code at the point where the
software is installed, or (more commonly) at run-time by a Just-In-Time (JIT) compiler.
9 . What is C#?
C# is a new language designed by Microsoft to work with the .NET framework. In their
"Introduction to C#" whitepaper, Microsoft describe C# as follows:
"C# is a simple, modern, object oriented, and type-safe programming language derived
from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++ family
tree of languages, and will immediately be familiar to C and C++ programmers. C# aims
to combine the high productivity of Visual Basic and the raw power of C++."
Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works
pretty well :-).
10 . What does 'managed' mean in the .NET context?
The term 'managed' is the cause of much confusion. It is used in various places within
.NET, meaning slightly different things.
Managed code: The .NET framework provides several core run-time services to the
programs that run within it - for example exception handling and security. For these
services to work, the code must provide a minimum level of information to the runtime.
Such code is called managed code.
Managed data: This is data that is allocated and freed by the .NET runtime's garbage
collector.
Managed classes: This is usually referred to in the context of Managed Extensions (ME)
for C++. When using ME C++, a class can be marked with the __gc keyword. As the name
suggests, this means that the memory for instances of the class is managed by the
garbage collector, but it also means more than that. The class becomes a fully paid-up
member of the .NET community with the benefits and restrictions that brings. An example
of a benefit is proper interop with classes written in other languages - for example, a
11. managed C++ class can inherit from a VB class. An example of a restriction is that a
managed class can only inherit from one base class.
>
11 . What is an assembly?
An assembly is sometimes described as a logical .EXE or .DLL, and can be an application
(with a main entry point) or a library. An assembly consists of one or more files (dlls,
exes, html files etc), and represents a group of resources, type definitions, and
implementations of those types. An assembly may also contain references to other
assemblies. These resources, types and references are described in a block of data called
a manifest. The manifest is part of the assembly, thus making the assembly selfdescribing.
An important aspect of assemblies is that they are part of the identity of a type. The
identity of a type is the assembly that houses it combined with the type name. This
means, for example, that if assembly A exports a type called T, and assembly B exports a
type called T, the .NET runtime sees these as two completely different types. Furthermore,
don't get confused between assemblies and namespaces - namespaces are merely a
hierarchical way of organising type names. To the runtime, type names are type names,
regardless of whether namespaces are used to organise the names. It's the assembly plus
the typename (regardless of whether the type name belongs to a namespace) that
uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security
restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.
12 . How can I produce an assembly?
The simplest way to produce an assembly is directly from a .NET compiler. For example,
the following C# program:
public class CTest
{
public CTest() { System.Console.WriteLine( "Hello from CTest" ); }
}
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler" tool that
comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the modules
into an assembly using the assembly linker (al.exe). For the C# compiler, the
/target:module switch is used to generate a module instead of an assembly.
12. 13 . What is the difference between a private assembly and a shared
assembly?
The terms 'private' and 'shared' refer to how an assembly is deployed, not any intrinsic
attributes of the assembly.
A private assembly is normally used by a single application, and is stored in the
application's directory, or a sub-directory beneath. A shared assembly is intended to be
used by multiple applications, and is normally stored in the global assembly cache (GAC),
which is a central repository for assemblies. (A shared assembly can also be stored outside
the GAC, in which case each application must be pointed to its location via a codebase
entry in the application's configuration file.) The main advantage of deploying assemblies
to the GAC is that the GAC can support multiple versions of the same assembly side-byside.
Assemblies deployed to the GAC must be strong-named. Outside the GAC, strong-naming
is optional.
14 . How do assemblies find each other?
By searching directory paths. There are several factors that can affect the path (such as
the AppDomain host, and application configuration files), but for weakly named assemblies
the search path is normally the application's directory and its sub-directories. For strongly
named assemblies, the search path is the GAC followed by the private assembly path.
15 . How does assembly versioning work?
An assembly has a version number consisting of four parts, e.g. 1.0.350.1. These are
typically interpreted as Major.Minor.Build.Revision, but this is just a convention.&
The CLR applies no version constraints on weakly named assemblies, so the assembly
version has no real significance.
For strongly named assemblies, the version of a referenced assembly is stored in the
referring assembly, and by default only this exact version will be loaded at run-time. If the
exact version is not available, the referring assembly will fail to load. It is possible to
override this behaviour in the config file for the referring assembly - references to a single
version or a range of versions of the referenced assembly can be redirected to a specific
version. For example, versions 1.0.0.0 to 2.0.0.0 can be redirected to version 3.0.125.3.
However note that there is no way to specify a range of versions to be redirected to.
Publisher policy files offer an alternative mechanism for redirecting to a different version
for assemblies deployed to the GAC - a publisher policy file allows the publisher of the
assembly to redirect all applications to a new version of an assembly in one operation,
rather than having to modify all of the application configuration files.
The restrictions on version policy for strongly named assemblies can cause problems when
providing patches or 'hot fixes' for individual assemblies within an application. To avoid
having to deploy config file changes or publisher policy files along with the hot fix, it
makes sense to reuse the same assembly version for the hot fix. If desired, the assemblies
can be distinguised by altering the assembly file version, which is not used at all by the
CLR for applying version policy. For more discussion, see Suzanne Cook's When to Change
13. File/Assembly Versions blog entry.
Note that the versioning of strongly named assemblies applies whether the assemblies are
deployed privately or to the GAC.
16 . How can I develop an application that automatically updates itself from
the web?
For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.
17 . What is an application domain?
An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist
inside a Win32 process. The primary purpose of the AppDomain is to isolate applications
from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An
AppDomain can be destroyed by the host without affecting other AppDomains in the
process.
Win32 processes provide isolation by having distinct memory address spaces. This is
effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping
control over the use of memory - all memory in the AppDomain is managed by the .NET
runtime, so the runtime can ensure that AppDomains do not access each other's memory.
One non-obvious use of AppDomains is for unloading types. Currently the only way to
unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful
if you create and destroy types on-the-fly via reflection.
18 . Can I write my own .NET host?
Yes. For an example of how to do this, take a look at the source for the dm.net
moniker developed by Jason Whittington and Don Box. There is also a code sample in
the .NET SDK called CorHost.
19 . What is garbage collection?
Garbage collection is a heap-management strategy where a run-time component takes
responsibility for managing the lifetime of the memory used by objects. This concept is not
new to .NET - Java and many other languages/runtimes have used garbage collection for
some time.
20 . Is it true that objects don't always get destroyed immediately when the
last reference goes away?
Yes. The garbage collector offers no guarantees about the time when an object will be
destroyed and its memory reclaimed.&
There was an interesting thread on the DOTNET list, started by Chris Sells, about the
implications of non-deterministic destruction of objects in C#. In October 2000, Microsoft's
Brian Harry posted a lengthy analysis of the problem. Chris Sells' response to Brian's
posting is here
14. 21 . Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by
periodically running through a list of all the objects that are currently being referenced by
an application. All the objects that it doesn't find during this search are ready to be
destroyed and the memory reclaimed. The implication of this algorithm is that the runtime
doesn't get notified immediately when the final reference on an object goes away - it only
finds out during the next 'sweep' of the heap
Futhermore, this type of algorithm works best by performing the garbage collection sweep
as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.
22 . Is the lack of deterministic destruction in .NET a problem?
It's certainly an issue that affects component design. If you have objects that maintain
expensive or scarce resources (e.g. database locks), you need to provide some way to tell
the object to release the resource when it is done. Microsoft recommend that you provide
a method called Dispose() for this purpose. However, this causes problems for distributed
objects - in a distributed system who calls the Dispose() method? Some form of referencecounting or ownership-management mechanism is needed to handle distributed objects unfortunately the runtime offers no help with this
23 . Should I implement Finalize on my class? Should I implement
IDisposable?
This issue is a little more complex than it first appears. There are really two categories of
class that require deterministic destruction - the first category manipulate unmanaged
types directly, whereas the second category manipulate managed types that require
deterministic destruction. An example of the first category is a class with an IntPtr
member representing an OS file handle. An example of the second category is a class with
a System.IO.FileStream member
For the first category, it makes sense to implement IDisposable and override Finalize. This
allows the object user to 'do the right thing' by calling Dispose, but also provides a fallback
of freeing the unmanaged resource in the Finalizer, should the calling code fail in its duty.
However this logic does not apply to the second category of class, with only managed
resources. In this case implementing Finalize is pointless, as managed member objects
cannot be accessed in the Finalizer. This is because there is no guarantee about the
ordering of Finalizer execution. So only the Dispose method should be implemented. (If
you think about it, it doesn't really make sense to call Dispose on member objects from a
Finalizer anyway, as the member object's Finalizer will do the required cleanup.)
For classes that need to implement IDisposable and override Finalize, see Microsoft's
documented pattern.
Note that some developers argue that implementing a Finalizer is always a bad idea, as it
hides a bug in your code (i.e. the lack of a Dispose call). A less radical approach is to
implement Finalize but include a Debug.Assert at the start, thus signalling the problem in
developer builds but allowing the cleanup to occur in release builds.
24 . Do I have any control over the garbage collection algorithm?
15. A little. For example the System.GC class exposes a Collect method, which forces the
garbage collector to collect all unreferenced objects immediately
Also there is a gcConcurrent setting that can be specified via the application
configuration file. This specifies whether or not the garbage collector performs some of its
collection activities on a separate thread. The setting only applies on multi-processor
machines, and defaults to true.
25 . How can I find out what the garbage collector is doing?
Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx'
performance counters. Use Performance Monitor to view them
26 . What is the lapsed listener problem?
The lapsed listener problem is one of the primary causes of leaks in .NET applications. It
occurs when a subscriber (or 'listener') signs up for a publisher's event, but fails to
unsubscribe. The failure to unsubscribe means that the publisher maintains a reference to
the subscriber as long as the publisher is alive. For some publishers, this may be the
duration of the application
This situation causes two problems. The obvious problem is the leakage of the subscriber
object. The other problem is the performance degredation due to the publisher sending
redundant notifications to 'zombie' subscribers.
There are at least a couple of solutions to the problem. The simplest is to make sure the
subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe()
method to the subscriber. Another solution, documented here by Shawn Van Ness, is to
change the publisher to use weak references in its subscriber list.
27 . What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization
is the opposite process, i.e. creating an object from a stream of bytes.
Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or
to persist objects (e.g. to a file or database).
28 . Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library - XmlSerializer and
SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and
SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code
29 . I want to serialize instances of my class. Should I use XmlSerializer,
SoapFormatter or BinaryFormatter?
It depends. XmlSerializer has severe limitations such as the requirement that the target
class has a parameterless constructor, and only public read/write properties and fields can
be serialized. However, on the plus side, XmlSerializer has good support for customising
the XML document that is produced or consumed. XmlSerializer's features mean that it is
most suitable for cross-platform work, or for constructing objects from existing XML
16. documents
SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can
serialize private fields, for example. However they both require that the target class be
marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written
with serialization in mind. Also there are some quirks to watch out for - for example on
deserialization the constructor of the new object is not invoked.
The choice between SoapFormatter and BinaryFormatter depends on the application.
BinaryFormatter makes sense where both serialization and deserialization will be
performed on the .NET platform and where performance is important. SoapFormatter
generally makes more sense in all other cases, for ease of debugging if nothing else.
30 . Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure serialization
for a particular class. For example, a field or property can be marked with the [XmlIgnore]
attribute to exclude it from serialization. Another example is the [XmlElement] attribute,
which can be used to specify the XML element name to be used for a particular property or
field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by
attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's
[XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by
implementing the the ISerializable interface on the class whose instances are to be
serialized.
>
31 . Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you
serialize or deserialize an object of a given type in an application, there is a significant
delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a
poor choice for loading configuration settings during startup of a GUI application
32 . Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary,
e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
33 . XmlSerializer is throwing a generic "There was an error reflecting
MyClass" error. How do I find out what the problem is?
Look at the InnerException property of the exception that is thrown to get a more specific
error message
34 . What are attributes?
There are at least two types of .NET attribute. The first type I will refer to as a metadata
attribute - it allows some data to be attached to a class or method. This data becomes
17. part of the metadata for the class, and (like other class metadata) can be accessed via
reflection. An example of a metadata attribute is [serializable], which can be attached to a
class and means that instances of the class can be serialized.
[serializable] public class CTest {}
The other type of attribute is a context attribute. Context attributes use a similar syntax
to metadata attributes but they are fundamentally different. Context attributes provide an
interception mechanism whereby instance activation and method calls can be pre- and/or
post-processed. If you have encountered Keith Brown's universal delegator you'll be
familiar with this idea.
35 . What is Code Access Security (CAS)?
CAS is the part of the .NET security model that determines whether or not code is allowed
to run, and what resources it can use when it is running. For example, it is CAS that will
prevent a .NET web applet from formatting your hard disk.
36 . How does CAS work?
The CAS security policy revolves around two key concepts - code groups and permissions.
Each .NET assembly is a member of a particular code group, and each code group is
granted the permissions specified in a named permission set.
For example, using the default security policy, a control downloaded from a web site
belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by
the 'Internet' named permission set. (Naturally the 'Internet' named permission set
represents a very restrictive range of permissions.)
37 . I'm having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to tell you what
code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what
permissions are being applied to a particular assembly using caspol -rsp
38 . I can't be bothered with CAS. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off
39 . Can I look at the IL for an assembly?
Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL for
an assembly.
40 . Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz
Roeder's Reflector does a very good job of turning IL into C# or VB.NET.
18. 41 . How can I stop my code being reverse-engineered from IL?
You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way
that reverse-engineering becomes much more difficult
Of course if you are writing web services then reverse-engineering is not a problem as
clients do not have access to your IL.
42 . Can I write IL programs directly?
Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr
"Hello, IL!"
call
void System.Console::WriteLine(class System.Object)
ret
}
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will
be generated.
43 . Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not
derived from System.Exception, and you can have non-zero-based arrays.
44 . Does .NET replace COM?
This subject causes a lot of controversy, as you'll see if you read the mailing list
archives. Take a look at the following two threads:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761
The bottom line is that .NET has its own mechanisms for type interaction, and they
don't use COM. No IUnknown, no IDL, no typelibs, no registry-based activation. This
is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to
package and use components in a similar way to COM, but makes the whole thing a
bit easier.
45 . Is DCOM dead?
Pretty much, for .NET developers. The .NET Framework has a new remoting model
which is not based on DCOM. DCOM was pretty much dead anyway, once firewalls
became widespread and Microsoft got SOAP fever. Of course DCOM will still be used in
interop scenarios.
46 . Is COM+ dead?
Not immediately. The approach for .NET 1.0 was to provide access to the existing
19. COM+ services (through an interop layer) rather than replace the services with native
.NET ones. Various tools and attributes were provided to make this as painless as
possible. Over time it is expected that interop will become more seamless - this may
mean that some services become a core part of the CLR, and/or it may mean that
some services will be rewritten as managed code which runs on top of the CLR.
For more on this topic, search for postings by Joe Long in the archives - Joe is the MS
group manager for COM+. Start with this message:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370
47 . Can I use COM components from .NET programs?
Yes. COM components are accessed from the .NET runtime via a Runtime Callable
Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM
component into .NET-compatible interfaces. For oleautomation interfaces, the RCW
can be generated automatically from a type library. For non-oleautomation interfaces,
it may be necessary to develop a custom RCW which manually maps the types
exposed by the COM interface to .NET-compatible types.
48 . Can I use .NET components from COM programs?
Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW).
This is similar to a RCW (see previous question), but works in the opposite direction.
Again, if the wrapper cannot be automatically generated by the .NET development
tools, or if the automatic behaviour is not desirable, a custom CCW can be developed.
Also, for COM to 'see' the .NET component, the .NET component must be registered in
the registry.
49 . Is ATL redundant in the .NET world?
Yes. ATL will continue to be valuable for writing COM components for some time, but
it has no place in the .NET world.
50 . How do I spawn a thread?
Create an instance of a System.Threading.Thread object, passing it an instance of a
ThreadStart delegate that will be executed on the new thread. For example:
class MyThread
{
public MyThread( string initData )
{
m_data = initData;
m_thread = new Thread( new ThreadStart(ThreadMain) );
m_thread.Start();
}
// ThreadMain() is executed on the new thread.
private void ThreadMain()
{
Console.WriteLine( m_data );
}
20. public void WaitUntilFinished()
{
m_thread.Join();
}
private Thread m_thread;
private string m_data;
}
In this case creating an instance of the MyThread class is sufficient to spawn the
thread and execute the MyThread.ThreadMain() method:
MyThread t = new MyThread( "Hello, world." );
t.WaitUntilFinished();
>
51 . How do I stop a thread?
There are several options. First, you can use your own communication mechanism to
tell the ThreadStart method to finish. Alternatively the Thread class has in-built
support for instructing the thread to stop. The two principle methods are
Thread.Interrupt() and Thread.Abort(). The former will cause a
ThreadInterruptedException to be thrown on the thread when it next goes into a
WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the
thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort()
throws a ThreadAbortException regardless of what the thread is doing. Furthermore,
the ThreadAbortException cannot normally be caught (though the ThreadStart's finally
method will be executed). Thread.Abort() is a heavy-handed mechanism which should
not normally be required.
52 . How do I use the thread pool?
By passing an instance of a WaitCallback delegate to the
ThreadPool.QueueUserWorkItem() method
class CApp
{
static void Main()
{
string s = "Hello, World";
ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );
Thread.Sleep( 1000 );
// Give time for work item to be executed
}
// DoWork is executed on a thread from the thread pool.
static void DoWork( object state )
{
Console.WriteLine( state );
}
}
21. 53 . How do I know when my thread pool work item has completed?
There is no way to query the thread pool for this information. You must put code into
the WaitCallback method to signal that it has completed. Events are useful for this.
54 . Should I use ReaderWriterLock instead of Monitor.Enter/Exit?
Maybe, but be careful. ReaderWriterLock is used to allow multiple threads to read
from a data source, while still granting exclusive access to a single writer thread. This
makes sense for data access that is mostly read-only, but there are some caveats.
First, ReaderWriterLock is relatively poor performing compared to Monitor.Enter/Exit,
which offsets some of the benefits. Second, you need to be very sure that the data
structures you are accessing fully support multithreaded read access. Finally, there is
apparently a bug in the v1.1 ReaderWriterLock that can cause starvation for writers
when there are a large number of readers.
Ian Griffiths has some interesting discussion on ReaderWriterLock here and here.
55 . Tracing . Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with
tracing - Debug and Trace. They both work in a similar way - the difference is that
tracing from the Debug class only works in builds that have the DEBUG symbol
defined, whereas tracing from the Trace class only works in builds that have the
TRACE symbol defined. Typically this means that you should use
System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and
release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to
work only in debug builds.
56 . Can I redirect tracing to a file?
Yes. The Debug and Trace classes both have a Listeners property, which is a collection
of sinks that receive the tracing that you send via Debug.WriteLine and
Trace.WriteLine respectively. By default the Listeners collection contains a single sink,
which is an instance of the DefaultTraceListener class. This sends output to the Win32
OutputDebugString() function and also the System.Diagnostics.Debugger.Log()
method. This is useful when debugging, but if you're trying to trace a problem at a
customer site, redirecting the output to a file is more appropriate. Fortunately, the
TextWriterTraceListener class is provided for this purpose.
Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:
Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );
Trace.WriteLine( @"This will be writen to c:log.txt!" );
Trace.Flush();
Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do
this, the output will go to the file and OutputDebugString(). Typically this is not what
you want, because OutputDebugString() imposes a big performance hit.
57 . Can I customise the trace output?
22. Yes. You can write your own TraceListener-derived class, and direct all output through
it. Here's a simple example, which derives from TextWriterTraceListener (and
therefore has in-built support for writing to files, as shown above) and adds timing
information and the thread ID for each trace line:
class MyListener : TextWriterTraceListener
{
public MyListener( Stream s ) : base(s)
{
}
public override void WriteLine( string s )
{
Writer.WriteLine( "{0:D8} [{1:D4}] {2}",
Environment.TickCount - m_startTickCount,
AppDomain.GetCurrentThreadId(),
s );
}
protected int m_startTickCount = Environment.TickCount;
}
(Note that this implementation is not complete - the TraceListener.Write method is
not overridden for example.)
The beauty of this approach is that when an instance of MyListener is added to the
Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener,
including calls made by referenced assemblies that know nothing about the
MyListener class.
58 . Are there any third party logging components available?
Log4net is a port of the established log4j Java logging component.
59 . Miscellaneous . How does .NET remoting work?
.NET remoting involves sending messages along channels. Two of the standard
channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for
LANs or WANs (internet).
Support is provided for multiple message serializarion formats. Examples are SOAP
(XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET
runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET
runtime Serialization Binary Formatter). But either channel can use either serialization
format.
There are a number of styles of remote access:
• SingleCall. Each incoming request from a client is serviced by a new object. The
object is thrown away when the request has finished.
• Singleton. All incoming requests from clients are processed by a single server
object.
• Client-activated object. This is the old stateful (D)COM model whereby the client
receives a reference to the remote object and holds that reference (thus keeping the
remote object alive) until it is finished with it.
Distributed garbage collection of objects is managed by a system called 'leased based
lifetime'. Each object has a lease time, and when that time expires the object is
23. disconnected from the .NET runtime remoting infrastructure. Objects have a default
renew time - the lease is renewed when a successful call is made from the client to
the object. The client can also explicitly renew the lease.
If you're interested in using XML-RPC as an alternative to SOAP, take a look at
Charles Cook's XML-RPC.Net.
60 . How can I get at the Win32 API from a .NET program?
Use P/Invoke. This uses similar technology to COM Interop, but is used to access
static DLL entry points instead of COM objects. Here is an example of C# calling the
Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;
class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true,
CharSet=CharSet.Auto)]
public static extern int MessageBox(int hWnd, String strMessage, String
strCaption, uint uiType);
public static void Main()
{
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );
}
}
Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.
61 . How do I write to the application configuration file at runtime?
You don't. See http://www.interact-sw.co.uk/iangblog/2004/11/25/savingconfig.
62 . What is the difference between an event and a delegate?
An event is just a wrapper for a multicast delegate. Adding a public event to a class is
almost the same as adding a public multicast delegate field. In both cases, subscriber
objects can register for notifications, and in both cases the publisher object can send
notifications to the subscribers. However, a public multicast delegate has the
undesirable property that external objects can invoke the delegate, something we'd
normally want to restrict to the publisher. Hence events - an event adds public
methods to the containing class to add and remove receivers, but does not make the
invocation mechanism public.
See this post by Julien Couvreur for more discussion.
63 . What size is a .NET object?
Each instance of a reference type has two fields maintained by the runtime - a
method table pointer and a sync block. These are 4 bytes each on a 32-bit system,
making a total of 8 bytes per object overhead. Obviously the instance data for the
type must be added to this to get the overall size of the object. So, for example,
instances of the following class are 12 bytes each:
24. class MyInt
{
...
private int x;
}
However, note that with the current implementation of the CLR there seems to be a
minimum object size of 12 bytes, even for classes with no data (e.g. System.Object).
Values types have no equivalent overhead.
64 . Will my .NET app run on 64-bit Windows?
64-bit (x64) versions of Windows support both 32-bit and 64-bit processes, and
corresponding 32-bit and 64-bit versions of .NET 2.0. (.NET 1.1 is 32-bit only).
.NET 1.x apps automatically run as 32-bit processes on 64-bit Windows.
.NET 2.0 apps can either run as 32-bit processes or as 64-bit processes. The OS
decides which to use based on the PE header of the executable. The flags in the PE
header are controlled via the compiler /platform switch, which allows the target of the
app to be specified as 'x86', 'x64' or 'any cpu'. Normally you specify 'any cpu', and
your app will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. However
if you have some 32-bit native code in your app (loaded via COM interop, for
example), you will need to specify 'x86', which will force 64-bit Windows to load your
app in a 32-bit process. You can also tweak the 32-bit flag in the PE header using the
SDK corflags utility.
Some more explanation here:
http://blogs.msdn.com/gauravseth/archive/2006/03/07/545104.aspx
http://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspx
http://msdn.microsoft.com/netframework/programming/64bit/gettingstarted/
65 . What is reflection?
All .NET compilers produce metadata about the types defined in the modules they
produce. This metadata is packaged along with the module (modules in turn are
packaged together in assemblies), and can be accessed by a mechanism called
reflection. The System.Reflection namespace contains classes that can be used to
interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo
to access type library data in COM, and it is used for similar purposes - e.g.
determining data type sizes for marshaling data across context/process/machine
boundaries.
Reflection can also be used to dynamically invoke methods (see
System.Type.InvokeMember), or even create types dynamically at run-time (see
System.Reflection.Emit.TypeBuilder).
66 . .NET 2.0 What are the new features of .NET 2.0?
Generics, anonymous methods, partial classes, iterators, property visibility (separate
visibility for get and set) and static classes. See
http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx for more
information about these features.
25. 67 . What are the new 2.0 features useful for?
Generics are useful for writing efficient type-independent code, particularly where the
types might include value types. The obvious application is container classes, and the
.NET 2.0 class library includes a suite of generic container classes in the
System.Collections.Generic namespace. Here's a simple example of a generic
container class being used:
List<int> myList = new List<int>();
myList.Add( 10 );
Anonymous methods reduce the amount of code you have to write when using
delegates, and are therefore especially useful for GUI programming. Here's an
example
AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Process
ending ..."); };
Partial classes is a useful feature for separating machine-generated code from handwritten code in the same class, and will therefore be heavily used by development
tools such as Visual Studio.
Iterators reduce the amount of code you need to write to implement
IEnumerable/IEnumerator. Here's some sample code:
static void Main()
{
RandomEnumerator re = new RandomEnumerator( 5 );
foreach( double r in re )
Console.WriteLine( r );
Console.Read();
}
class RandomEnumerator : IEnumerable<double>
{
public RandomEnumerator(int size) { m_size = size; }
public IEnumerator<double> GetEnumerator()
{
Random rand = new Random();
for( int i=0; i < m_size; i++ )
yield return rand.NextDouble();
}
int m_size = 0;
}
The use of 'yield return' is rather strange at first sight. It effectively synthethises an
implementation of IEnumerator, something we had to do manually in .NET 1.x.
68 . What's the problem with .NET generics?
.NET generics work great for container classes. But what about other uses? Well, it
turns out that .NET generics have a major limitation - they require the type
parameter to be constrained. For example, you cannot do this:
static class Disposer<T>
{
public static void Dispose(T obj) { obj.Dispose(); }
26. }
The C# compiler will refuse to compile this code, as the type T has not been
constrained, and therefore only supports the methods of System.Object. Dispose is
not a method on System.Object, so the compilation fails. To fix this code, we need to
add a where clause, to reassure the compiler that our type T does indeed have a
Dispose method
static class Disposer<T> where T : IDisposable
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The problem is that the requirement for explicit contraints is very limiting. We can use
constraints to say that T implements a particular interface, but we can't dilute that to
simply say that T implements a particular method. Contrast this with C++ templates
(for example), where no constraint at all is required - it is assumed (and verified at
compile time) that if the code invokes the Dispose() method on a type, then the type
will support the method.
In fact, after writing generic code with interface constraints, we quickly see that we
haven't gained much over non-generic interface-based programming. For example,
we can easily rewrite the Disposer class without generics:
static class Disposer
{
public static void Dispose( IDisposable obj ) { obj.Dispose(); }
}
For more on this topic, start by reading the following articles:
Bruce Eckel: http://www.mindview.net/WebLog/log-0050
Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics
Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html
69 . What's new in the .NET 2.0 class library?
Here is a selection of new features in the .NET 2.0 class library:
• Generic collections in the System.Collections.Generic namespace.
• The System.Nullable<T> type. (Note that C# has special syntax for this type, e.g.
int? is equivalent to Nullable<int>)
• The GZipStream and DeflateStream classes in the System.IO.Compression
namespace.
• The Semaphore class in the System.Threading namespace.
• Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes
in the System.Security.Cryptography namespace.
• The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc
namespace, for optimised intra-machine communication.
and many, many more. See http://msdn2.microsoft.com/en-us/library/t357fb32(enUS,VS.80).aspx for a comprehensive list of changes.