. NET Technologies Lab Manual and Notes

 

SYLLABUS

Pokhara University
NET Technologies
BCIS, Elective (3 Credit hours)

Course Objectives:
This course aims to familiarize students with various technologies brought about or changed by the introduction of the .NET framework, and enable them to be able to develop different kinds of applications using these technologies.
Prerequisites:
Programming in at least one of C++, Java or Visual Basic Object Oriented Programming Concepts
Course Contents:
1. DOT.NET Fundamentals (2 hours) – History, Overview, Terminology, Advantages
2. Windows Development using .NET (5 hours) – Overview – Structured programming and OOP, C#, Windows Forms
3. Web Development using .NET (6 hours) – Overview – HTML, JavaScript, ASP.NET Web Application using MVC, ASP.NET Mobile applications
4. Web Services using .NET (6 hours) – Overview – Web Services and their applications, XML, XML Web Services, SOAP and REST
5. Database Development using .NET (6 hours) – Overview – Database concepts and SQL, ADO.NET, XML and Data
6. DOT.NET Common Language Runtime (7 hours) – Overview, Assemblies and JIT, Garbage Collection, Security, Events and Delegates, Reflection, Remoting, CLS and Interop
7. DOT.NET Framework Class Library (8 hours) – Overview, GDI+, Exceptions, Input/Output, Threading, Windows Service
8. Case Studies (8 hours) – Developing Graphics Applications, Developing Network Applications, Creating and Publishing Customizable Web Reports, Database Application, Web Service
Note: The bracketed number at the end is the estimated number of 1.5 hour periods required for that topic.
Text book: Deitel’s: C# – How to program will be used for lab purposes.
Reference book: C#.Net Web Developers’ Guide

TABLE OF CONTENTS
SYLLABUS 2
TABLE OF CONTENTS 3
CHAPTER I 6
DOT.NET FUNDAMENTALS 6
1.1 History 6
1.2 Introduction 6
1.3 DOT.NET Platform Architecture 7
1.4 Features of the .NET Platform 9
1.4.1 Multilanguage Development 10
1.4.2 Platform and Processor Independence 11
1.4.3 Automatic Memory Management 11
1.4.4 Versioning Support 12
1.4.5 Support for Open Standards 13
1.4.6 Easy Deployment 13
1.4.7 Distributed Architecture 13
1.4.8 Interoperability with Unmanaged Code 14
1.4.9 Security 14
1.4.10 Performance and Scalability 16
1.5 Components of the .NET Architecture 16
1.5.1 .NET Runtime 16
1.5.2 Managed/Unmanaged Code 16
1.5.3 Intermediate Language 17
1.5.4 Common Type System 17
1.5.5 .NET Base Class Library (BCL) 17
1.5.6 Assemblies 18
1.5.7 Metadata 18
1.5.8 Assemblies and Modules 18
1.5.9 Assembly Cache 19
1.5.10 Reflection 19
1.5.11 Just In Time Compilation 20
1.5.12 Garbage Collection 20
1.6 Advantages/Disadvantages 21

CHAPTER 2 23
WINDOWS DEVELOPMENT USING .NET 23
2.1 Overview 23
2.2 Structured Programming and OOP 23
2.2.1 Structured Programming 23
2.2.2 Object Oriented Programming 23
2.2.3 OOP key terminologies 23
2.3 Visual C# 24
2.4 Windows Forms 24
2.4.1 Introduction 24
2.4.2 Components of IDE 25
CHAPTER 3 26
WEB DEVELOPMENT USING .NET 26
3.1 Overview 26
3.2 HTML 26
3.3 JavaScript 28
3.4 jQuery 29
CHAPTER 4 31
WEB SERVICES 31
4.1 Web Services 31
4.2 Web Services in Practice 34
4.3 Web Services Framework 34
4.3.1 Web Services Architecture 35
4.3.2 HTTP GET and HTTP POST 36
4.3.3 SOAP 36
4.3.4 REST 36
4.3.5 SOAP VS REST 37
4.4 Web Services and Security 37
4.4.1 System Security 38
4.4.2 Application Security 39
CHAPTER 5 40
DATABASE DEVELOPMENT USING .NET 40
5.1 Overview 40
5.2 Database concepts and SQL 40
5.2.1 Database 40
5.2.2 SQL 40
5.3 ADO.NET and Data 41
5.3.1 ADO.NET 41
5.3.2 ADO.NET Objects 43
5.3.3 Working with Disconnected Data 47
CHAPTER 6 51
.NET COMMON LANGUAGE RUNTIME 51
6.1 Introduction 51
6.2 Assemblies and JIT 52
6.3 Garbage Collection 52
6.4 Security 53
6.5 Events and Delegates 53
6.6 Reflection 53
6.7 Remoting 54
6.8 Common Language Specification 54
6.9 COM Interop 55
6.10 Managed Code 56
6.10 Common Type System 56
6.12 Memory Allocation in Managed Heap 56
CHAPTER 7 58
.NET FRAMEWORK CLASS LIBRARY 58
7.1 Overview 58
7.2 GDI+ 59
7.3 Exceptions 59
7.5 Threading 60
CHAPTER 8 62
CASE STUDIES (MINOR PROJECT) AND LAB 62
8.1 Overview 62
8.2 Guidelines for Case Studies 62
8.3 Guidelines for Lab 62
CODE SAMPLES 64

CHAPTER I
DOT.NET FUNDAMENTALS
1.1 History
Microsoft started development on the .NET Framework in the late 1990s, originally under the name of Next Generation Windows Services (NGWS). Originally, Microsoft developed a product called J++ which was similar to Java. Java was originally advertised as the “write once, run everywhere” language. It used operating system-independent runtimes (called JVM). Due to legal problems, Microsoft had to put off the development of J++. Later, they replaced the development with their own, unrelated, competing product, which was .NET.
By late 2000 the first beta versions of .NET 1.0 were released. The list below provides a summary of major generations of frameworks and their release dates along with the Integrated Development Environment (IDE) that contained the respective version out of the box.

1.2 Introduction
The .NET platform is the foundation upon which provides the environment to build the next generation of software. The .NET platform is much more than a new language, software development kit (SDK), or even an operating system. It offers powerful new services, a new processor-independent binary format, new managed languages, managed language extensions to existing languages, and the list goes on.
The precept behind the .NET platform is that the world of computing is changing from one of PCs connected to servers through networks such as the Internet, to one where all manner of smart devices, computers, and services work together to provide a richer user experience. The .NET platform is Microsoft’s answer to the challenges this change will provide for software developers.
The .NET platform has several components that include Visual Studio.NET (VS.NET), the .NET Common Language Runtime (CLR), and the .NET Base Class Libraries (BCL). The other components may be required by specific applications, but they are not a necessary part of all .NET applications.
Looking at the overall architecture, .NET consists of three primary components:
■ The .NET Framework: A completely new application development platform.
■ Several .NET Products: Various applications from Microsoft based on the .NET Framework, including new versions of Exchange and SQL Server, which are Extensible Markup Language (XML)–enabled and integrated into the .NET platform.
■ Several .NET Services: Provided by Microsoft for use in developing applications running under the .NET Framework. Microsoft’s Hailstorm project is actually an attempt to package some of the most crucial Web Services under the Microsoft brand name.
The .NET Framework itself can be divided into three parts:
■ The CLR: A managed execution environment that handles memory allocation, error trapping, and interacting with the operating-system services.
■ The Base Class Library: An extensive collection of programming components and application program interfaces (APIs).
■ Top-level development targets: One for Web applications (ASP.NET and ASP.NET MVC), other for regular Windows applications (Windows Forms), for Mobile applications (Windows Mobile) and many more.
The advantages offered by the .NET Framework include shorter development cycles (code reuse, fewer programming surprises, support for multiple programming languages), easier deployment, fewer data type–related bugs due to integral type safety, reduced memory leaks thanks to the garbage collector, and, in general more scalable, reliable applications.
1.3 DOT.NET Platform Architecture
The diagram in Figure 1.1 shows the .NET platform architecture. Essentially, the .NET families of languages are each compiled into Microsoft Intermediate Language (MSIL, or just IL) output according to the Common Language Specification. The primary types of application development are Web Forms, Web Services, and Windows Forms applications. These applications communicate using XML and Simple Object Access Protocol (SOAP), getting their functionality from the Base Class Library and run within the Common Language Runtime environment. Visual Studio.NET is not required in order to develop .NET Framework applications; however it does offer an extensible architecture that makes it an ideal choice for developing .NET software.

Figure 1.1: .NET Platform Architecture

The diagram shows the .NET platform architecture. Essentially, the .NET families of languages are each compiled using their respective compiler into Microsoft Intermediate Language aka Common Intermediate Language (MSIL, or CIL, or just IL) output according to the Common Language Specification. The primary types of application development are Web Forms, Web Services, and Windows Forms applications. These applications get their functionality from the Base Class Library and run within the Common Language Runtime environment. Visual Studio is not mandatorily required in order to develop .NET Framework applications, however it does offer a rich set of extensively helpful tools and productive environment that makes it an ideal choice for developing .NET software components.
The .NET Framework mainly consists of two major components, namely the Common Language Runtime and the Class Libraries. These two components build up the Framework.
Common Language Runtime (CLR)
CLR is the main runtime engine for .Net. This is an environment wherein our applications can run safely and in a well-mannered fashion. The CLR interacts with the OS on behalf of our application’s requests. CLR is responsible for verifying type safety, garbage collection (automatic memory management) and error handling along with Code Access Security. All code that is executed by the CLR (or targeted to run by the CLR) is called managed code. Any code that is executed directly on the Operating System is called unmanaged code.
CLR implements Code Access Security based on the evidence for an Assembly. Evidence can be such as from which site the code is being downloaded, any strong name key available or digital signatures and assigns the code to a particular code group based on the evidence. Each code group has a set of permissions which define what all the assembly can access and perform. Thus, various applications are assigned different levels of trust, each being allowed or denied with different level of authorization for resources access.
By default memory management is done by CLR and the garbage collection runs as a low priority thread. The execution of this is non-deterministic (i.e., runs differently on different machines based on various factors). This implies that no more pointer access by default (However, one can use pointers by writing unmanaged code using the keyword “unsafe”). Relinquishing/Releasing of memory is done by the garbage collection once the object is marked for garbage collection.
CLR is also known as Virtual Execution System (VES).
Class Libraries
In the .NET Framework classes, interfaces, and value types are bundled together into a library. With all of those elements bundled together the development process is much faster because all needed elements are there and ready to go. It also creates a more efficient environment by making system functionality readily accessible. One of the big advantages of the Microsoft .NET platform is due to the class libraries. As long as the compiler conforms to the Common Language Specifications (CLS), any programming language can use the .NET Framework types. This greatly increases the ease of interoperability between languages. Class libraries can be broadly categorized into two groups:
Base Class Libraries: Includes a small subset of entire class libraries. These provide the essential and core set of functionalities. It provides types to represent the built-in data types of the framework, simple file access, custom attributes, security attributes, string manipulation, formatting, streams, collections, among other things. The System namespace contains classes and methods of Base Class Libraries. These are essential for CLR to function properly.
Framework Class Libraries: Superset of BCL. It is the remaining set of class libraries that provide extended and/or development-specific functionalities. It is a rich set of reusable types allowing you to achieve a high level of developer productivity by simplifying many common programming tasks. E.g. ADO.NET, Windows Forms, ASP.NET, WCF, WPF.
1.4 Features of the .NET Platform
The core of the .NET platform is found in the Common Language Runtime, Base Class Library, and the Common Language Specification. The .NET Base Class Library exposes the features of the Common Language Runtime in much the same way that the Windows API allows you to utilize the features of the Windows operating system; however, it also provides many higher-level features that facilitate code reuse.
This architecture gives a great number of benefits, not the least of which is a consistent API. By writing to the Common Language Runtime and using the .NET Base Class library, all application services are available via a common object-oriented programming model. Today some OS functions are accessed via DLL calls using the C-based API and other facilities are accessed via COM objects, making the developer do the necessary legwork to make everything work together smoothly. Some features are available only to developers working in low-level languages, forcing design decisions.
This new programming model greatly simplifies the efforts that were required when writing Windows DNA applications, or for that matter, almost any Win32 and COM project. Developers no longer need to be a Windows or COM architecture guru with an in-depth understanding of GUIDs, IUnknown, AddRef, Release, HRESULTS, and so on. .NET doesn’t just hide these from the developer; in the new .NET platform, these concepts simply do not exist at all.
Another great benefit for .NET developers is its model for error handling via exceptions. Developing software for the Windows platform has always meant you were pulled into its own inconsistencies; particularly in the ways errors were returned. Some functions would return Win32 error codes, some return HRESULTS, and some raise exceptions, all requiring the programmer to write different types of error-handling code. In .NET, all errors are reported via exceptions, which greatly simplifies the writing, reading, and maintaining code.
Thanks to the Common Language Specification and Common Type System, .NET exceptions work across module and language boundaries as well.
1.4.1 Multilanguage Development
Because many languages target the .NET Common Language Runtime, it is now much easier to implement portions of your application using the language that’s best suited for it. Older methods of allowing different programming languages to interoperate, such as COM or CORBA did so through the use of an Interface Definition Language (IDL).The .NET platform allows languages to be integrated with one another through the use of the MSIL. Although it contains instructions that appear similar to assembly code, such as pushing and popping values and moving variables in and out of registers, it also contains instructions for managing objects and invoking their methods, manipulating arrays, and raising and catching exceptions.
The Microsoft Common Language Specification describes what other development tool authors must do in order for their compilers to output IL code that will allow them to integrate well with other .NET languages. Microsoft currently provides several compilers that produce IL code targeting the .NET Common Language Runtime: C++ with managed extensions, C#, Jscript, and Visual Basic.
In addition, several companies other than Microsoft are producing compilers for languages that also target the .NET Common Language Runtime. Currently support for COBOL, Eiffle, Fortran, Perl, Python, Scheme, and many more have been announced by various vendors. For a current list check http://msdn.microsoft.com/ vstudio/partners/language/default.asp.
Why should you care about the details of IL? Because this is how .NET manages many of its cross-language features. No Interface Definition Language is required to enable cross-language functionality because IL metadata handles the entire translation overhead. For instance, with an exception object defined by IL, the same object can be caught regardless of the .NET language used. Your component written in C# can raise an exception that can be caught by the Fortran application using it. No more worries about different calling conventions or data types, just seamless interoperability.
Cross-language inheritance is another feature made possible by the use of IL. You can now create new classes based on components written in other languages, without needing the source code to the base component. For example, you can create a class in C++ that derives from a class implemented in Visual Basic. .NET can enable this because it defines and provides a type system common to all .NET languages.
One of the great challenges of developing applications under the Windows DNA specification was in debugging applications developed in a variety of languages. Thanks to the unified development environment of Visual Studio.NET and the use of IL as the output of all .NET languages, cross-language debugging is possible without resorting to assembly language. The .NET Common Language Runtime fully supports debugging applications that cross language boundaries. The runtime also provides built-in stack-walking facilities, making it much easier to locate bugs and errors.
1.4.2 Platform and Processor Independence
The intermediate language is CPU-independent, and it’s much higher level than most machine languages. Once written and built, a managed .NET application can execute on any platform that supports the .NET Common Language Runtime. Because the .NET Common Type System defines the size of the base data types that are available to .NET applications, and applications run within the Common Language Runtime environment, the application developer is insulated from the specifics of any hardware or operating system that supports the .NET platform.
Although at the time of this writing .NET applications run only on Windows platforms, on June 27th, 2001 Microsoft announced that it had reached an agreement with Corel to develop a shared-source implementation of a C# compiler and the .NET Framework infrastructure components for the FreeBSD version of Unix. This is currently expected to be available in a beta version sometime in the first half of 2002.
A few weeks later, on July 10, 2001 Microsoft gave the go-ahead to an open source version of .NET being planned by Xamarin, the developer the popular GNOME user interface for Linux. You can find the project, called Mono, at www.go-mono.net. The group is developing a C# language compiler, along with the .NET Common Language Runtime. Work has also begun on the Base Class Library. The release of the first usable Project Mono code is planned for the end of 2001.
1.4.3 Automatic Memory Management
The mere mention of a memory leak problem brings forth images of endless hours of debugging for developers who’ve come from a development environment that did not offer automatic memory management. Even for those fortunate enough to work with this in some form have likely spent some time trying to hunt down obscure bugs caused by tricky code that circumvented the resource management methodology.
Developers coming from Visual Basic or COM backgrounds are familiar with the reference counting technique. This technique recovers the memory used by an object when no other object has a reference to it, essentially when it’s no longer needed. Although this sounds perfect in theory, in practice it has a few problems. One of the most common is a circular reference problem where one object contains a reference to another object which itself contains a reference back to the first object. When the memory manager looks for objects that are not in use, these objects will always have a reference count greater than zero, so unless they are implicitly deconstructed, their memory may never be recovered.
For a C or C++ programmer—accustomed to ensuring that objects are properly destroyed, essentially managing memory on their own—this sounds perfectly normal, and a good reason for not trusting anyone else to take care of managing resources. However, in the .NET environment, Microsoft is striving to make developing software easier. Later in this chapter, we cover a how .NET garbage collection works, and the improvements that have been made over strict reference counting or manual memory management approaches.
1.4.4 Versioning Support
Anyone who doesn’t understand the phrase “DLL Hell” hasn’t been developing (or at least supporting) software for Windows very long. For the uninitiated, you’ll find yourself in DLL Hell someday when a customer installs a software package that uses one of the same DLLs as your application. However, your application used version 1.0 of this DLL, and the new software replaces it with version 1.1. We developers all always make sure everything is 100% backwards-compatible, right? The new DLL makes your application exhibit some strange problem or perhaps just stop working altogether. After a lot of investigation, you figure out what the offending DLL is and have the customer replace the new one with the version that works with your software. Now their new software doesn’t work… welcome to DLL Hell. Many developers resort to simply installing every DLL their application requires in the application directory so that it will be found first when the application loads the libraries. This defeats the purpose of shared libraries, but it is one way around the problem. COM was going to change this; one of its primary tenants was that you never changed a methods interface you simply add new methods. Unfortunately, software developers are frequently perfectionists, and leaving a “broken” function alone just chafes some people. Problem is, changing a components interface once it’s in use can have adverse affects on the client software that expected the old behavior.
Because COM objects are loaded using information in the Registry, simply placing the DLL or control in the application directory doesn’t work for this problem. The .NET architecture now separates application components so that an application always loads the components with which it was built and tested. If the application runs after installation, the application should always run. This is done with assemblies, which are .NET-packaged components. Although current DLLs and COM objects do contain version information, the OS does not use this information for any real purpose. Assemblies contain version information that the .NET Common Language Runtime uses to ensure that an application will load the components it was built with.
1.4.5 Support for Open Standards
In today’s world, not every device you may want to work with is going to be running a Microsoft OS or using an Intel CPU. Realizing this, the architects of .NET are relying on XML and its most visible descendant, SOAP, an emerging standard for sending messages across the Internet that activates programs or applications regardless of their underlying infrastructure. SOAP will provide the means for disparate systems to exchange information easily, but even more, SOAP allows you to invoke methods on remote systems and return the results. Because SOAP is a simple text-based protocol similar to HTTP, it can easily pass through firewalls, unlike DCOM or CORBA objects.
Other standards employed by the .NET platform include Universal Description, Discovery, and Integration (UDDI), a directory of companies and their XML interfaces and the Web Services Description Language (WSDL), which describes what a piece of application code can do. By basing much of .NET on open standards and by submitting the proposed draft standards for C# and the .NET Common Language Infrastructure to ECMA, an international standards organization, Microsoft hopes to see its version of the future of software adopted beyond its own domain.
1.4.6 Easy Deployment
Today, developing installations for Windows-based applications can be incredibly difficult, to the point that most companies use third party tools for developing their installation programs, and even then it’s not pleasant. There are usually a large number of files to be installed in several directories, various Registry settings, installation of required COM components, and shortcuts that need to be created, and so on. Completely uninstalling an application is nearly impossible, most leave bits and pieces of themselves around even if they provide an uninstall feature. With the release of Windows 2000, Microsoft introduced a new installation engine that helps with some of these issues, but it is still possible that the author of a Microsoft Installer Package may fail to do everything correctly. Even with those third party tools specifically designed to make developing installation programs easier, it is still frequently a monumental task to correctly install a retrieval application.
The .NET design team must have felt the same way about this problem, because .NET plans to do away with these issues for good. .NET components are not referenced in the Registry, thanks to the use of metadata and reflection, components are self describing. In fact, installing many .NET applications will require no more than copying their files to a directory, and uninstalling an application will be as easy as deleting those files.
1.4.7 Distributed Architecture
Today’s distributed applications are much different than those we will see in the future. Microsoft certainly believes this; they say they are betting the company on the concept of distributed Web services.
For example, today when a user is interacting with a portal site, it appears to them that they are working with one remote server. Most of us know that is normally not the case, at least for a site of any significant size. There are various servers and applications behind the scenes are accessing information on several remote sites, combining it with information from their user database and merging it all into an integrated product that is delivered to the user via their browser.
As useful as these types of applications are, they are all very complex to develop and maintain. Each provider of information has developed different interfaces to access data and processes on their servers. This redundant development is grossly inefficient and for the most part fairly boring, so there has been a great deal of activity around three standards to streamline the process: XML, SOAP, and UDDI.As we discussed earlier, these are used in .NET and also in competing, less well known initiatives from IBM and Sun.
1.4.8 Interoperability with Unmanaged Code
As you can probably guess, unmanaged code is code that isn’t managed by the .NET Common Language Runtime. However, this code is still run by the CLR, it just doesn’t get the advantages that it offers, such as the Common Type System and Automatic Memory Management. You will probably end up using unmanaged code in a couple of different situations:
■ Calling DLL functions: There is a lot of functionality locked inside DLLs today. Not every company is going to rush to deliver a .NET component version of their products, so if you need to interface with them, you’ll be calling unmanaged code.
■ Using COM components: This is likely to be for pretty much the same reasons you might be required to call DLL functions.
■ Calling .NET services from COM components: Although this sounds a little odd, it is possible. A COM client can be made to call a .NET component as though it was a COM server.
Here’s a little more information on the COM interoperability issue. Microsoft didn’t want to force companies to abandon their existing COM components; especially because many of Microsoft’s own products are COM-based today. COM components interoperate with the .NET runtime through an interop layer that handles all the work required when translating messages that pass back and forth between the managed runtime and the COM components operating as unmanaged code.
On the other side of the coin, companies with a vested interest in COM technology might want to use a few bits and pieces from the .NET platform, sticking a toe in before taking the plunge. COM clients can easily interface with .NET components through the COM interop layer.
1.4.9 Security
Distributed component-based applications require security, and thus far Microsoft hasn’t had a lot of positive feedback about its products’ security features.
Fortunately, the .NET designers decided to take a new approach, different than traditional OS security, which provides isolation and access control based on user accounts, and also unlike the model used by Java, where code that is not trusted is run in a “sandbox,” with no access to critical resources. The .NET Framework provides a fine-grained control of application security. Security for .NET applications starts as soon as a class is loaded by the CLR.
Before the class loader instantiates a class, security information—such as accessibility rules and self-consistency requirements—are checked. Calls to class methods are checked for type safety. If you’ve ever heard of a security vulnerability caused by a “buffer overrun,” you can understand why this is important. With verified code, a method that is declared as taking a 4-byte integer parameter will reject an attempt to call it with an 8-byte integer parameter. Verification also prevents applications from executing code at a random location in memory, a common tactic in buffer overflow exploits.
Additionally, as code requests access to certain resources, the class credentials are verified. .NET security crosses process boundaries and even machine boundaries to prevent access to sensitive data or resources in a distributed application environment. The following are some of the basic elements of the .NET security system:
■ Evidence-based security is a new concept introduced by the .NET Framework. An assembly contains several important pieces of information that can be used to decide what level of access to grant the component. Some of the information used includes what site the component was downloaded from, what zone that site was in, (Internet, intranet, local machine, and so on) and the strong name of the assembly. The strong name refers to an encrypted identifier that uniquely defines the assembly and ensures that it has not been tampered with.
■ The .NET Common Language Runtime further provides security using a Policy-Driven Trust Model Using Code Evidence. It sounds worse than it really is. Essentially this is a system of security policies that can be set by an administrator to allow certain levels of access based on the component’s assembly information. The policies are set at three levels: the enterprise, the individual machine, and the user.
■ Calling .NET Framework methods from the Base Class Library get the benefits of built in security. That is, the developer doesn’t have to make explicit security calls to access system resources. However, if your components expose interfaces to protected resources, you will be
expected to take the appropriate security measures.
■ Role-based security plays a part in the .NET security scheme. Many applications need to restrict access to certain functions or resources based on the user, and .NET introduces the concepts of identities and principals to incorporate these functions.
■ Authentication and authorization functions are accessed through a single API. It can easily be extended to incorporate application-specific logic as required. Authentication methods include basic operating system user identification, basic HTTP,ASP.NET forms, Digest and Kerberos, as well as the new .NET service, Microsoft .NET Passport.
■ Isolated storage is a special area on disk assigned to a specific assembly by the security system. No access to other files or data is allowed, and each assembly using isolated storage is separated from each other. Isolated storage can be used for a saving a components state, or saving settings, and can be used by components that do not have access to read and write files on the system.
■ A robust set of cryptographic functions that support encryption, digital signatures, hashing, and random-number generation are included in the .NET Framework. These are implemented using well-known algorithms, such as RSA, DSA, Rijndael/AES, Triple DES, DES, and RC2, as well as the MD5, SHA1, SHA-256, SHA-384, and SHA-512 hash algorithms. Additionally, the XML Digital Signature specification, under development by the Internet Engineering Task Force (IETF) and the World Wide Web Consortium (W3C), is also available.
The .NET Framework uses these cryptographic functions to support various internal services. The cryptographic objects are also available in the Base Class Library for developers who require this functionality.
1.4.10 Performance and Scalability
Let’s face it—there is no magic bullet that will allow a poorly designed application to scale well. What the .NET Framework is giving you are tools to make it easier to design better performing software. One big gain for Web development will come from ASP.NET’s improved support for keeping code, data, and presentation separate. .NET offers features for transaction handling and component pooling, but makes them easier to use than they were in previous incarnations, so more development will be likely to take advantage of them. The .NET Base Class Library has an enormous set of functionality, which means that you will have to write less basic code and spend more time refining the features and performance of your applications.
New versions of Microsoft software christened with the .NET emblem offer improved performance over earlier versions. SQL Server.NET offers quite an enhancement over earlier versions of the database engine, and other server products offer enhanced scalability as well. When you redesign an application around the .NET Framework, take advantage of the latest advances all around and see what the results are.
1.5 Components of the .NET Architecture
As we mentioned earlier, there is a lot to the .NET Framework. In this section, we identify the individual components and describe their features and how they fit into the overall picture.
1.5.1 .NET Runtime
The heart of the .NET Framework is the CLR. Similar in concept to the Java Virtual Machine, it is a runtime environment that executes MSIL code. Unlike the Java environment, which is the concept of one language for all purposes, the .NET platform supports multiple programming languages through the use of the Common Language Specification, which defines the output required of compilers that want to target the CLR.
1.5.2 Managed/Unmanaged Code
Because all code targeted at the .NET platform runs with the CLR environment, it is referred to as managed code. This simply means that the execution of the code and its behavior is managed by the CLR. The metadata available with managed code contains the information required to allow the CLR to manage its safe execution. By safe execution we mean memory and security management, type safety, and interlanguage interoperability. Unmanaged code can write to areas of memory it does not own, execute instructions at arbitrary locations in memory, and exhibit any number of other bad behaviors that cannot be managed or prevented by the CLR. Most of the applications running on Windows today are unmanaged.
1.5.3 Intermediate Language
The .NET intermediate language, MSIL (Microsoft Intermediate Language), is defined in the Common Language Specification. It is an amalgam of a low-level language similar in many ways to a machine language and a higher object language. You can write applications directly in MSIL, much as you can write directly in assembly language. Thankfully, this is not necessary for most purposes.
1.5.4 Common Type System
.NET applications, regardless of their source languages all share a common type system. What this means is that you no longer have to worry when doing development in multiple languages about how a data type declared in one language needs to be declared in another. Any .NET type has the same attributes regardless of the language it is used in. Furthermore, all .NET data types are objects, derived from System.Object. Because all data types derive from a common base class, they all share some basic functionality, for example the ability to be converted to a string, serialized, or stored in a collection.
1.5.5 .NET Base Class Library (BCL)
If I could have bought a library that offered everything the .NET Base Class Library offers when I started programming, a year’s salary would have seemed reasonable—there really is that much to it. Almost everything in the .NET environment is contained within the BCL. Let’s look at a “Hello World” example:
using System;
class Hello
{
public static void Main()
{
Console.WriteLine(“Hello World”);
}
}
The only function contained in this simple program is a call to the WriteLine method of the Console class. What is really unique about the .NET environment is that .NET languages don’t have to implement even the most basic functions; they are available in the BCL. Because all .NET languages share the same common set of libraries, the code being executed by your C# program is the same code being executed by a program written in another language. This means that all languages that target the .NET environment essentially share the same capabilities, except they have different syntax.
Some people will wonder why we even have different languages if they all have the same capabilities. A few reasons immediately spring to mind:
■ Programmers don’t like change.
■ Programmers usually have a favorite language.
Imagine if Microsoft had come out with all the good things in .NET, but said that in order to use it, we all had to learn a new language. Lots of people might have never even given it an honest look unless forced by their employers. Making it available for all languages makes it seem less like the chore of learning a new language and more like the excitement of receiving a new library with tens of thousands of functions that will make your life as a developer easier.
1.5.6 Assemblies
Assemblies are the means of packaging and deploying applications and components in .NET. Just like a compiled application or component today, assemblies can be made up of either single or multiple files. An assembly contains metadata information (covered in the next section), which is used by the CLR for everything from type checking and security to actually invoking the components methods. All of this means that you don’t need to register .NET components, unlike COM objects.
1.5.7 Metadata
Metadata is the feature that lets the CLR know the details about a particular component. The metadata for an object is persisted at compile time and then queried at runtime so that the CLR knows how to instantiate objects, call their methods, and access their properties. Through a process called reflection, an application can interrogate this metadata and learn what an object exposes. This is similar to the way IDispatch and type libraries work in COM.
Unlike COM, where the information about a component can be found in type libraries and the Registry, where it is only associated with the actual component, .NET metadata is stored within the component itself in a binary format packaged inside the assembly. The metadata contains a declaration for every type and a declaration, including names and types, for all of its members (methods, fields, properties, and events). For every method implemented by the component, the metadata contains information that the loader uses to locate the method body. It is also possible (but not required) for the creator of a class type to associate help text and comments with a method or parameter in the metadata, similar to the way that information can be associated with a component using information within the IDL in the COM world.
Besides the low-level information described in this section, a component also includes information regarding its version and any culture information specific to the component. The culture information can be queried at runtime and used in developing localized applications. Look at the System.Reflection.AssemblyName class as a place to get started, and check out the CultureInfo class to see how extensive the culture support of .NET components can be. You can also use reflection to determine a components version, which might be useful if your application is dynamically loading components and needs to make adjustments for different versions.
1.5.8 Assemblies and Modules
.NET applications are deployed as assemblies, which can be a single executable or a collection of components. When you create a .NET application, you are actually creating an assembly, which contains a manifest that describes the assembly.
This manifest data contains the assembly name, its versioning information, any assemblies referenced by this assembly and their versions, a listing of types in the assembly, security permissions, its product information (company, trademark, and so on), and any custom attribute.
An assembly that is shared between multiple applications also has a shared name (also known as a strong name). This is a key pair containing a globally unique name (think GUID from COM) as well as an encrypted digital signature to prevent tampering. This information is optional and may not be in a component’s manifest if it was not intended as a shared component.
Creating .NET modules that do not contain assembly manifest data is also possible. These modules can then be added to an assembly, by including it in the Visual Studio project. An example of why you might want to do this would be if you had a component that was logically divided into several subcomponents that would be best distributed and versioned as a single unit.
1.5.9 Assembly Cache
The assembly cache is a directory normally found in the \WinNT\Assembly directory. When an assembly is installed on the machine, it can be merged into the assembly cache, depending upon the installation author or the source of the assembly. The assembly cache has two separate caches: a global assembly cache and a transient assembly cache. When assemblies are downloaded to the local machine using Internet Explorer, the assembly is automatically installed in the transient assembly cache. Keeping these assemblies separated prevents a downloaded component from impacting the operation of an installed application.
Now for what may be a great feature that you won’t think of until your project is finished. The assembly cache will hold multiple versions of an assembly, and if your installation programs are written correctly, they cannot overwrite a previous version of an assembly that may be needed by another application. You read that right, the .NET Framework is making a solid effort to banish DLL Hell.
Just to clarify what this means, the assembly cache can contain multiple versions of a component, as an example, we’ll say we’ve installed versions 1.0 and 1.1 of MyComponent.dll on a system. If an application was built and tested using Version 1.0 of MyComponent.dll, the CLR will see this when it reads the application’s metadata and will load Version 1.0 of MyComponent.dll, even though a later version of the assembly exists in the cache. The application will continue to function normally because the code that it is executing is the same code that it was built and tested with. Thanks to this feature, you also don’t have to maintain compatibility with earlier versions of your components. This feature alone is enough to make the .NET architecture great.
1.5.10 Reflection
Reflection is the means by which .NET applications can access an assembly’s metadata information and discover its methods and data types at runtime. You can also dynamically invoke methods and use type information through late binding through the Reflection API.
The System.Type class is the core of the reflection system. System.Type is an abstract class that is used to represent a Common Type System type. It includes methods that allow you to determine the type’s name, what module it is contained in, and its namespace, as well as if it is a value or reference type.
For example, using the System.Reflection.Assembly class you can retrieve all of the types in an assembly, and all of the modules contained in the assembly. To invoke a method of a class loaded at runtime, you would use a combination of the Activator class to create an instance of the type you had obtained through the Assembly class. Then you can use the type’s GetMethodmethod to create a MethodInfoobject by specifying the method name that you wish to invoke. At this point, you can use the MethodInfo object’s Invoke method, passing it the instance of the type you created with the Activator class.
It sounds a lot like some of the nasty bits of COM programming, but the Reflection API genuinely makes it a lot easier.
1.5.11 Just In Time Compilation
The .NET CLR utilizes Just In Time (JIT) compilation technology to convert the IL code back to a platform/device–specific code. In .NET, you currently have three types of JIT compilers:
■ Pre-JIT: This JIT compiles an assembly’s entire code into native code at one stretch. You would normally use this at installation time.
■ Econo-JIT: You would use this JIT on devices with limited resources. It compiles the IL code bit-by-bit, freeing resources used by the cached native code when required.
■ Normal JIT: The default JIT compiles code only as it is called and places the resulting native code in the cache.
In essence, the purpose of a JIT compiler is to bring higher performance to interpreted code by placing the compiled native code in a cache, so that when the next call is made to the same method/procedure, the cached code is executed, resulting in an increase in application speed.
1.5.12 Garbage Collection
Memory management is one of those housekeeping duties that takes a lot of programming time away from developing new code while you track down memory leaks. A day spent hunting for an elusive memory problem usually isn’t a productive day.
.NET hopes to do away with all of that within the managed environment with the garbage collection system. Garbage collection runs when your application is apparently out of free memory, or when it is implicitly called but its exact time of execution cannot be determined. Let’s examine how the system works.
When your application requests more memory, and the memory allocator reports that there is no more memory on the managed heap, garbage collection is called. The garbage collector starts by assuming everything in memory is trash that can be freed. It then walks through your application’s memory, building a graph of all memory that is currently referenced by the application. Once it has a complete graph, it compacts the heap by moving all the memory that is genuinely in use together at the start of the free memory heap. After this is complete, it moves the pointer that the memory allocator uses to determine where to start allocating memory from the top of this new heap. It also updates all of your application’s references to point to their new locations in memory. This approach is commonly called a mark and sweep implementation.
The exception to this is with individual objects over 20,000 bytes. Very large objects are allocated from a different heap, and when this heap is garbage collected, they are not moved, because moving memory in this size chunks would have an adverse effect on application performance.
As you can see, garbage collection involves a lot of work, and it does take some time. A number of performance optimizations involved in the .NET garbage collection mechanism make it much more than the simple description given here.
Normally you will just let the CLR take care of running garbage collection when it is required. However, at times you may want to force the garbage collector to run, perhaps before starting an operation that is going to require a large amount of memory. To do this, just callGC.Collect().And if you want to report on your memory use at various points during your application’s execution to help you determine when might be a good time to force collection, you can use GC.GetTotalMemory(bool forceFullCollection).
As you can probably guess, the parameter forceFullCollection determines if garbage collection is run before returning the amount of memory in use.
1.6 Advantages/Disadvantages
The aim of .net framework is to make the development of desktop, web and mobile applications easier. Microsoft provides a full-fledged IDE called Visual Studio to facilitate the development of .NET based applications.
1. The .NET applications are built to execute on the CLR (Common Language Runtime) and so same libraries are readily available for use regardless of the running platform/OS.
2. Rich set of libraries are already available ranging from graphic rendering to file reading, which reduces quantity of code and ultimately supports RAD (Rapid Application Development).
3. The .NET Visual Studio IDE provides WYSIWYG (What You See Is What You Get) development. It provides various features already available in the IDE itself that aid in development (like the Toolbox with useable controls).
4. The .Net Frammework simplifies testing, debugging, runtime diagnostics/tracing, and deployments and maintenance. The .Net Framework handles the details of locating and loads the components.
5. The .NET framework enables the developer and the system administrator to specify method level security. It uses industry-standard protocols such as TCP/IP, XML, SOAP and HTTP to facilitate distributed application communications. This makes distributed computing more secure.
6. The .NET framework has a consistent programming model. Despite the syntactical differences among various .NET based programming languages, the CTS (Common Type System) defines how types are declared, used, and managed in the CLR (Common Language Runtime), and is also supports cross-language integration. .NET Framework supports the exchange of types and object instances between libraries and applications written using any conforming .NET language.
7. The .NET framework has its own managed environment that handles many of the important tasks for the developers. This frees developers from worrying about memory allocation and handling, memory leaks, garbage collection, thread and process management, exception handling, among others.
8. The .NET framework provides high scalability options for applications. It has abundant tools and libraries that enable developers to write fast, highly concurrent and wide scaling applications, thus making developer able to build a real world performance-critical application like ones required in the web.
9. The .NET framework provides Cross-platform and/or platform neutral development. It supports the service-oriented Architecture making developers able to focus on development without worrying of what OS or programming language the consumer is using. Thus, applications can be technology-agnostic and can be compliant with future-technologies.
10. The .NET framework has built-in security systems designed for varying environments. New security vulnerabilities are identified and addressed in a fashion, thus relieving developers from most of the hassles with minimal effort.
Few disadvantages of .NET that can be comparatively stated are:
• Multi-platform isn’t completely supported
• Managed code can be slower than native code
• Compiled-code can be reverse engineered, if not secured, in majority of cases
• Applications require .NET Framework to be essentially installed for execution
• Application development and deployment are comparatively costlier than other languages.
CHAPTER 2
WINDOWS DEVELOPMENT USING .NET

2.1 Overview
.NET provides a wide range of user controls and libraries along with event-driven architecture that aids in development of rich and interactive User Interface (UI).
2.2 Structured Programming and OOP
2.2.1 Structured Programming
Structured programming (sometimes known as modular programming) is a subset of procedural programming that enforces a logical structure on the program being written to make it more efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBase are designed with features that encourage or enforce a logical program structure. Structured programming frequently employs developers mapping out the overall program structure into separate subsections. A defined function or set of similar functions is coded in a separate module or sub-module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure. Program flow follows a simple hierarchical model that employs looping constructs such as “for,” “repeat,” and “while”.
Structured programming consists of breaking big problems into smaller problems (modules), then further breaking those into still smaller problems, and so on, until a level of such simplicity is reached that the implementation is obvious to the programmer expected to do the programming.
2.2.2 Object Oriented Programming
Object Oriented Programming (OOP) is a programming paradigm organized around “objects” rather than “actions” and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data. The programming challenge was seen as how to write the logic, not how to define the data. Object-oriented programming takes the view that what we really care about are the objects we want to manipulate rather than the logic required to manipulate them.
Object-oriented programming (OOP) represents concepts as “objects” that have data fields (attributes that are the properties or that describe the object) and associated procedures known as methods (implementations that perform actions). Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs. Classes, on the other hand, can be referred to as templates of the objects.
2.2.3 OOP key terminologies
Class: A class is a blueprint/prototype/template from which objects are created.
Object: An object is a unified bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. They are real instances of classes that exist and occupy space/memory.
Encapsulation: Treating related properties, methods, and other members as a single unit or object.
Abstraction: Providing only essential information to the outside world and hiding their background details.
Inheritance: Acquisition of state and behavior from other (base) classes.
Interface: Contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface.
Polymorphism: One interface, multiple functions. The ability to use an operator or function in different ways, i.e. giving different meaning or purposes to the operators or functions is polymorphism.
2.3 Visual C#
C♯ is intended to be a simple, modern, general-purpose, object-oriented programming language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. C♯ is designed for Common Language Infrastructure (CLI), which consists of libraries and runtime environment that allows use of various high-level languages to be used on different computer platforms and architectures. You can use C♯ to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much more. Visual C♯ provides an advanced code editor, convenient user interface designers, integrated debugger, and many other tools to make it easier to develop applications based on the C♯ language and the .NET Framework. The most recent version is C♯ 5.0, which was released on August 15, 2012. As an object-oriented language, C# supports the concepts of encapsulation, inheritance, and polymorphism.
2.4 Windows Forms
There are a number of ways to develop graphical user interfaces (GUI) for Microsoft Windows with the C# language in Microsoft Visual Studio. With the introduction of Visual Studio 2003 .NET, Windows Forms tools were added.
2.4.1 Introduction
Windows Forms (also called WinForms) is the name given to the graphical application programming interface (API) included as a part of Microsoft .NET Framework, providing access to native Microsoft Windows interface elements. Windows Forms create GUIs for programs. A form is a graphical element that appears on the desktop. A form can be a dialog, a window or an MDI window (multiple document interface window). Windows Forms is built on the components provided by Windows API itself and some controls merely wrap underlying Windows components. So, Windows Forms is mainly a wrapper around components provided by Windows itself.
A Windows Forms application is an event-driven application supported by Microsoft’s .NET Framework. Event is a signal sent to the application when some action occurs, like mouse click or key press, so that the application can execute some logic as defined by the developer. Unlike a batch program, it spends most of its time simply waiting for the user to do something, such as fill in a text box or click a button. So, a form can be ultimately considered as a blank slate that a developer enhances with controls to create a user interface (UI) and with code (generally event-driven) to manipulate data.
In Windows Forms, a form is a visual surface on which you display information to the user. You ordinarily build Windows Forms applications by adding controls to forms and developing responses to user actions, such as mouse clicks or key presses. A control is a discrete user interface (UI) element that displays data or accepts data input. Windows Forms contains a variety of controls that you can add to forms: controls that display text boxes, buttons, drop-down boxes, radio buttons, and even Web pages. When a user does something to your form or one of its controls, the action generates an event. Your application reacts to these events by using code, and processes the events when they occur.
With the Visual Studio drag-and-drop Windows Forms Designer, you can easily create Windows Forms applications. Just select the controls with your cursor and add them where you want on the form. The designer provides tools such as gridlines and snap lines to take the hassle out of aligning controls.
2.4.2 Components of IDE
Solution: A solution contains all of the projects required to meet a particular business goal. For example, an “accounting solution” may contain projects for general ledger, accounts receivable, and accounts payable. The Solution can be browsed via “Solution Explorer” window.
Project: The set of specific items such as source code files, icons, images, scripts, database connections and other items required to create a project. For example, a project to create one software program might contain a few source code files that are compiled together.
Properties Window: Shows the properties available for the object that is currently selected. The selected element is basically a class’s object instance, and the property window is used to modify that object’s member field(s) or attributes, or associate some action (event) to it.
Output window: Shows errors or other details when the application is compiled.
Document/Editor tabs: Shows currently open code or design documents or views containing the corresponding code/UI.
Toolbars: Shows frequently used commands.
Toolbox: Shows categorized collection of available controls that you can visually add to the form.
CHAPTER 3
WEB DEVELOPMENT USING .NET

3.1 Overview
Web development has been made easier by .NET. It provides a multitude of ways a developer can develop web applications and web sites.
3.2 HTML
HTML (HyperText Markup Language) is the main markup language for creating web pages and other information that can be displayed in a web browser. HTML is written in the form of HTML elements consisting of tags enclosed in angle brackets (like), within the web page content. HTML tags most commonly come in pairs like

and

, although some tags represent empty elements and so are unpaired, for example


. The first tag in a pair is the start tag, and the second tag is the end tag (they are also called opening tags and closing tags respectively). In between these tags user can add text, further tags, comments and other types of text-based content.
The purpose of a web browser is to read HTML documents and compose them into visible or audible web pages. The browser does not display the HTML tags, but uses the tags to interpret the content of the page.
HTML elements form the building blocks of all websites. HTML allows images and objects to be embedded and can be used to create interactive forms. It provides a means to create structured documents by denoting structural semantics/meanings for text such as headings, paragraphs, lists, links, quotes and other items. It can embed scripts written in languages such as JavaScript which affect the behavior of HTML web pages. Web browsers can also refer to Cascading Style Sheets (CSS) to define the look and layout of text and other material.
Example:

Sample Document

An HTML Document

This is a simple document.

 

The general form of an HTML element is therefore: content. Some HTML elements are defined as empty elements and take the form . Empty elements may enclose no content, for instance, the BR tag or the inline IMG tag. The name of an HTML element is the name used in the tags. Note that the end tag’s name is preceded by a slash character, “/”. If attributes are not mentioned, default values are used in each case. Most of the attributes of an element are name-value pairs, separated by “=” and written within the start tag of an element after the element’s name. The value may be enclosed in single or double quotes. Leaving attribute values unquoted is considered unsafe. In contrast with name-value pair attributes, there are some attributes that affect the element simply by their presence in the start tag of the element. E.g. the “id” attribute provides a document-wide unique identifier for an element.
DOM
The Document Object Model (DOM) is an API for manipulating HTML and XML documents. It provides a structural representation of the document, enabling users to modify its content and visual presentation by using a scripting language such as JavaScript. A document object model (DOM) is an application programming interface (API) for representing a document (such as an HTML document) and accessing and manipulating the various elements (such as HTML tags and strings of text) that make up that document. JavaScript-enabled web browsers have always defined a document object model; a web-browser DOM may specify, for example, that the forms in an HTML document are accessible through the forms[] array of the document object.

Figure 2: The DOM Overview

The DOM representation in tree structure for the HTML example above is as shown below.

Figure 3: The DOM Overview of a sample HTML
3.3 JavaScript
JavaScript is a scripting language developed by Netscape to enable Web authors to design interactive sites. Although it shares many of the features and structures of the full Java language, it was developed independently. JavaScript can interact with HTML source code, enabling Web authors to spice up their sites with dynamic content. JavaScript is an open language that anyone can use without purchasing a license. It is supported by almost all browsers.
JavaScript is designed primarily for adding interactivity to Web pages and creating Web applications. The language was first implemented by Netscape Communications Corp. in Netscape Navigator 2 beta (1995). JavaScript was invented by Brendan Eich. It was adopted by ECMA (a standard association) since 1997. JavaScript is different from the Java language (developed in the 1990s at Sun Microsystems). Client-side JavaScript programs, or scripts, can be embedded directly in HTML source of Web pages. Depending on the Web developer’s intent, script code may run when the user opens the Web page, clicks or drags some page element with the mouse, types something on the keyboard, submits a form, leaves the page, among many other actions.
JavaScript can function as both a procedural and an object oriented language. JavaScript code may be either interpreted or compiled using a just-in-time (JIT) compiler. At run time, the browser decides whether (parts of) script code should be JIT-compiled for better performance. This makes JavaScript significantly faster and therefore more suitable for complex performance-demanding Web applications. Recent versions of all popular browsers have JavaScript JIT-compilers. JavaScript is available in Microsoft Internet Explorer (beginning with version 3.0), Firefox, Safari, Opera, Google Chrome, among others.
Use in web
The most common use of JavaScript is to write functions that are embedded in or included from HTML pages and that interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:
• Loading new page content or submitting data to the server via AJAX without reloading the page (for example, a social network might allow the user to post status updates without leaving the page).
• Animation of page elements, fading them in and out, resizing them, moving them, etc.
• Interactive content, for example games, and playing audio and video.
• Validating input values of a web form to make sure that they are acceptable before being submitted to the server.
• Transmitting information about the user’s reading habits and browsing activities to various websites. Web pages frequently do this for web analytics, ad tracking, personalization or other purposes.
Example:

Welcome to JavaScript

Please input a number.



3.4 jQuery
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 and is currently used by over 80% of the 10,000 most visited websites. jQuery is the most popular JavaScript library in use today.
jQuery’s syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. The modular approach to the jQuery library allows the creation of powerful dynamic web pages and web applications. Microsoft includes it with Visual Studio for use within Microsoft’s ASP.NET framework.

CHAPTER 4
WEB SERVICES
4.1 Web Services
Web Services allow access to software components through standard web protocols such as HTTP and SMTP. Using the Internet and XML, we can now create software components that communicate with others, regardless of language, platform, or culture. By substituting the Internet for proprietary transport formats and adopting standard protocols such as SOAP, Web Services help software developers create building blocks of software, which can be reused and integrated regardless of their location.
A Web service is a method of communication between two electronic devices over a network. It is a software function provided at a network address over the web with the service always remaining on.
Many organizations use multiple software systems for management. Different software systems often need to exchange data with each other, and a web service is a method of communication that allows two software systems to exchange this data over the internet. The software system that requests data is called a “service requester”, whereas the software system that would process the request and provide the data is called a “service provider”.
Different software might be built using different programming languages, and hence there is a need for a method of data exchange that doesn’t depend upon a particular programming language. Most types of software can, however, interpret XML tags. Thus, web services can use XML (and now JSON) files for data exchange.
Rules for communication between different systems need to be defined, such as:
• How one system can request data from another system?
• Which specific parameters are needed in the data request?
• What would be the structure of the data produced? Normally, data is exchanged in XML files, and the structure of the XML file is validated against an .xsd file.
• What error messages to display when a certain rule for communication is not observed, to make troubleshooting easier?
All of these rules for communication are defined in a file called WSDL (Web Services Description Language), which has the extension .wsdl.
XML: Extensible Markup Language is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.
JSON: JavaScript Object Notation is an open standard format that uses human-readable text to transmit data objects consisting of attribute-value pairs. It is uses primarily to transmit data between a server and web application, as an alternative to XML.

Web services architecture

SOAP: Simple Object Access Protocol (SOAP) is a network protocol specification for exchanging structured information in the implementation of web services in computer networks. It relies on XML information set for its message format, and usually relies on other application layer protocols like HTTP or SMTP, for message negotiation and transmission.

Web Services Description Language: The Web Services Description Language (WSDL) is an XML-based interface description language that is used for describing the functionality offered by a web service. The acronym is also used for any specific WSDL description of a web service (also referred to as a WSDL file), which provides a machine-readable description of how the service can be called, what parameters it expects, and what data structures it returns. It thus serves a purpose that corresponds roughly to that of a method signature in a programming language.
WSDL is the language that UDDI uses. WSDL is an integral part of UDDI, an XML-based worldwide business registry.
WSDL is often used in combination with SOAP and XML Schema to provide web services over the Internet. A client program connecting to a web service can read the WSDL to determine what functions are available on the server. Any special data types used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL.
The current version of WSDL is WSDL 2.0.
The service provider sends a WSDL file to UDDI. The service requester contacts UDDI to find out who is the provider for the data it needs, and then it contacts the service provider using the SOAP protocol. The service provider validates the service request and sends structured data in an XML file, using the SOAP protocol. This XML file would be validated again by the service requester using an XSD file.

Universal Description, Discovery and Integration: UDDI is an XML-based standard for describing, publishing, and finding Web services. UDDI is a global registry that defines which software system should be contacted for which type of data. Each service provider registers itself in the UDDI global directory. When one software system needs one particular report/data, it would go to the UDDI and find out which other system it can contact for receiving that data. Once the software system finds out which other system it should contact, it would then contact that system using a special protocol called SOAP (Simple Object Access Protocol). The service provider system would first of all validate the data request by referring to the WSDL file, and then process the request and send the data under the SOAP protocol.
• UDDI is a specification for a distributed registry of Web services.
• UDDI is platform independent, open framework.
• UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.
• UDDI uses WSDL to describe interfaces to web services.
• UDDI is an open industry initiative enabling businesses to discover each other and define how they interact over the Internet.
UDDI has two parts: A registry of all a web service’s metadata including a pointer to the WSDL description of a service and a set of WSDL port type definitions for manipulating and searching that registry.
UDDI, SOAP and WSDL form the three foundation standards of web services.
Benefits of web services
Exposing the existing function on to network: A Web service is a unit of managed code that can be remotely invoked using HTTP, i.e., it can be activated using HTTP requests. So, Web Services allows you to expose the functionality of your existing code over the network. Once it is exposed on the network, other application can use the functionality of your program.
Connecting Different Applications (Interoperability): Web Services allows different applications to talk to each other and share data and services among themselves. Other applications can also use the services of the web services. For example VB or .NET application can talk to java web services and vice versa. So, Web services is used to make the application platform and technology independent.
Standardized Protocol: Web Services uses standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description and Service Discovery layers) uses the well-defined protocol in the Web Services protocol stack. This standardization of protocol stack gives the business many advantages like wide range of choices, reduction in the cost due to competition and increase in the quality.
Low Cost of communication: Web Services uses SOAP over HTTP protocol for the communication, so you can use your existing low cost internet for implementing Web Services. This solution is much less costly compared to proprietary solutions like EDI/B2B. Beside SOAP over HTTP, Web Services can also be implemented on other reliable transport mechanisms like FTP etc.
Multi-transport support: Web services using SOAP can also be implemented on multiple transport mechanisms like FTP, TCP/IP.
Universal accessibility: Web Services can be accessed via any devices that can connect to the internet. Web services can easily be used even in the presence of firewalls.
4.2 Web Services in Practice
You may have heard the phrase “software as services” and wondered about its meaning. The term service, in day-to-day usage, refers to what you get from a service provider. For example, you bring your dirty clothing to the cleaner to use its cleaning service. Software, on the other hand, is commonly known as an application, either off-the-shelf, shrink-wrapped, or a custom application developed by a software firm.
How can software be viewed as services? The example we are about to describe might seem far-fetched; however, it is possible with current technology. Imagine the following. As you grow more attached to the Internet, you might choose to replace your computer at home with something like an Internet Device, specially designed for use with the Internet. Let’s call it an iDev. With this device, you can be on the Internet immediately. If you want to do word processing, you can point your iDev to a Microsoft Word service somewhere in Redmond and type away without the need to install word processing software. When you are done, the document can be saved at an iStore server where you can later retrieve it. Notice that for you to do this, the iStore server must host a software service to allow you to store documents. Microsoft would charge you a service fee based on the amount of time your word processor is running and which features you use (such as the grammar and spell checkers). The iStore service charges vary based on the size of your document and how long it is stored. Of course, all these charges won’t come in the mail, but rather through an escrow service where the money can be piped from and to your bank account or credit card.
This type of service aims to avoid the need to upgrade of your Microsoft Word application. If you get tired of Microsoft Word, you can choose to use a different software service from another company. Of course, the document that you store at the iStore server is already in a standard data format. Since iStore utilizes the iMaxSecure software service from a company called iNNSA (Internet Not National Security Agency), the security of your files is assured. And because you use the document storage service at iStore, you also benefit from having your document authenticated and decrypted upon viewing, as well as encrypted at storing time. All of these things can be done today with Web Services.
In fact, Microsoft has launched a version of the “software as service” paradigm with its Passport authentication service. Basically, it is a centralized authentication service that you can incorporate into your web sites. For sites using the Passport authentication service, it’s no longer necessary to memorize or track numerous username/password pairs.
4.3 Web Services Framework
Web Services combine the best of both distributed componentization and the World Wide Web. It extends distributed computing to broader ranges of client applications. The best thing is that it does it by seamlessly marrying and enhancing existing technologies.
4.3.1 Web Services Architecture
Web Services are distributed software components that are accessible through standard web protocols. The first part of that definition is similar to that of COM/DCOM components. However, it is the second part that distinguishes Web Services from the crowd. Web Services enable software to interoperate with a much broader range of clients. While COM-aware clients can understand only COM components, Web Services can be consumed by any application that understands how to parse an XML-formatted stream transmitted through HTTP channels. XML is the key technology used in Web Services and is used in the following areas of the Microsoft .NET Web Services framework:
Web Service wire formats: The technology enabling universal understanding of how to perform data exchange between the service provider and consumer, and the format of data for the request and response.
Web Service description in WSDL (Web Services Description Language): The language describing how the service can be used. Think of this as the instructions on the washing machine at the laundry telling you where to put quarters, what buttons to push, etc.
Web Service discovery: The process of advertising or publishing a piece of software as a service and allowing for the discovery of this service.
Figure 4.1 depicts the architecture of web applications using Windows DNA, while Figure 4.2 shows .NET-enabled web applications architecture. As you can see, communication between components of a web application does not have to be within an intranet. Furthermore, inter-component communication can also use HTTP/XML.
Figure 4.1. Windows Distributed interNet Architecture

Figure 4.2. NET-enabled web application framework

4.3.2 HTTP GET and HTTP POST
As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. The GET and POST methods of the HTTP protocol have been widely used in ASP (Active Server Pages), CGI, and other server-side architectures for many years now. Both of these methods encode request parameters as name/value pairs in the HTTP request. The GET method creates a query string and appends it to the script’s URL on the server that handles the request. For the POST method, the name/value pairs are passed in the body of the HTTP request message.
4.3.3 SOAP
Simple Object Access Protocol (SOAP) is a network protocol specification for exchanging structured information in the implementation of web services in computer networks. It relies on XML information set for its message format, and usually relies on other application layer protocols like HTTP or SMTP, for message negotiation and transmission.
Similar to HTTP GET and HTTP POST, SOAP serves as a mechanism for passing messages between the clients and servers. In this context, the clients are web services consumers, and the servers are the web services. The clients simply send an XML-formatted request message to the server to get the service. The server responds by sending back yet another XML-formatted message. The SOAP specification describes the format of these XML requests and responses. It is simple, yet extensible, because it is based on XML.
SOAP is different than HTTP GET and HTTP POST because it uses XML to format its payload. The messages being sent back and forth have a better structure and can convey more complex information compared to simple name/value pairs in HTTP GET/POST protocols. Another difference is that SOAP can be used on top of other transport protocols, such as SMTP in addition to HTTP.
4.3.4 REST
REST provides a lighter weight alternative to SOAP. Instead of using XML to make a request, REST relies on a simple URL in many cases. In some situations you must provide additional information in special ways, but most Web services using REST rely exclusively on obtaining the needed information using the URL approach. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks.
Unlike SOAP, REST doesn’t have to use XML to provide the response. You can find REST-based Web services that output the data in Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS). The point is that you can obtain the output you need in a form that’s easy to parse within the language you need for your application.
4.3.5 SOAP VS REST
Simple Object Access Protocol (SOAP)
• SOAP builds an XML protocol on top of HTTP or sometimes TCP/IP.
• SOAP describes functions, and types of data.
• SOAP describes a standard way to communicate.
• Several programming languages have native support for SOAP
• Binary data that is sent must be encoded first into a format such as base64 encoded.
• Has several protocols and technologies relating to it: WSDL, XSDs, SOAP, WS-Addressing
Representational state transfer (REST)
• REST is very lightweight.
• Typically uses normal HTTP methods instead of a big XML format describing everything.
• REST is a very simple in that it uses HTTP GET, POST and PUT methods to update resources on the server.
• REST typically is best used with Resource Oriented Architecture (ROA). In this mode of thinking everything is a resource, and you would operate on these resources.
• As long as your programming language has an HTTP library, and most do, you can consume a REST HTTP protocol very easily.
• Binary data or binary resources can simply be delivered upon their request.
4.4 Web Services and Security
This section demonstrates how to incorporate security into your web service. We will do so in two ways: system security and application security. System-level security allows for restricting access to the web services from unauthorized clients. It is done in a declarative fashion, whereas application-level security is more flexible. With system-level security, you will most likely have the list of authorized clients’ IP addresses that you will let access your web service through the use of some configuration-management tools. With application-level security, you will incorporate the authentication into your web service, thus providing a more flexible configuration.

4.4.1 System Security
Because web services communication is done through HTTP, you can apply system-level security on web services just as you do for other web pages or resources on your web site.
There are a number of different ways you can secure your web services. For a B2B solution, you can use the IIS Administration Tool to restrict or grant permission to a set of IP addresses, using the Internet Protocol Security (IPSec) to make sure that the IP address in the TCP/IP header is authenticated. When you rely only on the client to provide the IP in the TCP/IP header, hackers can still impersonate other host IPs when accessing your web services. IPSec authenticates the host addresses using the Kerberos authentication protocol. You can also use a firewall to restrict access to your web services for your partner companies. For a business-to-consumer (B2C) scenario, you can take advantage of the authentication features of the HTTP protocol.
To show how to use the authentication feature of the HTTP protocol to secure your web services, let’s revisit the example web service we have in this chapter, PubsWS. All we have to do to secure PubsWS web service is go to the IIS Admin Tool and choose to edit the File Security properties for the PubsWS.asmx. Instead of keeping the default setting, which leaves this file accessible to all anonymous users, we change this setting to Basic Authentication. After this change, only users that pass the authentication can make use of the web service.
For real-life situations, of course, we are not just going to use the Basic Authentication method because it sends the username and password in clear text through the HTTP channel. We would choose other methods, such as Secure Sockets Layer (SSL) underneath Basic Authentication, so that the data passed back and forth is secure. Available methods include:
Basic Authentication: Sends the username and password to the web server in clear text. IIS authenticates the login against the database of users for the domain.
Basic over SSL Authentication: Similar to Basic Authentication, except that the username and password are sent with Secure Sockets Layer (SSL) encryption.
Digest Authentication: Uses a hashing technique, as opposed to SSL encryption, to send client credentials securely to the server.
Integrated Windows Authentication: Good for intranet scenarios only. Uses the login information of the client for authentication.
Client Certificates Authentication: Requires each of the clients to obtain a certificate that is mapped to a user account. The use of client-side digital certificates is not widespread at this time.

4.4.2 Application Security
A less systematic way of securing your web services involves taking security into your own hands. You can program your web services so that all of their methods require an access token, which can be obtained from the web service after sending in the client’s username and password. The client credentials can be sent to the server through SSL, which eliminates the risk of sending clear-text passwords across the wire. Through this SSL channel, the server returns an access token to the caller, who can use it to invoke all other web service methods. Of course, all of the other web methods that you publish have to have one parameter as the token. A simple pseudocode example of a bank account web service can be as follows:
Web Service Bank Account
Web Methods:
Login(user id, password) returns access token or nothing
Deposit(access token, account number, amount, balance) returns T/F
Withdraw(access token, account number, amount, balance) returns T/F
The only method that should be on SSL is the Login method. Once the token is obtained, it can be used for other web methods. Of course, you should be able to make sure that subsequent calls using this token are coming from the same IP as the
Login( ) call. You can also incorporate an expiration timestamp on this access token to ensure that the token only exists in a certain time frame until a renewal of the access token is needed.
The Microsoft .NET Cryptographic Services can be very useful if you choose this route. DES, RC2, TripleDES, and RSA encryption/decryption algorithms are supported along with hashing methods such as SHA and MD5. These implementations in the .NET library enable developers to avoid low-level grunt work and focus on the application logic.

CHAPTER 5
DATABASE DEVELOPMENT USING .NET

5.1 Overview
.NET facilitates the development and support for application development that interact with various kinds of databases. It has built-in libraries that helps interact with various types of databases and XML data sources. It has a multitude of approaches that can be undertaken to interact with the database, ADO.NET being the core and the most optimal one. Other techniques lie LINQ-to-SQL and Entity Framework exist, but at their underlying core, they too rely on ADO.NET.
5.2 Database concepts and SQL
5.2.1 Database
A database is an organized collection of data. It is a collection of data that is organized so that its contents can easily be accessed, managed and updated. A database in RDBMS (Relational Database Management System) is made up of a collection of tables that stores a specific set of structured data. A table contains a collection of rows, also referred to as records or tuples, and columns, also referred to as attributes. Each column in the table is designed to store a certain type of information, for example, dates, names, dollar amounts, and numbers.
RDBMS is a database engine/system that lets you create, update, and administer a relational database based on the relational model.
5.2.2 SQL
Structured Query Language is a special-purpose programming language designed for managing data held in an RDBMS. It is the set of instructions used to interact with a relational database and is the only language most databases understand. The Structured Query Language (SQL) comprises one of the fundamental building blocks of modern database architecture. SQL defines the methods used to create and manipulate relational databases on all major platforms.
SQL Commands can broadly be divided into two major categories:
Data Definition Language (DDL): Deals with defining structure of database and its objects. Contains the commands used to create, modify and destroy databases and database objects. These commands are primarily used by database administrators during the setup and removal phases of a database project. E.g., CREATE, ALTER, DROP, TRUNCATE are DDL commands that physically modify the structure and/or objects in the database schema.
–Creates a database named ‘Apex’
CREATE DATABASE [Apex]

–Creates a table ‘Student’ inside ‘Apex’
CREATE TABLE [Apex].[dbo].[Student]
(
Id INT PRIMARY KEY
IDENTITY(1, 1),
Name VARCHAR(50) NOT NULL,
RollNumber VARCHAR(2) NOT NULL,
Gender BIT NOT NULL
)

–Changes the data type of ‘RollNumber’ from Varchar to int in the table schema
ALTER TABLE [Apex].[dbo].[Student] ALTER COLUMN [RollNumber] INT NOT NULL

–Removes the data by deallocating the data pages, and resets the identity/autoincrement of the table
TRUNCATE TABLE [Apex].[dbo].[Student]

–Physically removes the table ‘Student’ from ‘Apex’
DROP TABLE [Apex].[dbo].[Student]

–Physically removes the database ‘Apex’
DROP DATABASE [Apex]

Data Manipulation Language (DML): Deals with retrieval, insertion and modification the data contained within the database without modifying its structure. These commands are used by database developers and database users during the routine operation of the database. E.g., SELECT, INSERT, UPDATE, DELETE are DML commands that only manipulate the data in the database and not the schema.
–Inserts new data/tuples in the table ‘Student’
INSERT [Apex].[dbo].[Student]
( [Name], [RollNumber], [Gender] )
VALUES ( ‘Ram’, 1, 1 ),
( ‘Sita’, 2, 0 ),
( ‘Harry’, 3, 0 )

–Retrieves filtered data from the table ‘Student’
SELECT [S].[Id],
[S].[Name],
[S].[RollNumber],
[S].[Gender]
FROM [dbo].[Student] AS [S]
WHERE [S].[Gender] = 1
ORDER BY [S].[RollNumber] ASC

–Modifies the data in the table ‘Student’
UPDATE [Apex].[dbo].[Student]
SET [Student].[Name] = ‘Hari’,
[Student].[Gender] = 1
WHERE [Student].[Name] = ‘hARRY’

–Removes data from the table ‘Student’
DELETE FROM [Apex].[dbo].[Student]
WHERE [Student].[RollNumber] > 2
AND [Student].[Gender] = 1
5.3 ADO.NET and Data
5.3.1 ADO.NET
ADO.NET is a set of classes that expose data access services for .NET Framework programmers. ADO.NET provides a rich set of components for creating distributed, data-sharing applications. It is an integral part of the .NET Framework (part of the base class library that is shipped with the Microsoft .NET Framework), providing access to relational, XML, and application data. It is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file. ADO.NET supports various types of SQL databases like Oracle Database, MySQL, PostgreSQL, SQLite, Sybase ASE, Microsoft SQL Server, Microsoft Access, Borland Interbase, and IBM DB2, just to name a few.
ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be considered an entirely new product.
ADO.NET is designed as a unified back-end data store for all Microsoft .NET programming models, like ASP.NET, Windows Forms, Web Services, among others. Developers use ADO.NET to manage data in the .NET Framework either directly or indirectly.

ADO.NET in .NET Framework
ADO.NET has 3 major components:
1. Data Source: Any persistent storage of data, can be either a database or an XML file.
2. Data Provider: A set of class library that abstracts out the technical details and eases communication and data manipulation when working with any type of data source.
3. DataSet: An in-memory representations of data. It can contain multiple Datatable objects, which contain columns and rows, just like normal database tables.
Data Source:
The data source is the physical database, either local or remote, or an XML file. In traditional database programming, the developer typically works with the data source directly, often requiring complex, proprietary interfaces. With ADO.NET, the developer works with a set of components (libraries) to access the data source, to expose data, and to pass commands.
Data Providers:
Data Provider components connect to the physical databases or XML files, hiding implementation details. Providers can connect to one or more data sources, pass commands, and expose data to the DataSet. The .NET Framework includes data providers for many types of databases, like for MS SQL, OLE DB, and Oracle. These connect to a number of industry standard databases, providing a consistent programming environment.
Components of data provider (ADO.NET Objects) include:
• Connection: Establishes a connection to a specific data source
• Command: Executes a command against a data source
• DataReader: Reads a stream of data from a data source
• DataAdapter: Populates a data set and resolves updates with the data source
Although ADO.NET provides a relatively common way to interact with various data sources, different data sources expose different protocols and we need a way to communicate with the right data source using the right protocol. Thus, there isn’t a single set of classes that allow you to accomplish this universally. So, there are different sets of libraries for each way you can talk to a data source. These libraries are usually named for the protocol or data source type they allow you to interact with. Some well-known data providers, the API prefix they use, and the type of data source they allow you to interact with are as follows:
Provider Name API prefix Data Source Description
OLEDB Data Provider OleDb Data Sources that expose an OLEDB (Object Linking and Embedding, Database) interface, i.e. Access or Excel.
Oracle Data Provider Oracle For Oracle Databases.
SQL Data Provider Sql For interacting with Microsoft SQL Server.
Borland Data Provider Bdp For generic access to many databases such as Interbase, SQL Server, IBM DB2, and Oracle.
For example, if we were using the SQL Data Provider to connect to a SQL Server database, we would use a connection object named SqlConnection, and if we are using OLEDB Data Provider, connection object would be named OleDbConnection.
DataSet:
The DataSet object represents in-memory tables and relations from one or more data sources. The DataSet provides a temporary work area or virtual scratch pad for manipulating data. ADO.NET applications manipulate tables in memory, not within the physical database. The DataSet provides additional flexibility over direct connections to physical databases. Much like a typical database in many database systems, the DataSet can contain multiple DataTables, which are representations of tables or views from any number of data sources. The DataSet works in an asynchronous, non-connected mode, passing update commands through the Provider to the data source at a later time.
5.3.2 ADO.NET Objects
(Components of Data Provider)
ADO.NET includes many objects you can use to work with data. Some of the primary objects with reference to SQL Server are as follows:
SqlConnection:
To interact with a database, you must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the database. It manages all of the low level logic associated with the specific database protocols.
The purpose of creating a SqlConnection object is so you can enable other ADO.NET code to work with a database. Other ADO.NET objects, such as a SqlCommand and a SqlDataAdapter take a connection object as a parameter. The sequence of operations that occurs in the lifetime of a SqlConnection is as follows:
i. Instantiate the SqlConnection.
ii. Open the connection.
iii. Pass the connection to other ADO.NET objects.
iv. Perform database operations with the other ADO.NET objects.
v. Close the connection.
The SqlConnection object instantiated above uses a constructor with a single argument of type string, containing certain key/value pairs for specifying how to make a database connection. This argument is called a connection string.
Connection String Parameter Description
Data Source Identifies the server. Could be local machine, machine domain name, or IP Address.
Initial Catalog Database name.
Integrated Security Set to SSPI to make connection with user’s Windows login (if you are not providing user id and password).
User ID Name of user configured in SQL Server.
Password Password matching SQL Server User ID.
Example:
SqlConnection conn = new SqlConnection(“Data Source=DatabaseServer; Initial Catalog=Northwind; User ID=YourUserID; Password=YourPassword”);
Code:
using System;
using System.Data;
using System.Data.SqlClient;

///
/// Demonstrates how to work with SqlConnection objects
///

class SqlConnectionDemo
{
static void Main()
{
// 1. Instantiate the connection
SqlConnection conn
= new SqlConnection(“Data Source=ABHISHEK;Initial Catalog=Apex;Integrated Security=SSPI”);

SqlDataReader rdr = null;
try
{
// 2. Open the connection
conn.Open();

// 3. Pass the connection to a command object
SqlCommand cmd
= new SqlCommand(“select * from Student order by Id”, conn);

// 4. Use the connection
// Get query results
rdr = cmd.ExecuteReader();

// print the Student names of each record
while (rdr.Read()) Console.WriteLine(rdr["Name"]);
Console.ReadKey();
}
finally
{
// close the reader
if (rdr != null) rdr.Close();

// 5. Close the connection
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
SqlCommand:
A SqlCommand object allows you to specify what type of interaction you want to perform with a database. For example, you can do select, insert, modify, and delete commands on rows of data in a database table.
Example:
SqlCommand cmd = new SqlCommand(“select * from Student order by Id”, conn);
Using SqlCommand object to perform interactions:
Querying Data: To read data with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object. A SqlDataReader is a type that is good for reading data in the most efficient manner possible. You cannot use it for writing data. SqlDataReaders are often described as fast-forward streams of data. If the amount of data you need to read is larger than what you would prefer to hold in memory, then the streaming behavior of the SqlDataReader is a good choice since the data result isn’t kept in application’s memory. Also, call the Close method of the SqlDataReader to ensure there are not any resource leaks. The Read method in SqlDataReader returns true as long as there are more rows remaining to be read.
SqlCommand cmd = new SqlCommand(“select * from Student order by Id”, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) Console.WriteLine(reader["Name"]);
Inserting/Updating/Deleting Data: To insert/update/delete data into/from a database, use the ExecuteNonQuery method of the SqlCommand object.
SqlCommand cmd = new SqlCommand(“DELETE FROM Student WHERE Name = ‘Shyam’”, conn);
cmd.ExecuteNonQuery();
Getting Single value: Sometimes all you need from a database is a single value, which could be a count, sum, average, or other aggregated value. Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this. The best choice is to let the database perform the work and return just the single value you need. To do this, use the ExecuteScalar method that returns a single value of “object” type from data source.
SqlCommand cmd = new SqlCommand(“select count(*) from Student”, conn);
int studentCount = (int)cmd.ExecuteScalar();
Code:
using System;
using System.Data.SqlClient;

// Demonstrates how to work with SqlCommand objects
class SqlCommandDemo
{
static void Main()
{
string query = null;
//Create a connection object
SqlConnection conn = new SqlConnection(
“Data Source=ABHISHEK;Initial Catalog=Apex;Integrated Security=SSPI”);
//Create a command object
SqlCommand cmd = new SqlCommand(query, conn);
//Data reader to read stream of SQL data returned via command object
SqlDataReader rdr = null;
try
{
//Open the connection
conn.Open();

#region Query Data
//Assigns the command query to be executed to the command object
cmd.CommandText = “SELECT NAME FROM Student ORDER BY NAME”;
//Executes the command against the data source and assigns the data stream to reader
rdr = cmd.ExecuteReader();
while (rdr.Read()) //Reads a row and advances pointer to next row
Console.WriteLine(“The name is ” + rdr[0]);
// close the reader
rdr.Close();
#endregion

#region Insert Data
cmd.CommandText = “INSERT INTO Student VALUES (‘Laxman’, 4, 0)”;
//Executes the command against the data source and returns the number of rows affected (number of rows inserted, in this case)
cmd.ExecuteNonQuery();
#endregion

#region Update Data
cmd.CommandText = “UPDATE Student SET GENDER = 1 WHERE NAME = ‘Laxman’”;
cmd.ExecuteNonQuery();
#endregion

#region Delete Data
cmd.CommandText = “DELETE FROM Student WHERE NAME = ‘Laxman’”;
cmd.ExecuteNonQuery();
#endregion
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the connection
conn.Close();
Console.ReadKey();
}
}
}
So, a SqlCommand object allows you to query and send commands to a database. It has methods that are specialized for different types of commands.
ExecuteReader:
Returns a SqlDataReader object for displaying the results of a select query.
ExecuteNonQuery:
For insert, update, and delete SQL commands.
ExecuteScalar:
If you only need a single aggregate value from a query.
5.3.3 Working with Disconnected Data
The DataSet and SqlDataAdapter
A DataSet is an in-memory data store that can hold numerous tables. DataSets only hold data and do not interact with a data source. It is the SqlDataAdapter that manages connections with the data source and gives us disconnected behavior. The SqlDataAdapter opens a connection only when required and closes it as soon as it has performed its task. For example, the SqlDataAdapter performs the following tasks when filling a DataSet with data:
1. Open connection
2. Fill data into DataSet
3. Close connection
And performs the following actions when updating data source with DataSet changes:
1. Open connection
2. Update changes from DataSet to data source
3. Close connection
In between the Fill and Update operations, data source connections are closed and you are free to read and write data with the DataSet as you need. These are the mechanics of working with disconnected data. Because the applications holds on to connections only when necessary (only during adapter’s “Fill” and “Update” method calls), the application becomes more scalable.
Creating a DataSet Object:
DataSet dsStudents = new DataSet();

Instantiate an empty DataSet. You need a SqlDataAdapter to load it.
Creating a SqlDataAdapter Object:
The SqlDataAdapter holds the SQL commands and connection object for reading and writing data. You initialize it with a SQL select statement and connection object:
SqlConnection conn = new SqlConnection(“Server=ABHISHEK;DataBase=Apex;Integrated Security=SSPI”);
SqlDataAdapter daStudents = new SqlDataAdapter(“select * from Student”, conn);
The code above creates a new SqlDataAdapter named daStudents. The SQL select statement specifies what data will be read into a DataSet. The connection object, conn, should have already been instantiated, but not opened. It is the SqlDataAdapter’s responsibility to open and close the connection during Fill and Update method calls.
The SqlDataAdapter contains all of the commands necessary to interact with the data source. The code showed how to specify the select statement, but didn’t show the insert, update, and delete statements. These are added to the SqlDataAdapter using SqlCommandBuilder.
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daStudents);
After this statement, the SqlDataAdapter can call “Update” method to update the data source with inserted/updated/deleted data in the in-memory DataSet.
Filling the DataSet: Once you have a DataSet and SqlDataAdapter instances, you need to fill the DataSet. Here’s how to do it, by using the Fill method of the SqlDataAdapter:
daStudents.Fill(dsStudents, tableName);
The Fill method, in the code above, takes two parameters: a DataSet and a table name. The DataSet must be instantiated before trying to fill it with data. The second parameter is the name of the table that will be created in the DataSet. You can name the table anything you want. Its purpose is so you can identify the table with a meaningful name later on. Typically, table names are the same as the database table.
The Fill method has an overload that accepts one parameter for the DataSet only. In that case, the table created has a default name of “table1″ for the first table. The number will be incremented (table2, table3… tableN) for each table added to the DataSet where the table name was not specified in the Fill method.
Updating Changes: After modifications are made to the data, you’ll want to write the changes back to the database. The Update method of the SqlDataAdapter is used to push modifications back to the database.
daStudents.Update(dsStudents, tableName);
The Update method is called on the SqlDataAdapter instance that originally filled the dsStudents DataSet. The second parameter to the Update method specifies which table, in the DataSet, to update. The table contains a list of records that have been modified and the Insert, Update, and Delete properties of the SqlDataAdapter contain the SQL statements used to make database modifications.
Code:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter daStudents;
private DataSet dsStudents;
private string tableName;

private void btnFill_Click(object sender, EventArgs e)
{
tableName = “Student”; //Name of the table to operate

// 1. instantiate the connection
conn = new SqlConnection(“Server=ABHISHEK;DataBase=Apex;Integrated Security=SSPI”);

// 2. instantiate a new DataSet
dsStudents = new DataSet();

// 3. instantiate SqlDataAdapter with select command and connection
daStudents = new SqlDataAdapter(“select * from ” + tableName, conn);

// 4. fill in insert, update, and delete commands, without associating SqlDataAdapter to SqlCommandBuilder data modification isn’t allowed
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daStudents);

// 5. opens connection, fill the dataset and closes connection
daStudents.Fill(dsStudents, tableName);

// 6. Bind with the UI controls for display
dataGridView1.DataSource = dsStudents;
dataGridView1.DataMember = tableName;
}

private void btnUpdate_Click(object sender, EventArgs e)
{
// opens connection, updates the data source and closes connection
daStudents.Update(dsStudents, tableName);
}
}
}

So, in summary, a DataSet holds multiple tables and can be kept in memory and reused. The SqlDataAdapter enables you to fill a DataSet and Update changes back to the database. You don’t have to worry about opening and closing the SqlConnection because the SqlDataAdapter does it automatically. A SqlCommandBuilder populates insert, update, and delete commands based on the SqlDataAdapter’s select statement. Use the Fill method of the SqlDataAdapter to fill a DataSet with data. Call the SqlDataAdapter’s Update method to push changes back to a database.

CHAPTER 6
.NET COMMON LANGUAGE RUNTIME

6.1 Introduction
The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.
The Common Language Runtime (CLR) is a core component of Microsoft’s .NET initiative. It is Microsoft’s implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. In the CLR, code is expressed in a form of bytecode called the Common Intermediate Language (CIL, also known as MSIL—Microsoft Intermediate Language).
Developers using the CLR, write code in a language such as C# or VB.NET. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR’s just-in-time compiler converts the CIL code into code native to the operating system.
Common Language Runtime is the backbone of the .NET framework. CLR takes care of a number of low-level executions such as application hosting, thread handling, memory management, security checks and application performance. Its primary role is to locate, load, and manage the .NET types (class, array, object etc.). The beauty of CLR is that all .NET-supported languages can be executed under this single defined runtime layer.
Compilers and tools expose the common language runtime’s functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.
The runtime provides the following benefits:
• Performance improvements.
• The ability to easily use components developed in other languages.
• Extensible types provided by a class library.
• Language features such as inheritance, interfaces, and overloading for object-oriented programming.
• Support for explicit free threading that allows creation of multithreaded, scalable applications.
• Support for structured exception handling.
• Support for custom attributes.
• Garbage collection.
• Use of delegates instead of function pointers for increased type safety and security.
6.2 Assemblies and JIT
The CLR first locates the referenced assembly, and then it loads it into memory, compiles the associated IL code into platform specific instructions, performs security related checks, and finally executes the code. The .NET compilation process completes in two stages: first, the C# code you write is compiled into an Intermediate Code (MSIL). All .NET languages are compiled into virtual identical IL code. The compiled file with IL code is referred to as Assembly. An assembly contains CIL (Common Intermediate Code) code, which is conceptually similar to java byte code. In addition to CIL instruction, assemblies also contain metadata that describes in vivid detail the characteristics of every type in the binary. The .NET metadata is always present within an assembly and is automatically generated by .NET aware language compiler. When a *.exe or *.dll is created using .NET aware compiler, it is referred to as an assembly.
The second level of compilation happens just before the application is executed. At this point, the IL code is compiled into low-level native machine code. This stage is known-as Just-In-Time (JIT) Compilation. Finally .NET CLR produces the executable or library files and executes the code.
6.3 Garbage Collection
Memory management is the main concern for any application whether application is window based or web based. In .Net, CLR has garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collector frees the memory for objects that are no longer referenced and keeps the memory for future allocations. The .NET Framework’s garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector’s optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.
In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:
• Enables you to develop your application without having to free memory.
• Allocates objects on the managed heap efficiently.
• Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.
• Provides memory safety by making sure that an object cannot use the content of another object.
6.4 Security
Security is an essential part of any application and should be taken into consideration from the first stage of the development process. The .NET framework secures the resources by implementing various full-fledged security mechanisms such authentication, authorization, code access, role based security, sandboxing and certificate security. Furthermore, the .NET framework on its own provides you with a set of base classes for implementing confidentiality and integrity through encryption and digital signature.
The .NET allows you to manage security, including how .NET protects you from malicious code, how to administer security policies and how to access the security subsystems programmatically. The .NET framework security mainly revolves around code access security and role base security.
Code Access Security (CAS) reduces the risks associated with running code of dubious origin even if code is running under super user account. It is possible to use CAS to indicate that code should still not be permitted to perform certain type of operations. Whereas Role-Based security is based on the identity of the account under which the process is running, and CLR is able to inspect code before running in order to determine required security permissions.
6.5 Events and Delegates
An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises (triggers) the event is called the event sender. The object that captures the event and responds to it is called the event receiver.
In event communication, the event sender class does not know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer.
A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback.
6.6 Reflection
It is possible to access the metadata (vivid details about types) from an assembly programmatically using the Reflection mechanism. This method is commonly used to obtain the details of attributes, although you can also use reflection, among other purpose, such as instantiating classes or calling methods.
In this way, you could select classes to instantiate methods to call at runtime, rather than compile time, based on user inputs (Dynamic Binding). Reflection allows us to perform numerous tasks such as enumerating members of type, finding out information of types, creating and compiling new assemblies, and inspecting the custom attributes applied to type.
6.7 Remoting
Establishing communication between objects that run in different processes, whether on the same computer or on computers thousands of miles apart, is a common development goal, especially when building widely-distributed applications. Traditionally, this has required in-depth knowledge not only of the objects on either end of the communication stream, but also of a host of lower-level protocols, application programming interfaces, and configuration tools or files. In short, it was a complex task demanding concentration and experience.
The .NET Framework makes several communication methods available to accomplish this task quickly and easily, even with minimal knowledge of protocols and encodings. As a result, whether you need to develop a Web application quickly or spend more time building a critical enterprise-wide application that involves many computers or operating systems and uses multiple protocols and serialization optimizations, the .NET Framework supports your scenario. Communicating across processes is still a complex task, but much of it is now handled by the .NET Framework.
.NET remoting enables client applications to use objects in other processes on the same computer or on any other computer available on its network. You can also use .NET remoting to communicate with other application domains in the same process. .NET remoting provides an abstract approach to interprocess communication that separates the remotable object from a specific server and client process and from a specific mechanism of communication. As a result, it is flexible and easily customizable. You can replace one communication protocol with another communication protocol, or one serialization format with another without recompiling the client or the server. In addition, the remoting system assumes no particular application model. You can communicate from a Web application, a console application, a Windows Service – from almost anything you want to use. Remoting servers can also be any type of executable application. Any application can host remoting objects and thus provide its services to any client on its computer or network.
6.8 Common Language Specification
A Common Language Specification (CLS) is a document that says how computer programs can be turned into bytecode. When several languages use the same bytecode, different parts of a program can be written in different languages. Microsoft uses a Common Language Specification for their .NET Framework. To fully interact with other objects regardless of the language they were used in, objects must expose to callers only those features that are common to all the languages they must exchange information with. It was always a dream of Microsoft to unite all different languages into one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines for languages to follow so that it can communicate with other .NET languages in a seamless manner.

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the Common Type System; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these help you determine whether your managed code conforms to the CLS and to what extent a given tool supports the development of managed code that uses CLS features. The CLS was designed to be large enough to include the language constructs that are commonly needed by developers, yet small enough that most languages are able to support it.
If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS. Components that adhere to the CLS rules and use only the features included in the CLS are said to be CLS-compliant components.
The Common Language Specification works with the CTS to ensure language interoperability. Each language express the same programming constructs in specific terms.
6.9 COM Interop
Component Object Model (COM) is a binary-interface standard for software components introduced by Microsoft in 1993. It is used to enable inter-process communication and dynamic object creation in a large range of programming languages. It is a language-neutral way of implementing objects that can be used in environments different from the one in which they were created, even across machine boundaries.
COM Interop is a technology included in the .NET Framework Common Language Runtime (CLR) that enables Component Object Model (COM) objects to interact with .NET objects, and vice versa. COM Interop aims to provide access to the existing COM components without requiring that the original component be modified. It tries to make the .NET types equivalent to the COM types. In addition, COM Interop allows COM developers to access managed objects as easily as they access other COM objects. COM interop automatically provides conversion between COM types and.NET types.

6.10 Managed Code
Code developed and running under the control of the CLR is often termed managed code.
Microsoft shared the idea of IL code from Java byte code in which IL code can be quickly translated into native machine code. In other words, by compiling to IL code, you obtain platform independence for .NET in much same way as compiling java code.
IL code is compiled (JIT compilation), whereas java byte code was interpreted. One of the disadvantages of java was that, on execution, the process of translating from java byte code to native executable resulted in loss of performance. The JIT compiler simply compiles each portion of code so we can expect that execution of managed IL code will be as fast as executing native code.
IL is the backbone for every managed application. In a sense, the language is only recognized by .NET framework is IL. This means same program written in C# or VB.NET will compile to produce same IL code. You can compile to IL from one language, and this compiled code should be interoperable with another IL compiled languages, thus facilitating interoperability.
6.10 Common Type System
The CTS specification describes all possible data types and programming constructs supported by the runtime, specifies how these entities can interact with each other, and details how they are represented in the .NET metadata format. Types are the mechanism by which code written in one language can talk to code written in different programming language. CTS defines the predefined data types that are available in IL code, so that all languages that targets the .NET CLR will produce compile code that is based on these types.
Suppose that one of the methods is defined in VB.net class that returns an Integer, and if we call this method in C# defined class by implementing the inheritance but C# does not have any data type of that name. So this problem is circumventing by CTS. In VB.net Integer is actually a 32-bit signed integer that maps exactly to the IL type code, known as Int32. At source level, C# refers to Int32 with the keyword int. so the compiler will simply treat the VB.net methods as if it returned an int.
6.12 Memory Allocation in Managed Heap
The managed heap is a series of allocated memory segments (approx. 16Mb in size each) to store and manage objects. The memory for newly created object is allocated at the next available location on the managed heap. If there is available free memory, the garbage collector doesn’t search the dead objects for memory reclaim and memory allocations has been done very fast. If the memory is insufficient to create the object, the garbage collector search the dead objects for memory reclaim for the newly object.

Managed Heap and memory allocation by CLR
An object is created using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, NextObjPtr points to the object in the heap and object’s constructor is called and the new operator returns the address of the object.
Generations in Managed Heap
The managed heap is organized into three generations so that it can handle short lived and long lived objects efficiently. Garbage collector first reclaim the short lived objects that occupy a small part of the heap.
Generation 0: This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1.
Generation 1: This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generation 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.
Generation 2: This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently.

CHAPTER 7
.NET FRAMEWORK CLASS LIBRARY

7.1 Overview
The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, components, and controls are built. The namespaces and namespace categories in the class library are listed in the following table and documented in detail in this reference. The namespaces and categories are listed by usage, with the most frequently used namespaces appearing first.
Base Class Library Namespace Brief Description
System Contains the fundamentals for programming such as the data types, console, match and arrays, etc.
System.CodeDom Supports the creation of code at runtime and the ability to run it.
System.Collections Contains Lists, stacks, hashtables and dictionaries
System.ComponentModel Provides licensing, controls and type conversion capabilities
System.Configuration Used for reading and writing program configuration data
System.Data Is the namespace for ADO.NET
System.Deployment Upgrading capabilities via ClickOnce
System.Diagnostics Provides tracing, logging, performance counters, etc. functionality
System.DirectoryServices Is the namespace used to access the Active Directory
System.Drawing Contains the GDI+ functionality for graphics support
System.EnterpriseServices Used when working with COM+ from .NET
System.Globalization Supports the localization of custom programs
System.IO Provides connection to file system and the reading and writing to data streams such as files
System.Linq Interface to LINQ providers and the execution of LINQ queries
System.Linq.Expressions Namespace which contains delegates and lambda expressions
System.Management Provides access to system information such as CPU utilization, storage space, etc.
System.Media Contains methods to play sounds
System.Messaging Used when message queues are required within an application, superseded by WCF
System.Net Provides access to network protocols such as SSL, HTTP, SMTP and FTP
System.Reflection Ability to read, create and invoke class information.
System.Resources Used when localizing a program in relation to language support on web or form controls
System.Runtime Contains functionality which allows the management of runtime behavior.
System.Security Provides hashing and the ability to create custom security systems using policies and permissions.
System.ServiceProcess Used when a windows service is required
System.Text Provides the StringBuilder class, plus regular expression capabilities
System.Threading Contains methods to manage the creation, synchronization and pooling of program threads
System.Timers Provides the ability to raise events or take an action within a given timer period.
System.Transactions Contains methods for the management of transactions
System.Web Namespace for ASP.NET capabilities such as Web Services and browser communication.
System.Windows.Forms Namespace containing the interface into the Windows API for the creation of Windows Forms programs.
System.Xml Provides the methods for reading, writing, searching and changing XML documents and entities.

7.2 GDI+
Windows GDI+ is the portion of the Windows XP operating system or Windows Server 2003 operating system that provides two-dimensional vector graphics, imaging, and typography. GDI+ improves on Windows Graphics Device Interface (GDI) (the graphics device interface included with earlier versions of Windows) by adding new features and by optimizing existing features.
Windows GDI+ is a class-based API that enables applications to use graphics and formatted text on both the video display and the printer. Applications based on the Microsoft Win32 API do not access graphics hardware directly. Instead, GDI+ interacts with device drivers on behalf of applications. It allows programmers to write device-independent applications. The services of GDI+ are exposed through a set of C++ classes.
A graphics device interface, such as GDI+, allows application programmers to display information on a screen or printer without having to be concerned about the details of a particular display device. The application programmer makes calls to methods provided by GDI+ classes and those methods in turn make the appropriate calls to specific device drivers. GDI+ insulates the application from the graphics hardware, and it is this insulation that allows developers to create device-independent applications.
7.3 Exceptions
Exception is an error caused by circumstances outside the program’s control. When an error occurs within a method, the method creates an object and hands it off to the run time system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “something” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional events requiring special processing – often changing the normal flow of program execution. In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are not severe and program execution can be continued, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.
7.5 Threading
A thread of execution is the smallest sequence of programmed instructions that can be managed independently by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources. In particular, the threads of a process share the latter’s instructions (its code) and its context (the values that its variables reference at any given moment).

A process with two threads of execution on a single processor

Operating systems use processes to separate the different applications that they are executing. Threads are the basic unit to which an operating system allocates processor time, and more than one thread can be executing code inside that process. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled.
Threads are basically light weight processes responsible for multitasking within a single application. The base class used for threading is System.Threading. Threads are managed under the Common Language Runtime, programmers don’t have to manage any threads explicitly. Threads are implemented when you have situation in which you want to perform more than one task at a time.

Example:
using System;
using System.Threading;

namespace Threading
{
class Program
{
static void Main()
{
Thread t = new Thread(ThreadFxn);
t.Priority = ThreadPriority.AboveNormal;
t.Start();

for (var i = 0; i < 100; ++i)
Console.WriteLine(“Main thread Running”);

Console.ReadKey();
}

static void ThreadFxn()
{
for (var i = 0; i < 100; ++i)
Console.WriteLine(“Running other Thread”);
}
}
}

Output:

CHAPTER 8
CASE STUDIES (MINOR PROJECT) AND LAB

8.1 Overview
Students are required to perform case studies (minor project) using .NET Framework. Students can choose from one of the following technologies for minor project:
• Desktop Application,
• Web Application using ASP.NET,
• Web Application using ASP.NET MVC, or
• Mobile Application
8.2 Guidelines for Case Studies
The complete tasks required are:
• Prepare the proposal
• Perform analysis and design (system analysis, database design, system design)
• Build the application (development / implementation)
• Test and debug the application
• Deploy the application to appropriate environment
• Prepare the final report
• Prepare for presentation of the project

8.3 Guidelines for Lab
Language to be used
Labs will be conducted in C#. The first few labs will be introductory to Visual Studio and C#. These labs will enable the students to migrate from C++ to C#
Lab Procedure:
The lab sheet will be provided to the students one week before the lab. The lab sheet will indicate relevant chapters in the book. Students are required to study the related chapters from the book and prepare a pre-report before coming to the lab. The lab instructor will make a presentation explaining the concepts, through the use of one or several typical program. In the lab, students will modify the program as instructed, or write an entirely new program similar to the one presented.

Buffer Labs:
In addition to accommodate for labs that could not be conducted, buffer labs can be used to repeat past labs, or complete labs that were not completed in the assigned session. However, at the end of the buffer lab, the student should have submitted all lab reports until that point.

Lab 1 – Introducing the Visual Studio .NET IDE
Lab 2 – Introducing the C# language: Structured Programming and exception handling
Lab 3 – Introducing the C# Language: Object Oriented Programming
Lab 4 – Buffer
Lab 5 – Windows Forms: Simple Controls and Events
Lab 6 – Windows Forms: Tree views, List views
Lab 7 – Windows Forms: GridView and DataTable
Lab 8 – Buffer
Lab 9 – IO: Streams, sequential files and random access files
Lab 10 – XML: The Basics
Lab 11 – Databases and ADO.NET
Lab 12 – Buffer
Lab 13 – Web Programming: HTML, JavaScript
Lab 14 – ASP.NET MVC
Lab 15 – File I/O
Lab 16 – Buffer

CODE SAMPLES
Console Applications
Note:
• The programs are self-sufficient and can be copied and run directly within Visual Studio IDE (except for the WinForm examples where UI and controls should be created first).
• The programs are heavily commented for clarity propose. Remove the comments once copied inside VS IDE to reduce the lines of code in VS, if that helps you to understand the workflow clearly.

1. Write a console application to display the string “Welcome!”
Code:
using System;

namespace ConsoleApplication1
{
//A simple class.
class Program
{
//Property: Enforces encapsulation. Creates (if not defined by user) and hides a private member variable and serves as its accessor. Here, a private static string variable _myName is created, and getters (the “get” property accessor enables user to read/obtain the value of the variable) and setters (the “set” property accessor enables user to assign/update the value of the variable).
private static string MyName { get; set; }

//Constructor: Method that gets called when an instance of the class is made. Mainly used for pre-processing, or to perform initial setup operations. Doesn’t return any value.
static Program()
{
//Initialize class variables here, and do other initial configurations, like database’s connection string initialization.
MyName = “Welcome!”;
}

//A simple method. The Main() method is entry point for console application.
private static void Main()
{
/*Console class provides standard I/O stream for console application.
WriteLine() method writes to the standard output stream.*/
Console.WriteLine(MyName);

//Program waits until user presses any key from keyboard.
Console.ReadKey();
//Program terminates and returns to OS after user hits a key.
}
}
}

//Output:
//Welcome!

2. Write a program that calculates simple interest. Use try-catch-finally block.
Code:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
//try block returns control to catch block in case any unexpected behavior/anomaly (exception) occurs.
try
{
//Interest = Principle * Rate * Time
double interest, principle, rate, time;

Console.Write(“Enter principle amount:”);
principle = Convert.ToDouble(Console.ReadLine()); //Reads a line as string from user and tries to convert it to double. Throws invalid format exception if non-numeric input is provided.

Console.Write(“Enter time in years:”);
time = Convert.ToDouble(Console.ReadLine());

var rand = new Random(); //Creates an object/instance of the Random class, for random number generation.
rate = rand.Next(1, 7); //Generates a random integer number between 1 and 6 (but not 7 itself).
rate = rate / 100; //Divides the new integer value by 100, to convert it into percent.
Console.WriteLine(“The rate is:” + rate);

Console.WriteLine(); //Prints a blank line.
interest = principle * rate * time;
Console.WriteLine(“The interest is ” + interest);
}
catch (Exception ex) //If any unexpected run-time error occurs, control returns to catch block. “Exception” is the base class of all exception classes (but user-defined exception should derive from “ApplicationException” class).
{
Console.WriteLine(ex.Message);
}
finally //This block is always processed, whether or not exception occured. Used mainly to release resources.
{
Console.Write(“Press any key to exit…”);
Console.ReadKey();
}
}
}
}

//Output 1: Normal program flow
//Enter principle amount:100
//Enter time in years:2
//The rate is:0.05

//The interest is 10
//Press any key to exit…

//Output 2: When input was not correct and couldn’t be converted to double
//Enter principle amount:some text
//Input string was not in a correct format.
//Press any key to exit…

3. Write a program to calculate factorial (n!) of any integral value entered by user.
Code:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
try
{
Console.Write(“Enter a number:”);
//Takes string from user.
string userInput = Console.ReadLine();
//Tries to cast it to int. Throws invalid format exception if unsuccessful.
var number = Convert.ToInt32(userInput);
var fact = Factorial(number); //Calls Factorial() method with the entered number as argument.
Console.WriteLine(“The factorial is ” + fact);
}
catch (Exception e)
{
Console.WriteLine(e.Message); //Prints the exception.
}
Console.ReadKey(); //Waits for user key press before proceeding.
}

//Note: Since Main() must always be static, Factorial() is also made static because any static method cannot call non-static method or use non-static field.
private static int Factorial(int n)
{
if (n <= 1) return n;
return n * Factorial(n – 1);

//Inside Factorial:
//If user enters 3, Factorial(3) is called via Main().
//Inside Factorial(), 3 is found to be greater than 1 (3 <= 1 is false), so the return statement breaks as “return 3 * Factorial(3 – 1)” or “3 * Factorial(2)”.
//Factorial() calls itself again, this time passing 2 (Any method calling itself directly or indirectly is called a recursive method).
//Inside Factorial(), 2 is found to be greater than 1 (2 <= 1 is false), so the return statement breaks as “return 2 * Factorial(1)”.
//Factorial() calls itself again, this time passing 1.
//Inside Factorial(), 1 is found to be equal to 1 (1 <= 1 is true), so “return n” breaks as “return 1″ (This is the feasible/base condition).
//Summary:
//Factorial(3) = 3 * Factorial(2)
//Factorial(2) = 2 * Factorial(1)
//Factorial(1) = 1
//Replace the “Factorial(n)” with respective values to get numeric output.
//Factorial(3) = 3 * Factorial(2) = 3 * 2 * Factorial(1) = 3 * 2 * 1.
}
}
}

//Output:
//Enter a number:5
//The factorial is 120

4. Write a .NET program that displays the count of odd numbers from a list of 10 numbers. The list and the method to count odd numbers should be in a separate class “Counter”.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var obj = new Counter();
obj.Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine(obj.CountOddNumbers());
Console.ReadKey();
}
}

class Counter
{
public List Numbers { get; set; }

public int CountOddNumbers()
{
return Numbers.Count(x => x % 2 == 1);
}
}
}

5. Write a .NET application using C# to calculate area of a circle. The program should demonstrate the capability of displaying to user any encountered exception.
using System;

namespace ConsoleApplication1
{
class Program
{
static void Main()
{
try
{
Circle obj = new Circle();
Console.WriteLine(“Enter the radius”);
double r = Convert.ToDouble(Console.ReadLine());
//Console.WriteLine(“The area is {0}.”, 3.14 * r * r); //Simple alternative
Console.WriteLine(“The area is {0}.”, obj.Area(r));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
}

class Circle
{
public double Area(double radius)
{
return Math.PI * Math.Pow(radius, 2);
}
}
}

6. Assuming a suitable database schema, write a sample code using ADO.NET in C# to generate a list of employee in IT department having salary more than or equal to $5000.
using System;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
class SqlConnectionDemo
{
static void Main()
{
// 1. Instantiate the connection
SqlConnection conn
= new SqlConnection(“Data Source=.;Initial Catalog=Office;Integrated Security=SSPI”);

try
{
// 2. Open the connection
conn.Open();

// 3. Pass the connection to a command object
SqlCommand cmd
= new SqlCommand(“select Name from Employee where departmentid = 7 and salary >= 5000 order by Name”, conn);

// 4. Use the connection
// Get query results
SqlDataReader rdr = cmd.ExecuteReader();

// print the names of each record
while (rdr.Read())
Console.WriteLine(rdr["Name"]);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// 5. Close the connection
conn.Close();

Console.ReadKey();
}
}
}
}
7. Write a .NET program that sorts a collection of numbers and displays the ordered output.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
var numbers = new List() { 5, 4, 3, 2, 1, 10, 6, 8, 7, 9 };
var orderedNumbers = numbers.OrderBy(x => x);
foreach (var item in orderedNumbers)
Console.WriteLine(item);

//new List { 5, 4, 3, 2, 1, 10, 6, 8, 7, 9 }.OrderBy(x => x).ToList().ForEach(Console.WriteLine); //One-liner alternative
Console.ReadKey();
}
}
}

8. Write a program in .NET that calculates the perimeter of a rectangle. Program should handle and display any runtime exceptions.
using System;

namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
try
{
Console.WriteLine(“Enter rectangle’s length: “);
var length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(“Enter rectangle’s breadth: “);
var breadth = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(“The perimeter is {0}.”, 2 * (length + breadth));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
}
}

9. Write a program to demonstrate the use of generic class “List” in C#.
Code:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
//A simple class
class Contact
{
public string Name { get; set; }
public long ContactNumber { get; set; }
}

internal class Program
{
private static void Main()
{
//List is used to hold a list (like array) of any type T.
//Here, “addressBook” is created to hold a list of objects of “Contact” types.
List addressBook = new List();

Contact c; //Object “c” is declared.

//Adding a “Contact” object to the list.
c = new Contact(); //Object “c” is initialized. Now, memory is allocated for the class’s object in Heap, and its address is assigned to “c”.
c.Name = “Ram”;
c.ContactNumber = 9841123456;
addressBook.Add(c); //The list now holds one item.

//Adding another “Contact” object to the list. Since first contact is already added to the list, “c” can now safely point to another newly allocated Contact instance in heap.
c = new Contact() { Name = “Shyam”, ContactNumber = 9803654321 }; //Same thing, done in a shorter way, using object initialization.
addressBook.Add(c);

//Adding another “Contact” object to the list. This technique doesn’t even require assigning new Contact to “c”. The small brackets () after new Contact are optional.
addressBook.Add(new Contact { Name = “Sita”, ContactNumber = 9841987654 }); //Same thing, done in shortest way.

//You can add as many objects as you like; both at design time and runtime (asking user to enter multiple contacts).

foreach (Contact item in addressBook)
{
Console.WriteLine(item.Name + ” has contact number ” + item.ContactNumber);
}

Console.ReadKey();
}
}
}

//Output:
//Ram has contact number 9841123456
//Shyam has contact number 9803654321
//Sita has contact number 9841987654

10. Write a lambda expression (in LINQ) to retrieve the list of all the employees with property “FirstName” starting with the letters “Ra” in a list named “employeeList” of type List.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
var allEmployeeList = new List();
allEmployeeList.Add(new Employee() { FirstName = “Ram”, Salary = 20000, DepartmentId = 7 });
allEmployeeList.Add(new Employee() { FirstName = “Laxman”, Salary = 15000, DepartmentId = 7 });
allEmployeeList.Add(new Employee() { FirstName = “Sita”, Salary = 15000, DepartmentId = 14 });
allEmployeeList.Add(new Employee() { FirstName = “Rawan”, Salary = 420, DepartmentId = 13 });

var filteredEmployeeList =
allEmployeeList.Where(x => x.FirstName.StartsWith(“Ra”, StringComparison.OrdinalIgnoreCase));
foreach (var employee in filteredEmployeeList)
Console.WriteLine(employee.FirstName);

Console.ReadKey();
}
}

class Employee
{
public string FirstName { get; set; }
public int Salary { get; set; }
public int DepartmentId { get; set; }
}
}

Windows Form applications
1. Create a Windows form application that takes two textboxes, a dropdown with add, subtract, multiply and divide options, and a button to perform addition, subtraction, multiplication or division of the entered numbers and displays the result when the button is pressed. Use label or dialog box to display the result.
Design:

Code:
//This method is invoked when button “button1″ is clicked.
private void button1_Click(object sender, EventArgs e)
{
try
{
//Reads the values from textboxes and tries to assign them into variables.
var num1 = Convert.ToDouble(textBox1.Text);
var num2 = Convert.ToDouble(textBox2.Text);

//”SelectedIndex” of “combobox” control returns the index of currently selected item.
switch (comboBox1.SelectedIndex)
{
case 0: //Add
label3.Text = (num1 + num2).ToString();
break;
case 1: //Subtract
label3.Text = (num1 – num2).ToString();
break;
case 2: //Multiply
label3.Text = (num1 * num2).ToString();
break;
case 3: //Divide
label3.Text = (num1 / num2).ToString();
break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //Displays dialog box containing any exception.
}
}

Output:

2. Create a program that creates a DataTable (in-memory table) and displays it in DataGridView.
Design:

Code:
private void Form1_Load(object sender, EventArgs e)
{
//Creates an in-memory table (datatable) with no schema/columns defined.
DataTable dt = new DataTable();

//Add columns to the in-memory datatable so that the table gets a schema/structure.
dt.Columns.Add(“Name”); //First column added.
dt.Columns.Add(“Contact”); //Second column added.
dt.Columns.Add(“Email”); //Third column added.

//Now since datatable has schema, we add rows to it. A row in WinForms is represented using an object of DataRow class.
//The new DataRow object should know what the schema of the table is, so dt.NewRow() is used to initialize DataRow object with schema of the required type.
DataRow dr; //Object of DataRow type is declared. It doesn’t know anything about table schema.
dr = dt.NewRow(); //DataRow object is initialized, meaning a new row is created in memory, with same schema as that of the datatable object dt.

//The in-memory data row with schema as that of dt should now be populated with data.
dr["Name"] = “Ram”;
dr["Contact"] = 9841111111;
dr["Email"] = “Ram@gmail.com”;

//Finally, add the new populated row in the in-memory datatable.
dt.Rows.Add(dr);

//Assign the datatable object as DataSource of the DataGridView control in the UI.
dataGridView1.DataSource = dt;
}

Output:

3. Create a program that reads from a file and displays the content to a label control. Also, replace the file-contents with new contents.
Design:

Code:
private void Form1_Load(object sender, EventArgs e)
{
//Opens a file for read operation.
StreamReader sr = new StreamReader(“c:\\sample.txt”);
label1.Text = sr.ReadToEnd(); //Reads the file till the end, and displays the file-content to label in the UI.
sr.Close(); //We should close the file after use (releasing resources).

//Opens a file for write operation.
StreamWriter sw = new StreamWriter(“C:\\sample.txt”);
sw.WriteLine(“I am fine, thank you.”); //Replaces the file-contents with the provided contents.
sw.Close(); //We should close the file after use (releasing resources).
}

Output:
During first run (with original file contents):

During second run (with replaced file contents):

Web applications

1. Create a web page that allows user to input two numbers and perform addition or subtraction on them. Use two buttons that perform addition and subtraction operations respectively. You can display the result on any HTML element (like text input element, or div) or alert it.

Design:

Code:

Using pure JavaScript:
HTML with JavaScript

Number 1:

Number 2:


Result


Using JavaScript with jQuery:
HTML with JavaScript/jQuery

Number 1:

Number 2:


Result


Output:

JavaScript vs jQuery (example)
The example retrieves value from a textbox having id=’myid’ and alerts to the user by using JavaScript and jQuery.
HTML

JavaScript:

jQuery:

 ALL THE BEST 

International business FAQ’s

EXAM 2012 FALL

1)What do you mean by globalization? Which forces lead international business organizations towards globalization of their functions? Discuss.

Globalization refers to the shift toward a more integrated and independent world economy. It is the system of interaction among the countries of the world in order to develop the global economy. It involves technological, economic, political and cultural exchanges in communication, transportation and infrastructure.

Due to globalization the whole world is increasingly behaving as though it were a part of a single market with independent production, consuming similar goods and responding to the same impulses. The current wave of globalization has been driven by policies that have opened economic domestically and internationally.

The forces that lead international business organizations towards globalization of their functions are:
a. Declining trade and investment barriers:
International trade occurs when a firm exports goods or services to consumers in another country. During 1920 and 30s there were formidable barriers to international trade in the form of high tariffs. These tariffs were implemented to protect domestic industries from foreign competition. Ultimately, this led to great depression.
After this, many countries started to remove barriers to the free flow of goods and services, capital between countries. Under the umbrella of GATT (General Agreement on Tariffs and Trade),eight rounds of negotiations among member states have worked to lower barriers to the free flow of goods and services.
In addition to reducing trade barriers, many countries have also been progressively removing restrictions to foreign direct investment (FDI). Governments desire to facilitate FDI also has been reflected in dramatic increase in the number of bilateral investment treaties designed to protect and promote investment between two countries.
Such trends have been driving both the globalization of markets and the globalization of the products.
b. The role of technology:
Technological change has been made globalization of markets and production a tangible reality. The world has seen major advances in communication, information processing, transportation technology and emergence of internet and World Wide Web.
• Microprocessors and Telecommunications:
The development of microprocessor has enabled the explosive growth of high power, low cost computing and vastly increasing the amount of information that can be processed by individuals and firms. Over the past 3o years, global communications have been revolutionized by developments in satellite, optical fiber and wireless technologies and Internet and World Wide Web. These technologies rely on the microprocessor to encode, transmit and decode that vast amount of information that flows along these electronic highways.
• Internet and World Wide Web:
The rapid growth of the internet and the associated World Wide Web is the latest development in technology. It promises to develop into the information backbone of the global economy. The greatest current potential of the web seems to be in the business-to-business arena.
c. Transportation technology:
After the World War II many changes were seen in transportation technology as well. The most important changes were commercial jet aircrafts and super freighters. The jet aircraft reduced the time taken from one place to another greatly. It had effectively shrunken the globe. The cost of shipping goods over long distances was also lowered.

2) Why is it crucial for global businesses to understand and analyzes the existing education system of the place where they desire to expand? Explain.
There are three types of education systems that exist today, the Traditional education, the Industrial age education, and the Information age education. The traditional education system have existed for thousand years focuses on basic knowledge of an agriculture society where “rote memorization” is important and success is based on passing examinations. After graduated, most students will work as administrations for government (In the old day: The emperor). This system is now considered obsolete by most educators. The Industry age education system have existed for about three hundreds years focuses on meeting the needs of the industry where students learn “Mass production processes” to produce certain manufactured products. In this system, students learned everything they needed to know in school, and education usually ended at graduation. Success is based on getting jobs in the manufacturing industry. This system is becoming obsolete as it no longer equates to success in today business. The Information age education system is relatively new focuses mostly on technical knowledge and the application of technology to solve business problems. Students learn the fundamental in schools however education do not end there but continue throughout their life as technology always changes. Success is based on the knowledge and skills that individual obtain in actual working life and adjust to every situation that he or she meets. In this system, innovation and individual creativity are highly valued.
Students who are educated by the Traditional education do NOT feel comfortable with the Industrial age education system because the academia’s view and industry‘s view differs greatly. Students graduated with good grades by “memorization” and passing exams may NOT be able to apply what they learned into industry system and may NOT be successful in their jobs. This situation has happened in many countries that still follow the traditional education system. Students educated by the Industrial-age education system and then work in information technology system will have to adjust by additional trainings. There is a huge gap exists between the industrial age education and what people need to know to stay competitive in the information age, and that gap is widening. This situation is happening in many countries, mostly Europe and America, as change is still take place in their education systems.
These may not be the skills we have been taught in school today but the skills that we must acquire because the lifelong learners are becoming the most valuable people in this competitive world.
A lifelong learner always reads and learn new things. improve their skills by taking additional trainings. Even it is the responsibility of the individual to learn, individual learning alone cannot help improve a society. To be competitive as a society, we must advocate more learning by encourage more readings, more trainings, more coverage of technical knowledge, and more opportunity for learning.
A society that does not value learning cannot improve. Our success, our survival in this rapidly changing world, will depend upon our ability to respond to change. To do that, we must be able to learn and continue learning.
So it is clear that with no proper educational system businesses cannot expand their operations due to lack of qualified workforce. So it is very crucial to analyze and understand the existing education system.

3) Differentiate the Theory of Comparative Advantage from the Theory of Absolute Advantage.
Theory of Comparative Advantage Theory of Absolute Advantage
1) An individual, business, or country that can produce a certain good at a lower opportunity cost than its trading partners is said to have a comparative advantage.
2) This theory was proposed by David Ricardo.

3) It makes sense for a country to specialize in the production of those goods that it produces most effectively, and to buy goods that it produces less effectively from other countries even if this means buying goods from other countries that it could produce more effectively itself.

4) It suggests that trade is a positive sum game in which all countries that participate realize economic gains. This theory also suggests that consumer in all nation can consumes more if there are no restrictions on trade.
1) An individual, business, or country can produce a certain good with fewer resources than other countries is said to have absolute advantage.

2) This theory was proposed by Adam Smith.

3) It makes sense for a country that must produce goods that they are efficient on than any other country and they must produce goods that have an absolute advantage for the country.

4) This theory concludes that trade is a positive sum game, it provides net gain for all involved.

5) As a global business manager why is it necessary for you to access the impact of intellectual property rights on your business? Discuss.
Intellectual property (IP) rights are the legally recognized exclusive rights to creations of the mind. Under intellectual property law, owners are granted certain exclusive rights to a variety of intangible assets, such as musical, literary, and artistic works; discoveries and inventions; and words, phrases, symbols, and designs. Common types of intellectual property rights include copyrights, trademarks patents, industrial design rights, trade dress, and in some jurisdictions trade secrets.

These exclusive rights allow owners of intellectual property to benefit from the property they have created, providing a financial incentive for the creation of an investment in intellectual property, and, in case of patents, pay associated research and development costs.
Addition to this, these rights restricts the theft of trademark, patent and their brand of businesses.
So it is necessary for global business manger to access the impact of intellectual property rights on your business.

6) How would you assess the impact of cultural differences of international business? Explain.
The number of companies operating internationally is growing constantly. Many new firms are launched in foreign country which is creating a high competition.
Understanding cultural differences can mean success or losing the deal at first meeting in today’s business world. It can create a huge impact on reputation and the way business is viewed by rest of the world. When going international the challenges that the company must handle are new and unfamiliar. Culture is one of the obstacles and can affect entire organization.
Culture can influence the business in different ways. For example, cultural mistakes were made by big companies such as coca-cola in the 20’s when the Chinese characters that sounded like coke stood for a completely vulgar meaning in Chinese. So, before entering the foreign country, we should respect and understand the foreign culture without enforcing on our own beliefs on people.
So, to make connection essential for ongoing business relationships we must understand the culture of people we are dealing with. A common language helps to break through cultural barriers and sort out misunderstandings.

7) What are the non-tariff barriers? Comment on their application in this era of globalization? State its merits and demerits.
Non-tariff barriers to trade (NTBs) are trade barriers that restrict imports, but are unlike the usual form of a tariff. Some common examples of NTB’s are anti-dumping measures and countervailing duties, which, although called non-tariff barriers, have the effect of tariffs once they are enacted.
Their use has risen sharply after the WTO rules led to a very significant reduction in tariff use. Some non-tariff trade barriers are expressly permitted in very limited circumstances, when they are deemed necessary to protect health, safety, sanitation, or depletable natural resources. In other forms, they are criticized as a means to evade free trade rules such as those of the World Trade Organization (WTO), the European Union (EU), or North American Free Trade Agreement (NAFTA) that restrict the use of tariffs.
Some of non-tariff barriers are not directly related to foreign economic regulations but nevertheless have a significant impact on foreign-economic activity and foreign trade between countries.
Trade between countries is referred to trade in goods, services and factors of production. Non-tariff barriers to trade include import quotas, special licenses, unreasonable standards for the quality of goods, bureaucratic delays at customs, export restrictions, limiting the activities of state trading, export subsidies, countervailing duties, technical barriers to trade, sanitary and phyto-sanitary measures, rules of origin, etc. Sometimes in this list they include macroeconomic measures affecting trade.
Types of non tariff barriers are:
- Licensing
- Quotas
- Embargo
- Quality and Standards
- Administrative and bureaucratic delays at the entrance
- Import deposits
- Foreign exchange restrictions and foreign exchange controls
- Intellectual property laws
- “Buy national” policy
So due to these non-tariff barriers in the era of globalization it has its merits and demerits which is discussed below:
Merits:
- As it is concerned with quality and standard consumers get quality products.
- It provides trademark, patent, intellectual property rights.
- Supports national or domestic products as it concerns with “buy national” policy.
Demerits:
- Due to quotas system all customer will not be satisfied.
- Effect in smooth operative activities of organization.
- Delays in entrance of foreign goods and products.

8) Discuss the role of World Trade Organization (WTO) in international trade.
The World Trade Organization (WTO) is the only global international organization dealing with the rules of trade between nations. At its heart are the WTO agreements, negotiated and signed by the bulk of the world’s trading nations and ratified in their parliaments. The goal is to help producers of goods and services, exporters, and importers conduct their business.
The WTO’s mission is to open markets gradually while ensuring that rules are respected. The origin of the organization dates back to the end of World War II when the idea of peaceful cooperation among peoples was emerging. In 1947, a number of countries decided to open up their markets on the basis of common principles, and founded the WTO’s predecessor, the General Agreement on Tariffs and Trade (GATT). In the current round of trade negotiations, the WTO is seeking to make further advances in equitable trade.
The WTO acts as conductor, tribunal, monitor and trainer
Orchestra conductor
International trade is governed by very precise rules developed by the WTO’s members. Countries must apply these rules when trading with one another. The WTO acts as the orchestra conductor, ensuring that rules are respected. The WTO was founded in 1995, but its origins date back to 1947 and the creation of the GATT. Since then, WTO members have adapted these rules to keep up with new developments. For example, services have developed considerably since the 1980s, and have now become one of the most important economic sectors. As a result, WTO members established rules governing international trade in services. Adapting or changing the principles of international trade means reaching consensus among WTO members through a round of negotiations. The latest round the ninth since 1947 was launched in 2001 (see “How do trade negotiations work?” above).
Tribunal
One of the main roles of the WTO is to settle disputes between its members. The WTO trade tribunal, where members may file complaints against other members who fail to abide by the principles of international trade. There are three stages to dispute settlement. To begin with, the disputing countries try to settle their differences by themselves. If that fails, the case is decided by a panel made up of three experts, which issues a ruling. That ruling may be appealed. Once a definitive ruling has been issued, the losing party must comply. If it does not, it is liable to sanctions. Since 1995, over 400 complaints have been filed by WTO members.
Monitor
The WTO regularly reviews the trade policies of its members. These reviews assess whether WTO members are aiding by WTO rules and measure the impact of their domestic policies on international trade. The purpose of these reviews is not so much to solve problems as to prevent them from occurring in the first place.
Trainer
The WTO provides training programmes for government officials from developing countries for example, ministry staff or customs officials. The WTO currently spends about 35 million Swiss francs annually on these programmes. Africa is the main beneficiary, followed by Asia and Latin America. In 2011, approximately 26 per cent of training activities took place in Africa.

9) Discuss briefly about the pricing issues to be considered while expanding the foreign businesses.
The price of a product or service plays a large part in how well it sells. Producers and retailers practice ethical pricing strategies to earn profits without defrauding competitors or consumers. Despite that, competitor’s prices, convenience, availability and other factors affect consumer impressions of fair pricing. Business laws protect competitors and consumers from many unethical pricing strategies that unscrupulous marketers may wish to attempt.
Fair Pricing
Producers sell products at wholesale costs that pay for the labor, materials and overhead to make the products with a reasonable margin of profit. Retailers commonly mark up the price to two or three times the wholesale cost to pay for employees and overhead with a considerable profit margin for the company and its shareholders. At times retailers cut prices to stimulate sales of particular products or to sell large quantities of popular products.
Advertising Schemes
Trade laws bind companies’ advertising price comparisons. A car dealer who claims to sell for thousands less than competitors has to be able to produce documentation of that competitor’s prices and their own to prove it. Advertisers publishing an inexpensive product when there is not much inventory of the product are often using the illegal bait-and-switch scheme with a large inventory of a similar product at a much higher price.
Price Cutting
At times firms cut prices to sell off outdated stock or to make way for a new line of products. Some vendors set prices very low for new products to introduce them to the market and inspire customers to try them. These are both legal and ethical pricing strategies. A company uses unethical pricing cuts to squash the sales of competitors by selling the same products for lower prices. Federal laws protect competitors from undercutting.
Monopolizing
A monopoly exists when there is only one source of a particular product. Federal antitrust laws protect competition in the marketplace by outlawing monopolies. The American Telephone and Telegraph Corporation (AT&T) was a communications monopoly. The government divided the company up in 1982, o new competing phone companies. It is also illegal to fix prices or divide markets among competitors to undermine competition. An assumed monopoly exists when one firm sets pricing for the whole market.
Charm Pricing
One of the most common pricing tactics that companies use is to price their products just a few pennies lower so that the first number of the price is lower. For example, if you were using charm pricing, you would sell your products for $19.99 instead of $20 because $19.99 seems like it is less. It pushes your product into the $10-$19.99 price bracket so it appears to cost much less than $20.
Price skimming: Discriminating through time
Price skimming is when the price for a product is first sold at a very high price and then gradually lowered. The goal here is pretty obvious, producers want to capture each step on the demand curve; consumers who are willing to pay more buy the product first, and then new groups’ purchases are triggered with each decrease in price.

This strategy is most commonly seen in the tech industry, as some consumers are willing to pay a premium price for the newest gadgets. Apple is a prime example, as prices drop within months of a release and new iterations happen within six to 12 months. Like price discrimination, this practice isn’t illegal, but if too obvious and not tested enough, it can trigger an unfortunate PR backlash. Apple received a lot of flack for cutting their production cycle on the latest iPad, instantly lowering the prices of the older models.

10) What are different types of international business strategy? Explain.
International business strategy refers to plans that guide commercial transactions taking place between entities in different countries. Typically, international business strategy refers to the plans and actions of private companies rather than governments; as such, the goal is increased profit.
Most companies of any appreciable size deal with at least one international partner n their supply chain, and in most well-established fields competition is international. Because methods of doing business vary appreciably in different countries, an understanding of cultural and linguistic barriers, political and legal systems, and the many complexities of international trade is essential to commercial success.
a) Multidomestic Strategy
A firm using a multidomestic strategy sacrifices efficiency in favor of emphasizing responsiveness to local requirements within each of its markets. Rather than trying to force all of its American-made shows on viewers around the globe, MTV customizes the programming that is shown on its channels within dozens of countries, including New Zealand, Portugal, Pakistan, and India. Similarly, food company H. J. Heinz adapts its products to match local preferences. Because some Indians will not eat garlic and onion, for example, Heinz offers them a version of its signature ketchup that does not include these two ingredients.
b) Global Strategy
A firm using a global strategy sacrifices responsiveness to local requirements within each of its markets in favor of emphasizing efficiency. This strategy is the complete opposite of a multidomestic strategy. Some minor modifications to products and services may be made in various markets, but a global strategy stresses the need to gain economies of scale by offering essentially the same products or services in each market.
Microsoft, for example, offers the same software programs around the world but adjusts the programs to match local languages. Similarly, consumer goods maker Procter & Gamble attempts to gain efficiency by creating global brands whenever possible. Global strategies also can be very effective for firms whose product or service is largely hidden from the customer’s view, such as silicon chip maker Intel. For such firms, variance in local preferences is not very important.
c) Transnational Strategy
A firm using a transnational strategy seeks a middle ground between a multidomestic strategy and a global strategy. Such a firm tries to balance the desire for efficiency with the need to adjust to local preferences within various countries. For example, large fast-food chains such as McDonald’s and Kentucky Fried Chicken (KFC) rely on the same brand names and the same core menu items around the world. These firms make some concessions to local tastes too. In France, for example, wine can be purchased at McDonald’s. This approach makes sense for McDonald’s because wine is a central element of French diets.
11) Differentiate Strategic Alliance and Joint Venture.
Joint Ventures
When two companies invest funds into creating a third, jointly owned company, that new subsidiary is called a joint venture. Because the joint venture can access assets, knowledge and funds from both of its partners it can combine the best features of those companies without altering the parent companies. The new company is an ongoing entity that will be in business for itself, but profits are owned by the parents.
Strategic Alliances
When companies want to quickly gain a new area of expertise or access to new technology or markets, they usually have two options: buy a smaller company with those assets or form a strategic alliance with another company that would benefit equally from the partnership. These agreements often have a limited scope and function, such as trading access to a strong brand for access to an emerging technology.
Joint venture and Strategic Alliance differ from each other financially and legally too. There is difference between them in their definitions too. A joint venture is indeed a contractual agreement between two or more companies that come together in business in terms of the performance of a business task.
A strategic alliance on the other hand is a formal relationship between two or more companies in pursuit of common goal in their business even while remaining as independent organizations. This is the main difference between the two terms joint venture and strategic alliance.
In other words it can be said the two or more companies that join together in a joint venture do not remain as independent companies in a joint venture. On the other hand the two or more companies that join together in a strategic alliance will remain as independent organizations in a strategic alliance.
There has been a lot of debate on the issue whether joint venture is better than strategic alliance. It is generally felt that joint venture is better than strategic alliance for some interesting reasons. A joint venture is legally binding in a better way than a strategic alliance.
When it comes to tax purposes strategic alliance is a bit disadvantageous when compared to joint venture. On the other hand you will find strategic alliance more flexible when compared to joint venture. Alliance can also be broken by the help of less number of lawyers. A joint venture on the other hand is not easily broken for that matter. This is because of the fact that it is more legally binding in nature.
Things would work better in strategic alliance due to the fact that it is characterized by a wonderful combination of resources or information. On the other hand lot of hard work has to be put into joint venture in order to taste success.

12) Short notes
a) Licensing:
Licensing which involve minimal commitment of resources and effort on the part of international markets are easy ways of entering the foreign markets. Under international licensing, a firm in another country to use the intellectual property (such as patents, trademarks, technology etc). the licensee will have to pay the licensor a royalty fee.A licensor may grant a license under intellectual property laws to authorize a use (such as copying software or using a (patented) invention) to a licensee, sparing the licensee from a claim of infringement brought by the licensor.[7] A license under intellectual property commonly has several components beyond the grant itself, including a term, territory, renewal provisions, and other limitations deemed vital to the licensor.
Term: many licenses are valid for a particular length of time. This protects the licensor should the value of the license increase, or market conditions change. It also preserves enforceability by ensuring that no license extends beyond the term of the agreement.
Territory: a license may stipulate what territory the rights pertain to. For example, a license with a territory limited to “North America” (Mexico/United States/Canada) would not permit a licensee any protection from actions for use in Japan.
A shorthand definition of license is “a promise by the licensor not to sue the licensee.” That means without a license any use or exploitation of intellectual property by a third party would amount to copying or infringement. Such copying would be improper and could, by using the legal system, be stopped if the intellectual property owner wanted to do so.[8]
It is undeniable that intellectual property licensing plays a major role in today’s business and economy. Business practices such as franchising, technology transfer, publication and character merchandising entirely depend on the licensing of intellectual property. Licensing has been recognized as an independent branch of law. It is born out of the interplay of the doctrine of contract and the principles of intellectual property.
a) Tariff barriers:
A tariff is a tax on imports or exports (an international trade tariff), or a list of prices for such things as rail service, bus routes, and electrical usage (electrical tariff, etc.).
When tariffs are an integral element of a country’s technology strategy, the tariffs can be highly effective in helping to increase and maintain the country’s economic health. As an integral part of the technology strategy, tariffs are effective in supporting the technology strategy’s function of enabling the country to outmaneuver the competition in the acquisition and utilization of technology in order to produce products and provide services that excel at satisfying the customer needs for a competitive advantage in domestic and foreign markets.
This is related to the Infant industry argument.
In contrast, in economic theory tariffs are viewed as a primary element in international trade with the function of the tariff being to influence the flow of trade by lowering or raising the price of targeted goods to create what amounts to an artificial competitive advantage. When tariffs are viewed and used in this fashion, they are addressing the countries and the competitors’ respective economic heaths in terms of maximizing or minimizing revenue flow rather than in terms of the ability to generate and maintain a competitive advantage which is the source of the revenue. As a result, the impact of the tariffs on the economic health of the country is at best minimal but often is counter-productive.
A program within the US intelligence community, Project Socrates that was tasked with addressing America’s declining economic competitiveness determined that countries like China and India were using tariffs as an integral element of their respective technology strategies to rapidly build their countries into economic superpowers. It was also determined that the US, in its early years, had also used tariffs as an integral part of amounted to technology strategies to transform the country into a superpower.

EXAM 2013 FALL
1) Define International business. What makes international business different from domestic business?
International business conducts business transactions all over the world. These transactions include the transfer of goods, services, technology, managerial knowledge and capital to other countries. It compromises all commercial transactions that take place between two or more regions, countries and nations beyond their political boundary. Its objectives are:
- Sales expansion
- Achieve higher rates of profit
- Increase market share
- Make use of available technology and human resources

How international business different from domestic business
Scope: Scope of international business is quite wide. It includes not only merchandise exports, but also trade in services, licensing and franchising as well as foreign investments. Domestic business pertains to a limited territory. Though the firm has many business establishments in different locations all the trading activities are inside a single boundary.
Benefits: International business benefits both the nations and firms. Domestic business have lesser benefits when compared to the former.
- To the nations: Through international business nations gain by way of earning foreign exchange, more efficient use of domestic resources, greater prospects of growth and creation of employment opportunities. Domestic business as it is conducted locally there would be no much involvement of foreign currency. It can create employment opportunities too and the most important part is business since carried locally and always dealt with local resources the perfection in utilization of the same resources would obviously reap the benefits.
- To the firms: The advantages to the firms carrying business globally include prospects for higher profits, greater utilization of production capacities, way out to intense competition in domestic market and improved business vision. Profits in domestic trade are always lesser when compared to the profits of the firms dealing transactions globally.
Modes of entry: A firm desirous of entering into international business has several options available to it. These range from exporting/importing to contract manufacturing abroad, licensing and franchising, joint ventures and setting up wholly owned subsidiaries abroad. Each entry mode has its own advantages and disadvantages which the firm needs to take into account while deciding as to which mode of entry it should prefer. Firms going for domestic trade does have the options but not too many as the former one.
To establish business internationally firms initially have to complete many formalities which obviously is a tedious task. But to start a business locally the process is always an easy task. It doesn’t require to process any difficult formalities.
Purvey: Providing goods and services as a business within a territory is much easier than doing the same globally. Restrictions such as custom procedures do not bother domestic entities but whereas globally operating firms need to follow complicated customs procedures and trade barriers like tariff etc.
Sharing of Technology: International business provides for sharing of the latest technology that is innovated in various firms across the globe which in consequence will improve the mode and quality of their production.
Political relations: International business obviously improves the political relations among the nations which gives rise to Cross-national cooperation and agreements. Nations co-operate more on transactional issues.

2) Explain the motivations for firms to engage in international business.
The motivations for firms to engage in international business are:
a. The role of technology:
Technological change has been made globalization of markets and production a tangible reality. The world has seen major advances in communication, information processing, transportation technology and emergence of internet and World Wide Web.
• Microprocessors and Telecommunications:
The development of microprocessor has enabled the explosive growth of high power, low cost computing and vastly increasing the amount of information that can be processed by individuals and firms. Over the past 3o years, global communications have been revolutionized by developments in satellite, optical fiber and wireless technologies and Internet and World Wide Web. These technologies rely on the microprocessor to encode, transmit and decode that vast amount of information that flows along these electronic highways.
• Internet and World Wide Web:
The rapid growth of the internet and the associated World Wide Web is the latest development in technology. It promises to develop into the information backbone of the global economy. The greatest current potential of the web seems to be in the business-to-business arena.
b. Transportation technology:
After the World War II many changes were seen in transportation technology as well. The most important changes were commercial jet aircrafts and super freighters. The jet aircraft reduced the time taken from one place to another greatly. It had effectively
c. Declining trade and investment barriers:
International trade occurs when a firm exports goods or services to consumers in another country. During 1920 and 30s there were formidable barriers to international trade in the form of high tariffs. These tariffs were implemented to protect domestic industries from foreign competition. Ultimately, this led to great depression.
After this, many countries started to remove barriers to the free flow of goods and services, capital between countries. Under the umbrella of GATT(General Agreement on Tariffs and Trade),eight rounds of negotiations among member states have worked to lower barriers to the free flow of goods and services.
In addition to reducing trade barriers, many countries have also been progressively removing restrictions to foreign direct investment (FDI). Governments desire to facilitate FDI also has been reflected in dramatic increase in the number of bilateral investment treaties designed to protect and promote investment between two countries.
Such trends have been driving both the globalization of markets and the globalization of the products.

3) Explain how political and legal system affects international business.

The study of political systems is extensive and complex. A political system is basically the system of politics and government in a country. It governs a complete set of rules, regulations, institutions, and attitudes. A main differentiator of political systems is each system’s philosophy on the rights of the individual and the group as well as the role of government. Each political system’s philosophy impacts the policies that govern the local economy and business environment.
There are more than thirteen major types of government, each of which consists of multiple variations. Let’s focus on the overarching modern political philosophies. At one end of the litical philosophies, or ideologies, is anarchism, which contends that individuals should control political activities and public government is both unnecessary and unwanted. At the other extreme is totalitarianism, which contends that every aspect of an individual’s life should be controlled and dictated by a strong central government. In reality, neither extreme exists in its purest form. Instead, most countries have a combination of both, the balance of which is often a reflection of the country’s history, culture, and religion. This combination is called pluralism, which asserts that both public and private groups are important in a well-functioning political system. Although most countries are pluralistic politically, they may lean more to one extreme than the other.
Democracy is the most common form of government around the world today. Democratic governments derive their power from the people of the country, either by direct referendum (called a direct democracy) or by means of elected representatives of the people (a representative democracy). Democracy has a number of variations, both in theory and practice, some of which provide better representation and more freedoms for their citizens than others.
A company may ask several questions regarding a prospective country’s government to assess possible risks:
- How stable is the government?
- Is it a democracy or a dictatorship?
- If a new party comes into power, will the rules of business change dramatically?
- Is power concentrated in the hands of a few, or is it clearly outlined in a constitution or similar national legal document?
- How involved is the government in the private sector?
- Is there a well-established legal environment both to enforce policies and rules as well as to challenge them?
- How transparent is the government’s political, legal, and economic decision-making process?
Let’s focus briefly on how the political and economic ideologies that define countries impact their legal systems. In essence, there are three main kinds of legal systems—common law, civil law, and religious or theocratic law. Most countries actually have a combination of these systems, creating hybrid legal systems.
Civil law is based on a detailed set of laws that constitute a code and focus on how the law is applied to the facts. It’s the most widespread legal system in the world.
Common law is based on traditions and precedence. In common law systems, judges interpret the law and judicial rulings can set precedent.
Religious law is also known as theocratic law and is based on religious guidelines. The most commonly known example of religious law is Islamic law, also known as Sharia. Islamic law governs a number of Islamic nations and communities around the world and is the most widely accepted religious law system. Two additional religious law systems are the Jewish Halacha and the Christian Canon system, neither of which is practiced at the national level in a country. The Christian Canon system is observed in the Vatican City.
While the past century has seen a major shift toward free trade, many governments continue to intervene in trade. Governments have several key policy areas that can be used to create rules and regulations to control and manage trade.
- Tariffs. Tariffs are taxes imposed on imports. Two kinds of tariffs exist—specific tariffs, which are levied as a fixed charge, and ad valorem tariffs, which are calculated as a percentage of the value. Many governments still charge ad valorem tariffs as a way to regulate imports and raise revenues for their coffers.
- Subsidies. A subsidy is a form of government payment to a producer. Types of subsidies include tax breaks or low-interest loans; both of which are common. Subsidies can also be cash grants and government-equity participation, which are less common because they require a direct use of government resources.
- Import quotas and VER. Import quotas and voluntary export restraints (VER) are two strategies to limit the amount of imports into a country. The importing government directs import quotas, while VER are imposed at the discretion of the exporting nation in conjunction with the importing one.
- Currency controls. Governments may limit the convertibility of one currency (usually its own) into others, usually in an effort to limit imports. Additionally, some governments will manage the exchange rate at a high level to create an import disincentive.
- Local content requirements. Many countries continue to require that a certain percentage of a product or an item be manufactured or “assembled” locally. Some countries specify that a local firm must be used as the domestic partner to conduct business.
- Antidumping rules. Dumping occurs when a company sells product below market price often in order to win market share and weaken a competitor.
- Export financing. Governments provide financing to domestic companies to promote exports.
- Free-trade zone. Many countries designate certain geographic areas as free-trade zones. These areas enjoy reduced tariffs, taxes, customs, procedures, or restrictions in an effort to promote trade with other countries.

4) “Cultural diversity among the countries provides opportunities and threat to international business”. Explain the statement.
The number of companies operating internationally is growing constantly. Many new firms are launched in foreign country which is creating a high competition.
Understanding cultural differences can mean success or losing the deal at first meeting in today’s business world. It can create a huge impact on reputation and the way business is viewed by rest of the world. When going international the challenges that the company must handle are new and unfamiliar. Culture is one of the obstacles and can affect entire organization.
Culture can influence the business in different ways. For example, cultural mistakes were made by big companies such as coca-cola in the 20’s when the Chinese characters that sounded like coke stood for a completely vulgar meaning in Chinese. So, before entering the foreign country, we should respect and understand the foreign culture without enforcing on our own beliefs on people.
So, to make connection essential for ongoing business relationships we must understand the culture of people we are dealing with. A common language helps to break through cultural barriers and sort out misunderstandings.
Socio-cultural differences concern aspects of culture that can influence as individuals interaction with others of different backgrounds. It can influence how individuals respond to management demands operational requirements and company policies.
As the managers and the employees in multinational organization gradually understand the dimensions and differences, it is the duty of both managers and the employees to adopt strategies to keep diversity at bay. The strategies to manage socio-cultural differences are:
i) Good knowledge of foreign culture:
The first strategy is acknowledging and admitting the existence of difference between cultures. This mainly includes differences in perceptions, interpretations and evaluations of social situations. These differences have to be named, described, explained and understood.
ii) Respect of foreign culture:
Respects of foreign culture mean most of all accepting their differences without any judgment. Cultures are different and their members, they represent optimum to manage life situations in conditions they have been living in for a long time. So, respecting other culture helps to manage socio-cultural differences.
iii) Helpful steps in the relationship to a foreign country:
The next strategy is to find common solution, mutual understanding and simplification of the complicated and demanding cultural conditions.
iv) Ignore the cultural differences:
In this strategy, a stage comes where the managers ignore the differences. The employee and managers feel that in this type of strategy that “our way is the only way”. The ignorance of diversity precludes effective management of cultural differences and possibilities of minimizing negative impacts and increasing positive impacts of diversity.

Thus the global managers should manage this cultural diversity and cultural differences to acquire potential impact for the business to expand in this globalised world.

5) Define foreign exchange control and explain its objectives.
Foreign exchange controls are various forms of controls imposed by a government on the purchase/sale of foreign currencies by residents or on the purchase/sale of local currency by nonresidents.
Common foreign exchange controls include:
- Banning the use of foreign currency within the country
- Banning locals from possessing foreign currency
- Restricting currency exchange to government-approved exchangers
- Fixed exchange rates
- Restrictions on the amount of currency that may be imported or exported

The main objects of foreign exchange control may be stated as follows:
a) Conservation of Foreign Exchange :
Exchange control may be introduced by the monetary authority to conserve the gold, bullion, foreign exchange currencies, etc., i.e., foreign exchange resources, of the country. It may be necessary to ensure the availability of sufficient amount of foreign exchange needed to buy essential foreign goods.
b) Check on Flight of Capita:
Under the free exchange system there is the danger of huge outflow of capital which may weaken the country’s economy. Especially erratic shifting of capital tends to accentuate the disequilibrium in the balance of payments and it also adversely affects future growth of the country. Exchange control, however, offers a prompt and effective means to prevent such capital outflows.
c) Correcting Disequilibrium in Balance of Payments:
To correct the deficit in the balance of payments, the country needs to put a curb on imports. For this purpose, the use of Foreign exchange earnings by exporters for import of goods must be checked through appropriate exchange control. Again, exchange control is essential to implement an import policy very effectively. In short, exchange control may be introduced to protect the country’s balance of payments.
d) Stabilization of Exchange Rates:
In a free exchange market, exchange rate is a fluctuating phenomenon. Thus, exchange control may be adopted to maintain exchange rates at an arbitrarily chosen fixed point.
e) Protecting the Interest of Home Producers:
Exchange control may be used for giving protection to domestic producers by restricting the competition from foreign traders through import control.
f) Redemption of External Debt:
The Government may use the exchange control device to obtain foreign exchange needed for repaying or servicing of its foreign loans.

6) Explain the characteristics of multinational companies. What impact do they have on the economic life of the host country?
Multinational is made out of two words “Multi and national “. So Multinational means a company which operates in more than one country or which has access to International markets. Such companies has branches, Factories, Workshops, headquarters in different countries which are operated or are under control of the headquarters in the home country.
The characteristics of MNCs are:
a) International Operation: A multinational corporation operates in more than one country. It has branches, factories, offices in several countries. It operates through a network of branches and subsidiaries in host countries. They sell their products in different countries. For eg: Coca Cola, apple etc.
b) Professional Management: A Multinational corporation employs professional experts, specialized people. MNCs try to keep their employees updated by imparting them training from time to time. It employs professionals to handle the advance in technology effectively.
c) Centralized Control: The branches of Multinational companies spread in different countries are controlled and managed from the headquarters situated in the home country. Headquarters in the home country is the main branch. All branches operate within the policy framework formed by headquarters.
d) Oligopolistic Powers: Oligopoly means power in the hands of few companies only. Due to their giant size, the multinational companies occupy dominating position in the market .They join hands with big business houses and give rise to monopoly. They also take over other firms to acquire huge power and improve market share
e) Sophisticated Technology: Multinational companies make use of latest and advanced technology to supply world class products. They use capital-intensive technology and innovative techniques of production.

Advantages
The possible benefits of a multinational investing in a country may include:
• Improving the balance of payments – inward investment will usually help a country’s balance of payments situation. The investment itself will be a direct flow of capital into the country and the investment is also likely to result in import substitution and export promotion. Export promotion comes due to the multinational using their production facility as a basis for exporting, while import substitution means that products previously imported may now be bought domestically.
• Providing employment – FDI will usually result in employment benefits for the host country as most employees will be locally recruited. These benefits may be relatively greater given that governments will usually try to attract firms to areas where there is relatively high unemployment or a good labour supply.
• Source of tax revenue – profits of multinationals will be subject to local taxes in most cases, which will provide a valuable source of revenue for the domestic government.
• Technology transfer – multinationals will bring with them technology and production methods that are probably new to the host country and a lot can therefore be learnt from these techniques. Workers will be trained to use the new technology and production techniques and domestic firms will see the benefits of the new technology. This process is known as technology transfer.
• Increasing choice – if the multinational manufactures for domestic markets as well as for export, then the local population will gain form a wider choice of goods and services and at a price possibly lower than imported substitutes.
• National reputation – the presence of one multinational may improve the reputation of the host country and other large corporations may follow suite and locate as well.
Disadvantages
The possible disadvantages of a multinational investing in a country may include:
• Environmental impact – multinationals will want to produce in ways that are as efficient and as cheap as possible and this may not always be the best environmental practice. They will often lobby governments hard to try to ensure that they can benefit from regulations being as lax as possible and given their economic importance to the host country, this lobbying will often be quite effective.
• Access to natural resources – multinationals will sometimes invest in countries just to get access to a plentiful supply of raw materials and host nations are often more concerned about the short-term economic benefits than the long-term costs to their country in terms of the depletion of natural resources.
• Uncertainty – multinational firms are increasingly ‘footloose’. This means that they can move and change at very short notice and often will. This creates uncertainty for the host country.
• Increased competition – the impact the local industries can be severe, because the presence of newly arrived multinationals increases the competition in the economy and because multinationals should be able to produce at a lower cost.
• Crowding out – if overseas firms borrow in the domestic economy this may reduce access to funds and increase interest rates.
• Influence and political pressure – multinational investment can be very important to a country and this will often give them a disproportionate influence over government and other organizations in the host country. Given their economic importance, governments will often agree to changes that may not be beneficial for the long-term welfare of their people.
• Transfer pricing – multinationals will always aim to reduce their tax liability to a minimum. One way of doing this is through transfer pricing. The aim of this is to reduce their tax liability in countries with high tax rates and increase them in the countries with low tax rates. They can do this by transferring components and part-finished goods between their operations in different countries at differing prices. Where the tax liability is high, they transfer the goods at a relatively high price to make the costs appear higher. This is then recouped in the lower tax country by transferring the goods at a relatively lower price. This will reduce their overall tax bill.
• Low-skilled employment – the jobs created in the local environment may be low-skilled with the multinational employing expatriate workers for the more senior and skilled roles.
• Health and safety – multinationals have been accused of cutting corners on health and safety in countries where regulation and laws are not as rigorous.
• Export of Profits – large multinational are likely to repatriate profits back to their ‘home country’, leaving little financial benefits for the host country.
• Cultural and social impact – large numbers of foreign businesses can dilute local customs and traditional cultures.

7) What are the objectives of WTO?
Important objectives of WTO are mentioned below:
(i) To implement the new world trade system as visualized in the Agreement;
(ii) To promote World Trade in a manner that benefits every country;
(iii) To ensure that developing countries secure a better balance in the sharing of the advantages resulting from the expansion of international trade corresponding to their developmental needs;
(iv)To demolish all hurdles to an open world trading system and usher in international economic renaissance because the world trade is an effective instrument to foster economic growth;
(v) To enhance competitiveness among all trading partners so as to benefit consumers and help in global integration;
(vi) To increase the level of production and productivity with a view to ensuring level of employment in the world;
(vii) To expand and utilize world resources to the best;
(viii) To improve the level of living for the global population and speed up economic development of the member nations.

8) Short notes:
a) Features of a market economy:
In market economy, the economic decisions are made by individuals. In this, all the productive activities are privately owned as opposed to being owned by state. The interaction of individuals and companies in market place determines how resources are allocated and goods are distributed. Individual choose how to invest their personal resources, what to pursue, what jobs to take, what goods or services to produce and what to consume.
Goods and services that country produces are not planned by anyone. Production is determined by interaction of demand and supply through price system. If demand and exceed supply, price will rise signaling to produce less, so supply must not be restricted.
Example of market economic consists of USA. Private ownership are encouraged for competition and efficiency.
Its main features are:
I) private property
II) freedom of choice and enterprise
III) self interest as the dominating motive
IV) Competition
V) a reliance on the price system
VI) a very little role for government ( negligible role for government )

b) Exchange rate system:
Broadly, exchange rate systems fall into two categories, fixed systems and floating systems. As the name suggests, in a fixed system, the currencies involved are not allowed to appreciate or depreciate against each other. If a currency is floating, then it ‘floats’ around taking any level it wants; its value is determined in the foreign exchange markets.
Few exchange rate systems are totally fixed. The eleven countries that are currently involved in the single currency are, in a sense, part of a totally fixed exchange rate system. Their currencies were totally fixed as of 1st January 1999. But one could argue that they are not part of a fixed exchange rate system any more; they have become one and share a single currency.
Fixed exchange rate systems of the past have tended to be ‘fixed but adjustable’. This meant that the participants fixed their currency at some central rate, but were allowed to move it up and down within quite tight bands, say, +1%. These systems tended to allow for ‘realignments’ as well. If one of the countries kept recording current account deficits, meaning that their exchange rate within the fixed system was obviously wrong (too high), the currency would be allowed to devalue to a new fixed parity. Obviously these ‘realignments’ were not regular occurrences. If currencies were realigning every five minutes it wouldn’t really be a fixed exchange rate system anymore.
This was the system set up after the Second World War to promote stability and help the countries in the world that had persistent trade imbalances. The International Monetary Fund (IMF) was set up to oversee the system. Every country chose its own initial exchange rate. This was done by choosing the number of units of their currency that they were prepared to exchange for an ounce of gold, valued at $35. This is why the dollar was the currency in which all other currencies were expressed.

.

SlC result 2070 out, एसएलसी नतिजा २०७०

Here is the slc result for the year 2070…. For regular click the first link… REGULAR_2070 FOr excempted list click the second one.. Slc

check your results here: http://slc.ppokharel.com.np/SLC%20Search.html

 

Follow fostersoftware #worldcup

यस विश्वकप फुटबल महाकुम्भको नेपाली समय अनुसारको तालिका प्राप्त गर्न हाम्रा अपडेट्सहरु हेर्नुहोस् साथै विश्वकप सम्बन्धि गरिने हरेक दिनको प्रेडिक्सन “भोट एन्ड विन ” मा सहभागी बन्न हाम्रो फेसबुक एप्स प्रयोग गर्नुहोस |
हामीलाई लाइक गर्न हाम्रो फेसबुक पेज तल छ :

https://www.facebook.com/FosterSoftware

र नेपाली समयसहितको तालिका डाउनलोड गर्न निम्न लिंक मा क्लिक गर्नुहोस !!! http://goo.gl/VOrvS6

#worldcup

SmartPhones

स्मार्टफोन
स्मार्टफोन सहजै बोकेर हिड्न सकिने फोन हो जसमा सामान्य फोनमा हुने सबै सुबिधा हुन्छन नै र थप सुबिधाको रुपमा कम्प्यूटरले गर्न सक्ने सबै काम गर्न सक्छ जस्तै इमेल पठाउन, फोटो खिच्न, भिडियो च्याट गर्न, आदि | फोटो खिच्न, सथिसंग बिनाझन्झट उसको अनुहार हेरी हेरी कुरा गर्ने मिल्ने भिडियो च्याट गर्न अब बिजुली कुर्न नपर्ने भयो आफ्नो स्मार्टफोनबाट थ्रीजी प्रयोग गरि सजिलै कुराकानी गर्न सकिने भयो | इमेल पठाउन, इन्टरनेट प्रयोग गर्न, गणीतिय कारोबार सरल बनाउन, आफ्ना इमेज तथा भिडियो सुरक्षित गर्न, उपलब्ध भिडियोलाई इन्टरनेटमा अपलोड गर्न, डाउनलोड गर्न सकिने भएकाले स्मार्टफोन सामान्य मोबाइल भन्दा फरक छ | सामान्य मोबाइलमा भएका सबै सुबिधा उपलब्ध हुदा हुदै नयाँ र परिस्कृत टच सुबिधा, वाईफाई र आफ्नो काम सरल बनाउन फोन उत्पादकभन्दा बाहिरका तेश्रो पक्षले बनाएका एप्स प्रयोगगर्न पाइने सुबिधाले स्मार्टफोनलाई छोटो समयमै चर्चाको सिखरमा पुर्यायो |
स्मार्टफोन बजार प्रबेश गर्नभन्दा पहिले बजारमा एकमुस्ट प्रभुत्त जमाएका पर्सनल डीजीटल असिस्टेन्ट (पीडीए) जस्ता क्यामरा भएका, संगीत सुन्न र राख्न मिल्ने, आफ्नो लोकेसन पत्ता लगाउने डिभाइस ग्लोबल पोजिसनइंग सिस्टम (जीपीस ) जडित पाल्म कम्प्यूटरहरु बिकाश भए |

स्मार्ट फोनको बिकाशक्रम:
पर्सनल डीजीटल असिस्टेन्ट (पीडीए) जस्ता डीजीटल डिभाइसमा भएका कमजोरीको सुधारनै अहिलेका बहुसुबिधा युक्त स्मार्टफोनको जन्ममा प्रमुख हिस्सा राक्छन् | १९८० को  दशकमै टेलिफोनी र कम्प्युटिंग मिस्रित हार्डवेयरको अबधारणा आएपनि पुर्णरुपमा बिक्रियोग्य बन्न १९९३ सम्म कुर्नु पर्यो |  सन् १९९७ मा एर्रिक्सन कम्पनीले  जी८८ “पेनेलोप” सार्बजनिक गर्यो जुन अधिकारिक रुपमा स्मार्टफोन नामको पहिलो परिचय थियो |
१९९२ मा पहिलोपटक अमेरिकी कम्पनी आईबिएमले पर्सनल डीजीटल असिस्टेन्ट (पीडीए)मा उपलब्ध सुबिधा सहितको फोन प्रोटोटाइप कोमडेक्स सार्बजनिक गर्यो | सन् १९९४ मा बेलसाउथ नामक कम्पनीले साइमन पर्सनल कम्म्युनीकेटर नाम दिदै प्रोटोटाइपको सफल उत्पादन गरिदियो | प्रबिधिको विकास संगै बेलसाउथले साइमनमा फोन, इमेल, फ्याक्स आदान प्रदान गर्ने सुबिधा थपिदियो | त्यति मात्रै नभई यसमा छोएरमात्रै पनि चल्ने टच स्क्रिनको प्रयोग गरिएको थियो | आधिकारिक रुपमा भने पहिलो स्मार्टफोन साईमननै बन्न पुग्यो |

सन् १९९६ मा फिनल्याण्ड मोबाइल जाइन्ट नोकियाले नोकिया ९००० सार्बजनीक गर्यो | त्यसताका नोकिया ९००० अत्याधिक सफल बन्यो | झट्ट हेर्दा हत्केलामा राख्न मिल्ने सानो कम्प्यूटरझैँ देखिने ९००० सबैको रोजाई बन्यो | स्क्रिन र फोनको पछिल्लो भागगरि दुईभाग मा विभाजित ९००० बजारमा उपलब्ध तत्कालिन ग्याजेटले छोटो समयमानै अनपेक्षित बिक्रि रेकर्ड राख्यो | सानो कब्जाले जोडिएको नोकिया ९००० लाई खोल्दा भित्रपट्टी स्क्रिन र अर्कापट्टि कम्प्यूटरजस्तै किबोर्ड उपलब्ध थियो | जीओएस भी ३.० अपरेटिंग सिस्टम  उपलब्ध ९०००मा इमेल र टेक्स्ट वेब ब्राउजिंग सुबिधा थियो | सन् २०००मा एर्रिक्सनले स्मार्टफोनकै नाममा बजार भित्र्याएको एर्रिक्सन आर३८० ले टचस्क्रिन र सिमित इन्टरनेट सुबिधाको सुरुवात गर्यो |
सन् १९९९मा जापानी कम्पनी एनटिटि डोकोमोले सिएचटिएमएल सहितक फोन  सार्बजनिक गर्यो जसले डाटा  ९.६ किलोबिट प्रति सेकन्ड स्पीड पठाउन सक्थ्यो | एनटिटि डोकोमोले २००१को अन्त्यमा ४ करोड प्रयोगकर्ता बनायो

सन् २००० को मध्यतिर माइक्रोसफ्टको विन्डोज मोबाइलले ठुला ब्यापारिक घरानामाझ प्रभुत्त जमायो | विन्डोज मोबाइलको गति तब सुस्तियो जब ब्ल्याकबेरीले २००३मा बहुचर्चित जीएसएम मोबाइलहरु ब्ल्याकबेरी ६२१०, ब्ल्याकबेरी ६२२०, ब्ल्याकबेरी ६२३० सार्बजनिक गर्यो | कलर स्क्रिन युक्त ब्ल्याकबेरी ७७३० सर्बजबिक भएसंगै ब्ल्याकबेरीको उचाई बढेर गयो | सन् २००६मा क्रयाकबेरी नामले उत्तर अमेरिकाको बजारमा विन्डो मोबाइलको अस्तित्व संकटोपन्न बनाईदियो | यूरोपमा ब्ल्याकबेरीले भने खासै प्रत्सिपर्धा बेहोर्नु परेन | ब्ल्याकबेरीको इमेल सुबिधा, फ्याक्स, सरल कल बिधिले चाडैनै बजारमा स्थान सुरक्षित बनायो |

सन २००८ मा ब्ल्याकबेरीको बजारमाथि फिनल्याण्ड मोबाइल जाइन्ट नोकियाको सिम्बिएनले अंकुस लगायो | यूरोपमा नोकिया एक नम्बर मोबाइल उत्पादक बन्यो | नोकियाले मोबाइलको प्रयोग ब्यापारिक प्रयोजनभन्दा बाहिर लैजान नसकेका उत्पादकभन्दा भिन्न मनोरंजन प्रयोजनमा सुरुवात गर्यो | एन सेरिजको सुरुवात संगै फोन उत्पादकहरुमा नोकिया एक नम्बर बन्न पुग्यो | सुरुवातका वर्षहरुमा ब्यापारिक प्रयोजनलाई उत्पादन लक्षित गरेको नोकिया सिम्बिएनले बजारलाई फराकिलो बनाउदै युवापुस्तामा उत्पादन पुर्यायो | यसरीनै परिबर्तित बजार ब्यबस्थापन गर्न नसकेर बजारबाट ओझेल परेका विन्डोज र ब्ल्याकबेरीको कमजोरीले नोकिया स्मार्टफोन उत्पादनमा बिस्वकै अग्लो उचाईमा पुग्यो | यसरीनै पाल्म ओएस उदायो र अस्तायो |

“चुचुरोमा पुग्न सजिलो छ तर टिकीरहन मुस्किल छ ” भन्ने भनाई यहाँ पनि साचो भएर निस्कियो सन् २००७ मा सार्बजनिक मल्टीटच स्क्रिनयुक्त एप्पल इन्कले आईफोन सार्बजनिक भयो | फराकिलो टचस्क्रिन भएको आईफोनले सार्बजनिक भएसंगै स्थापित मोबाइल उत्पादकलाई पछाडी पारिदियो | सन् २००७ मा टुजी सार्बजनिक गरेको एप्पलेले २००८ मा थ्रीजी, २००९ मा थ्रीजी एस, २०१० मा फोरजी, २०११ मा फोरजी एस, २०१२ मा फाईव, २०१३ मा फाईव एस र फाईव सि सार्बजनिक गर्यो | गूगलले २००८ मा ओपनसोर्स अपरेटिंग सिस्टम एन्ड्रोईड सार्बजनिक गर्यो | २००८ मा एचटिसी ड्रिममार्फत पहिलो एन्ड्रोईड फोन सार्बजनिक भयो | एन्ड्रोईडको सर्बजनिकिकरणले स्मार्टफोन बजारलाई कायापलट गरिदियो | एन्ड्रोईडको अपरेटिंग सिस्टमले मोबाइल उत्पादन प्रभुत्त ठुला तथा धनि रास्ट्रको नियन्त्रणबाट मुक्त भयो | एन्ड्रोईडको सहज उपलब्धता र आफूअनुकुल परिबर्तन गर्न सकिने सुविधाले भारत र चिन जस्ता उदयीमान बजारलाई सबैभन्दा बढी फाइदा हुन पुग्यो | बिशाल हार्डवेयर उत्पादक चिन र सफ्टवेयर उत्पादक भारतले यसको प्रयोगमा कुनै कसर बाकी राखेनन् |

माइक्रोसफ्टले बदलिदो बजारमा सुरक्षित रहन विन्डोज फोन सार्बजनिक गर्यो, नोकियाको सिम्बिएनले आफ्नो उत्पादन र सपोर्ट बन्द गर्यो र माइक्रोसफ्टसंग बिक्रि सम्झौतामा हस्ताक्षर गर्यो | माइक्रोसफ्ट अहिले नोकियाको हार्डवेयर प्रयोगगर्दै लुमिया सेरिज़को उत्पादनमा जुटेको छ | अहिले पनि लुमिया सेरिज़का ५ भन्दा बढी विन्डोज फोन उपलब्ध छन् | यति मात्रै नभई नोकियाले एन्ड्रोईड अपरेटिंग सिस्टमका फोन पनि सार्बजनिक गरेको छ | माइक्रोसफ्टले आफ्नो बजार दह्रिलो बनाउन आफ्नो विन्डोज फोन अपरेटिंग सिस्टम तेश्रो पक्षलाई प्रयोग गर्न दिने सम्झौता गर्यो | भारतको मोबाइल उत्पादक माइक्रोम्याक्स पहिलो सम्झौता गर्ने कम्पनी बन्न पुग्यो |
अहिले सामसङ, एचटिसी, सोनी, कलर्स, माइक्रोम्याक्स आदि मोबाइल उत्पादक एन्ड्रोईडमै निर्भर रहेका छन् | बजारमा उपलब्ध अन्य अपरेटिंग सिस्टमहरु जोल्ला, बाडा, मोजिल्लाको फायरफक्स ओएस, सेलफिश ओएस, टाईजेन, यूबन्टु टच, आदि छन् |

बिकाश क्रममा के के देखिए ?
१.० इनोभेसन
बजारमा उपलब्ध मोबाइलहरुभन्दा नयाँ र परिस्कृत फिचर्स दिनु अहिलेको बदलिदो स्मार्टफोन ट्रेन्ड हो | नयाँ स्मार्टफोन सार्बजनिक हुदाँ नयाँ फिचर्स के के थपिए भन्ने खोजि हुन्छ | सार्बजनिक हुन पहिले विभिन्न अड्कल बाजी गरिन्छ | साना कम्पनी भन्दा ठुला उत्पादकसंग प्रयोगकर्ताको ठुलो अपेक्षा हुनेगर्छ | बिसेष गरि एप्पल, सामसङ, माइक्रोसफ्ट, नोकिया जस्ता ठुला कहलिएका उत्पादकसंग ठुलो अपेक्षा हुने गर्छ |

२.० फराकिलो र एक्टिभ टच स्क्रिन:
ल्यापटपलाई नै चुनौती दिन थालिसकेको स्मार्टफोनमा प्रयोगकर्ताको प्रयोग अब सामान्य फोन मात्रै सिमित छैन | कम्प्यूटरले गरिने आफ्ना सबै काम स्मार्टफोन बाट सम्भब भएपछि तिनीहरुको प्रयोग पनि छरितो र सहज हुन आवस्यक छ | त्यही समस्यालाई मध्यनजर गरि बजारमा भित्रिने नयाँ स्मार्टफोनहरु उत्पादकहरुले फराकिला स्क्रिन र चलाख टच भएका डिभाइस सार्बजनिक गर्न चाहन्छन् | राम्रो क्वालिटिको भिडियो हेर्नपनि फराकिलो स्क्रिन लाभदायक हुन्छ |
३.० ब्याट्री लाइफ :
फराकिलो स्क्रिन डिस्प्ले मागे संगै ठुलो डिस्प्लेमा लाग्ने धेरै ब्याट्री खर्च अर्को स्मार्टफोनमा सबैभन्दा धेरै अपेक्षा गरिन्छ | ब्याट्री लाइफ बढाउन कम्पनीले धेरै शक्तिशाली ब्याट्री प्रयोग गर्दै आएका छन् | पहिने १३०० एमएच ब्याट्री हुने गरेका सामान्य फोनहरुभन्दा अहिलेका स्मार्टफोन करिब दोहोरो अथवा तिन गुणा शक्तिशाली छन् | धेरै ब्याट्री आयु भएका फोनहरुनै अहिलेको बजारको रोजाईमा पर्छन |
४.० शक्तिशाली र्याम र धेरै स्टोरेज :
युवा पुस्ताहरुमा  मोबाइलमा खेलिने खेल पनि लोकप्रिय छ | धेरै रेजोलुसन भएको गेम खेल्न धेरै र्याम अत्यावश्यक हुन्छ | हाल बजारमा उपलब्ध स्मार्टफोन क्वाड कोर प्रोसेसर सम्मका उत्पादन भइसकेका छन् र हुदै पनि छन् | येसरी हेर्ने हो भने यि स्मार्टफोनहरु सामान्य कम्प्यूटरभन्दा शक्तिशाली हुन्छन | स्मार्टफोन उत्पादक प्रयोगकर्ताको चाहना अनुरुप धेरै र्याम र धेरै स्टोरेजमा प्रतिस्पर्धा गर्दैछन् | हाल बजारमा १२८ जीबी सम्मका मेमोरी कार्ड उपलब्ध भैसकेका छन् |

५.० एप्स स्टोर को अबधारणा:
बजारमा चल्तीका स्मार्ट फोन उत्पादकहरु आफ्ना ग्राहकलाई झन्झट रहित सुबिधा उपलब्ध गराउने उदेश्यले विभिन्न सेवा तथा सुबिधा दिदै आईरहेका छन् | एप्स स्टोरको स्थापना सामान्य बनिसकेको अहिलेको स्मार्टफोन बजार नयाँ र चल्तीका एप्स ग्राहकलाई कसले चाडो र सस्तो मुल्यमा पुर्याउने भन्नेमा केन्द्रित छ | सन् २००० मा स्थापित डेन्जर इन्क नामक कम्पनीले टि-मोबाइल साइडकिक (डेन्जर हिपटप ) सार्बजनिक गर्यो | बजार प्रवेशको अनौठो तरिका अपनाएको डेन्जर २ बर्ष भित्रै माइक्रोसफ्ट को रोजाई मा पर्यो र सन् २००२ मा अघोसित रुपमा १० लाख डलर भन्दा बढीमा बिक्रि भयो | हाल डेन्जरको एप्स स्टोर संचालनमा छैन | त्यहि ट्रेन्ड पछ्याउने अन्य मोबाइल उत्पादकले पनि धमाधम आफ्ना स्टोर संचालनमा ल्याए |

६.० मोबाइल अपरेटरसंगको बन्डिंग:
आफ्ना उत्पादनहरुलाई बजारका सबैखाले प्रयोगकर्तासमक्ष पुर्याउन मोबाइल अपरेटरसंगको बन्डिंग अत्यन्त फाइदाजनक साबित भएको छ | बन्डिंगमा प्रयोगकर्तालाई स्मार्टफोन उपलब्ध गराउने अपरेटरको सिम मात्रै चल्ने गरि मोबाइल लक गरिएर दिएको हुन्छ जसबापत प्रयोगकर्ताले मासिक वा बार्षिक सिमित रकम तिर्न पर्छ| सर्त अनुसार बक्यौता तिरी नसकी अर्को मोबाइल अपरेटरको सेवापनि लिन नपाइन सक्छ | पुरा रकम भुक्तानी नभएसम्म मोबाइलको सेवा तथा मोबाइल आफै पनि जुनसुकै बेला लक हुनसक्छ र अनलक गर्न बक्यौता रकम भुक्तानी गर्न पर्छ | बन्डिंगमा टि-मोबाइल, एटि एंड टि, भोड़ाफोन, भर्जिन मोबाइल अग्रणी नाम हुन् |