Wednesday, February 19, 2020

Plugins

Nuget - Microsoft.CrmSdk.CoreAssemblies (9.0.2.22)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ServiceModel;
using Microsoft.Xrm.Sdk;

namespace MS.DEV.Plugins
{
    public class CreateAccountTask : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                Entity entity = (Entity)context.InputParameters["Target"];

                try
                {
                    Entity followup = new Entity("task");
                    followup["subject"] = "Send e-mail to the new customer.";
                    followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
                    followup["scheduledstart"] = DateTime.Now;
                    followup["scheduledend"] = DateTime.Now.AddDays(2);
                    followup["category"] = context.PrimaryEntityName;

                    if (context.OutputParameters.Contains("id"))
                    {
                        Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
                        string regardingobjectidType = "account";
                        followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
                    }

                    // Create the followup activity
                    service.Create(followup);
                }

                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in Plugin.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }

            }
        }
    }
}

---------------------

Update

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;

namespace MS.DEV.Plugins
{
    public class UpdateAccountEmail : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                Entity entity = (Entity)context.InputParameters["Target"];

                try
                {

                    Entity fromActivityParty = new Entity("activityparty");
                    Entity toActivityParty = new Entity("activityparty");

                    Guid accoundId = entity.Id;
                    Guid userId = context.UserId;

                    fromActivityParty["partyid"] = new EntityReference("systemuser", userId);
                    toActivityParty["partyid"] = new EntityReference("account", accoundId);



                    Entity Email = new Entity("email");
                    Email["from"] = new Entity[] { fromActivityParty };
                    Email["to"] = new Entity[] { toActivityParty };

                    Email["subject"] = "New Escalations ";
                    Email["description"] = "You got escalted !!";
                    Email["directioncode"] = true;


                    Email["regardingobjectid"] = new EntityReference("account", accoundId);


                    // Create the followup activity
                    Guid EmailId = service.Create(Email);

                    SendEmailRequest sendEmailRequest = new SendEmailRequest
                    {
                        EmailId = EmailId,
                        TrackingToken = Convert.ToString(new Random().Next(0, 999999)),
                        IssueSend = true
                    };

                    SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailRequest);

                }

                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in Plugin.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }

            }
        }
    }
}

Friday, August 29, 2014

Windows Communication Foundation

What Is Windows Communication Foundation?
The global acceptance of Web services, which includes standard protocols for application-to-application communication, has changed software development. For example, the functions that Web services now provide include security, distributed transaction coordination, and reliable communication. The benefits of the changes in Web services should be reflected in the tools and technologies that developers use. Windows Communication Foundation (WCF) is designed to offer a manageable approach to distributed computing, broad interoperability, and direct support for service orientation.

WCF simplifies development of connected applications through a new service-oriented programming model. WCF supports many styles of distributed application development by providing a layered architecture. At its base, the WCF channel architecture provides asynchronous, untyped message-passing primitives. Built on top of this base are protocol facilities for secure, reliable, transacted data exchange and broad choice of transport and encoding options.

The typed programming model (called the service model) is designed to ease the development of distributed applications and to provide developers with expertise in ASP.NET Web services, .NET Framework remoting, and Enterprise Services, and who are coming to WCF with a familiar development experience. The service model features a straightforward mapping of Web services concepts to those of the .NET Framework common language runtime (CLR), including flexible and extensible mapping of messages to service implementations in languages such as Visual C# or Visual Basic. It includes serialization facilities that enable loose coupling and versioning, and it provides integration and interoperability with existing .NET Framework distributed systems technologies such as Message Queuing (MSMQ), COM+, ASP.NET Web services, Web Services Enhancements (WSE), and a number of other functions.

Problem Example

The following example illustrates some of the problems that WCF addresses. A car rental company decides to create a new application for reserving cars. The creators of this rental car reservation application know that the business logic it implements must be accessible by other software running both inside and outside their company. Accordingly, they decide to build it in a service-oriented style, with the application’s logic exposed to other software through a well-defined set of services. To implement these services, and thus communicate with other software, the new application will use WCF.

Over its lifetime, the rental car reservation application will likely be accessed by a range of other applications. When it is designed, however, the architects of the rental car reservation application know that its business logic will be accessed, as shown in the preceding figure, by three other kinds of software:

A call center client application running on the Windows desktops that are used by employees in the organization’s call center. Created specifically for the new reservations system, this application will also be built using the Microsoft .NET Framework and WCF. This application is not truly distinct from the new rental car reservation application, because its only purpose is to act as a client for the new system. From a service-oriented perspective, it is just another client for the reservation system’s business logic.
An existing reservation application built on a J2EE server running on a non-Windows system. Due to a recent merger with another car rental firm, this existing system must be able to access the new application’s logic to provide customers of the merged firms with a unified experience.
Partner applications running on a variety of platforms, each located within a company that has a business arrangement with the car rental firm. Partners might include travel agencies, airlines, and others that have a business requirement to make car rental reservations.
The diverse communication requirements for the new rental car reservation application are not simple. For interactions with the call center client application, for instance, performance is important, while interoperability is straightforward, because both are built on the .NET Framework. For communication with the existing J2EE-based reservation application and with the diverse partner applications, however, interoperability becomes the highest goal. The security requirements are also quite different, varying across local Windows-based applications, a J2EE-based application running on another operating system, and a variety of partner applications coming in across the Internet. Even transactional requirements might vary, with only the internal applications being allowed to make transactional requests. How can these diverse business and technical requirements be met without exposing the creators of the new application to unmanageable complexity?

WCF is designed for this diverse but realistic scenario and is the default technology for Windows applications that expose and access services. This topic provides an introduction to WCF, examining what it provides and showing how it is used. Throughout this introduction, the scenario just described will serve as an example. The goal is to make clear what WCF is, show what problems it solves, and illustrate how it solves those problems.

Addressing the Problem

The foundation for new Windows-based applications is the .NET Framework. Accordingly, WCF is implemented primarily as a set of classes on top of the .NET Framework CLR. Because it extends their familiar environment, WCF enables developers who create object-oriented applications using the .NET Framework today to also build service-oriented applications in a familiar way.



The figure shows a view of a WCF client and service. The two interact using SOAP, the WCF native message representation, so even though the figure shows both parties built on WCF, this is not required. WCF is built on .NET Framework 2.0.

As the scenario described earlier suggests, WCF addresses a range of challenges for communicating applications. Three things stand out, however, as the most important aspects of WCF:

Unification of existing .NET Framework communication technologies.

Support for cross-vendor interoperability, including reliability, security, and transactions.
Explicit service orientation.
Unification of Microsoft Distributed Computing Technologies
In the absence of WCF, the development team that implements the rental car application would need to choose the right distributed technology from the multiple choices offered by the .NET Framework. Yet given the diverse requirements of this application, no single technology would fit the requirements. Instead, the application would probably use multiple existing .NET Framework technologies, such as the following:

ASP.NET Web services (ASMX). An option for communicating with the J2EE-based existing reservation application and with the partner applications across the Internet. Given that basic Web services are supported today on most platforms, this was the most direct way to achieve cross-vendor interoperability before the release of WCF.
.NET Framework remoting. An option for communication with the call center application, because both are built on the .NET Framework. Remoting is designed expressly for tightly coupled .NET-to-.NET communication, so it offers a seamless and straightforward development experience for applications in the local network.
Enterprise Services. Used by the rental car reservation application for managing object lifetimes and defining distributed transactions. These functions could be useful in communicating and integrating with any of the other applications in this scenario, but Enterprise Services supports only a limited set of communication options.
WSE. Could be used along with ASMX to communicate with the J2EE-based reservation application and with the partner applications. Because it implements more recently defined Web services agreements, known collectively as the WS-* specifications, WSE allows for more flexible Web services security, as long as all applications involved support compatible versions of these new specifications.
Microsoft Message Queuing (MSMQ). Used to communicate with Windows-based partner applications that require guaranteed data delivery as well as decoupling of workloads and application lifetimes. The durable messaging that Message Queuing provides is typically the best solution for intermittently connected applications.
Built on .NET Framework, the rental car reservation application must use more than one of these communication technologies to meet its requirements. Although this is technically possible, the resulting application would be complex to implement and challenging to maintain.

With WCF, the solution is much easier to implement. As the figure shows, WCF can be used for all the situations previously described. Accordingly, the rental car reservation application can use this single technology for all of its application-to-application communication. The following shows how WCF addresses each of these requirements:

Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.
You can also configure and extend WCF to communicate with Web services using messages not based on SOAP, for example, simple XML formats like RSS.
Performance is of paramount concern for most businesses. WCF is developed with the goal of being one of the fastest distributed application platform developed by Microsoft. For a high-level performance comparison between WCF and other Microsoft .NET distributed communication technologies, see http://go.microsoft.com/fwlink/?LinkId=94274.
To allow optimal performance when both parties in a communication are built on WCF, the wire encoding used in this case is an optimized binary version of an XML Information Set. Messages still conform to the data structure of a SOAP message, but their encoding uses a binary representation of that data structure rather than the standard angle-brackets-and-text format of the XML 1.0 text encoding. Using this option makes sense for communicating with the call center client application, because it is also built on WCF, and performance is an important concern.
Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise Services are now provided by WCF. They are available to any WCF-based application, which means that the rental car reservation application can use them with any of the other applications it communicates with.
Because it supports a large set of the WS-* specifications, WCF helps provide reliability, security, and transactions when communicating with any platform that also supports these specifications.
The WCF option for queued messaging, built on Message Queuing, allows applications to use persistent queuing without using another set of application programming interfaces.
The result of this unification is greater functionality and significantly reduced complexity.

Interoperability with Applications Built on Other Technologies

While WCF introduces a new development environment for distributed applications, it is designed to interoperate well with the non-WCF applications. There are two important aspects to WCF interoperability: interoperability with other platforms, and interoperability with the Microsoft technologies that preceded WCF. The following section describes both.

Interoperability with Other Web Services Platforms
Enterprises today typically have systems and applications that they purchased from a range of suppliers. In the rental car application, for instance, communication is required with various other software applications written in various languages and running on various operating systems.

Because WCF’s fundamental communication mechanism is SOAP-based Web services, WCF-based applications can communicate with other software running in a variety of contexts. An application built on WCF can interact with all of the following:

WCF-based applications running in a different process on the same Windows machine.
WCF-based applications running on another Windows machine.
Applications built on other technologies, such as J2EE application servers, that support standard Web services. These applications can be running on Windows machines or on machines running other operating systems.
To allow more than just basic communication, WCF implements Web services technologies defined by the WS-* specifications. All of these specifications were originally defined by Microsoft, IBM, and other vendors working together. As the specifications become stable, ownership often passes to standards bodies, such as the World Wide Web Consortium (W3C) or the Organization for the Advancement of Structured Information Standards (OASIS). These specifications address several areas, including basic messaging, security, reliability, transactions, and working with a service’s metadata. For more information, see Interoperability and Integration. For more information about advanced Web services specifications, see http://go.microsoft.com/fwlink/?LinkId=86603.

Grouped by function, those specifications cover:

Messaging: SOAP is the foundation for Web services and defines a basic envelope that contains header and a body sections. WS-Addressing defines additions to the SOAP header for addressing SOAP messages, which frees SOAP from relying on the underlying transport protocol, such as HTTP, to carry addressing information. Message Transmission Optimization Mechanism (MTOM) defines an optimized transmission format for SOAP messages with large binary data contents based on the XML-binary Optimized Packaging (XOP) specification.
Metadata: The Web Services Description Language (WSDL) defines a standard language for specifying services and various aspects of how those services can be used. WS-Policy allows specification of more dynamic aspects of a service’s behavior that cannot be expressed in WSDL, such as a preferred security option. WS-MetadataExchange allows a client to directly request descriptive information about a service, such as its WSDL and its policies, using SOAP.
Security: WS-Security, WS-SecureConversation, WS-Trust, and WS-Federation all define additions to SOAP messages for providing authentication, data integrity, data privacy, and other security features.
Reliability: WS-Reliable Messaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more Web services intermediaries must be traversed.
Transactions: Built on WS-Coordination, WS-Atomic Transaction allows coordinating two-phase commit transactions in the context of Web services conversations.
The rental car reservation application would likely use several of these more advanced technologies. For example, WS-Addressing is essential whenever SOAP is used over a transport mechanism other than HTTP, which might be the case for communication with the .NET Framework-based call center client application. WCF relies on WS-Policy and WS-Metadata Exchange to discover whether the system it is communicating with is also using WCF and for other things. Reliable communication is essential for most situations, so it is likely that WS-Reliable Messaging would be used to interact with many of the other applications in this scenario. Similarly, you might also use WS-Security and the related specifications for securing the communication with one or more of the applications, because all would require some kind of protection against unauthorized access or message modification and interception. For the applications that require transaction integration with the rental car reservation system, WS-Atomic Transaction would be essential. Finally, MTOM could be used whenever an optimized wire format for binary data is necessary (for instance for pictures of fleet examples), and both sides of the communication supported this option.

The key point is that WCF implements interoperable Web services complete with cross-platform security, reliability, transactions, and other services. To provide maximum throughput, WCF-to-WCF communication can be significantly optimized, but all other communication uses standard Web services protocols. In fact, it is possible for a single application to expose its services to both kinds of clients.

Interoperability with Microsoft Technologies
Many Microsoft customers have made significant investments in the .NET Framework technologies that WCF includes. Protecting those investments was a fundamental goal of WCF’s designers. Installing WCF does not break existing technology, so there is no requirement that organizations change existing applications to use it. A clear upgrade path is provided, however, and wherever possible, WCF interoperates with those earlier technologies.

For example, both WCF and ASMX use SOAP, so WCF-based applications can directly interoperate with those built on ASMX. Existing Enterprise Services applications can also be wrapped with WCF interfaces, allowing them to interoperate with applications built on WCF. And because persistent queuing in WCF relies on MSMQ, WCF-based applications can interoperate directly with non-WCF-based applications built using native MSMQ interfaces. In the rental car reservations application, software built using any of these earlier technologies could directly connect to and use the new system’s WCF-based services.

Interoperability is not always possible, however. For example, even though WSE 1.0 and WSE 2.0 implement some of the same WS-* specifications as WCF, these earlier technologies implement earlier versions of the specifications. Version 3.0 of WSE does allow interoperability with WCF, but earlier versions do not. For more information about interoperability, see Migrating WSE 3.0 Web Services to WCF.

Interoperability with Other XML Protocols

The future of the Internet is not predictable and the technologies used today may evolve or be replaced. Today, a popular trend in building Web-centric applications (called by many "Web 2.0"), is an application model based on communication using only simple XML formats that are not SOAP-based and exclusively rely on HTTP as a transport and as an application protocol. For example, the Representational State Transfer (REST) architectural style has no notion of user-defined operations for dealing with data. Instead, application state is associated with HTTP URLs and HTTP methods (such as PUT, POST, DELETE, and GET). This approach is in contrast to the creation of user-defined procedures or functions that most developers are familiar with in an enterprise environment. However, the REST approach is of value in scenarios where services must function as the back end of Web 2.0 applications.

REST is just one example of an evolving Web 2.0 technology. In this environment of experimental programming models and ongoing reinterpretation and refinement of standards, flexibility is required to cope with unforeseeable changes. WCF is flexible. For example, while WCF uses SOAP as an underlying structure, it is not bound to using SOAP for wire communication. In fact, WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON). This flexibility ensures that code written today will be valid in the future, even if protocols change or are replaced. Therefore, WCF was designed for the present and the future.

Know about Assemblies

Introduction to assemblies

The assembly is an important element of .NET programming. On the .NET platform, an assembly is a unit of reuse, versioning, security and deployment. In order to package and deploy our types, they must be placed into modules that are part of an assembly. Every managed application in .NET is deployed as an assembly. It means that the entire .NET code on compilation gets converted into an Intermediate Language (IL) code and gets stored as an assembly. In addition to the IL code, an assembly also contains Assembly metadata (Manifest), Type metadata and Resources. Assemblies are hence self-describing. Let us peep into the structure of an assembly.

Structure of an assembly

If an assembly is to be made up of several programs, the programs can be stored in separate modules. Suppose there are two source files ‘a.cs’ and ‘b.cs’ of which, ‘a.cs’ is stored in a module, whereas, ‘b.cs’ is stored in the assembly itself. Both comprise an assembly named ‘mydll.dll’. The structure of the assembly ‘mydll.dll’ would look as shown in the following figure.

The PE file ‘a.dll’ is said to be stored in a module of the ‘mydll.dll’ assembly. Had ‘mydll.dll’ contained resources, they would also get added in the structure with the type metadata and manifest. The ‘assembly description’ shown in manifest contains the identity of the assembly, consisting of its name, version and culture. An assembly has a four part version number e.g. 1.0.1.1. The parts are . . . . Other contents are the names of all the files in the assembly, information regarding whether all the types defined in the assembly are visible to other assemblies or private to one, a hash of all files in the assembly and details of any security permissions that clients need to have in order to be able to run the assembly.

Private and shared assemblies
 

We can create two types of assemblies—private assemblies and shared assemblies. A private assembly is used by only one application while a shared assembly is shared amongst different applications.

By default, when a C# program is compiled, the assembly produced will be a private assembly. This assembly (DLL/EXE) should be placed in the same folder as the calling application. With a private assembly it’s not necessary to think about naming conflicts with other classes or versioning problems because each application has its own copy of the assembly. In shared assemblies we have to ensure that the assembly is unique, and therefore, give it a unique name (called strong name).

In this article we would see how to build and use a shared assembly.

Let us write a class library consisting of a function called display( ). We will call this function from a client program, which we will create later. Here is code of the display( ) method, which is defined in the mytext class.

public class mytext
{
         public void display ( Form fr, string s, Color c, string fname,int size, Point pt )
       {
                 Graphics g = fr.CreateGraphics();
                  Font myfont = new Font(fname, size);
                  SolidBrush mybrush = new SolidBrush(c);
                  g.DrawString(s, myfont, mybrush, pt);
         }
}


The display() method simply draws text with the specified Font and Brush. On building the project a ‘fontassembly.dll’ file would get created in the ‘fontassembly\bin\Debug’ subfolder.

A shared assembly is always unique. To be uniquely identified, a shared assembly has a strong name. The combination of a file name, a public key, a version number and culture (locale details) gives an assembly a strong name, which is guaranteed to be unique. Now let’s first see what are public and private keys and then see how to build them.

Public keys, private keys and encryption


Encryption is the act of encoding files/programs so that others not privy to the decryption mechanism cannot understand the content of the text. Thus encryption is the process of hiding our data from anyone we feel should not be allowed to read it. Under the .NET platform this has special significance since here we distribute our IL code embedded in assemblies, instead of the executable machine code, which can potentially be deciphered without too much difficulty. .NET has a strong inbuilt mechanism to maintain the privacy of code. If this had not been the case, any one with the ILDASM.EXE utility would have an access to your code. Not only that, he or she would also have the opportunity to distribute it under his name. .NET achieves this security by public key encryption.

The public key and private keys are complementary entities; one is meaningless without the other. The creation of public and private keys is carried out by complicated mathematical algorithms. A document encrypted with one key can be decrypted only by using the other key. Not even the key with which the data was encrypted can be used to decrypt it back. The public key can be distributed freely without any fear of it being misused.

Building the keys


To build public and private keys we have to use the sn (short for strong name) utility. This utility generates a public/private key pair. The public key created using this utility will be used to define a strong name. To create the key pair we must type the following at command prompt:

C:\CSharp\fontassembly>sn –k mykey.snk
On executing the utility a file called mykey.snk gets created. This file contains the public and private keys.

To create a strong name, the compiler uses the public key from the mykey.snk file, hence we must provide this file to the compiler. To do so we would have to open the AssemblyInfo.cs file of the project. In this file we would have to set the AssemblyKeyFile attribute to the ‘.snk’ file path. The attribute must be either set to an absolute path to the key file or if the file is copied to the local directory of the project, only the file name must be mentioned. We need to add the following to the ‘AssemblyInfo.cs’ file.

[assembly: AssemblyKeyFile(“mykey.snk”)]
We should also change the version number of our assembly as shown below.

[assembly: AssemblyVersion(“1.0.1.1”)]
On rebuilding the program, the assembly would now use the public key from the mykey.snk file along with the name of the assembly, the version number and the culture to build a strong name. Culture is a combination of a two-letter word indicating the language and a two-letter word indicating the country code. The strong name never contains the private key. This ensures that the private key is not written in the manifest and hence is not made available to everybody. This strong name is written in the manifest of the assembly.

Along with the strong name, the compiler also generates a cryptographic hash from the names and contents of the files in the assembly. The compiler then encrypts the cryptographic hash for the assembly using the private key (available in mykey.snk). It places the encrypted hash in the manifest of the assembly. This hash would be used by the client to check the authenticity of the assembly.

So, in all, two things are written inside the manifest—the strong name and the encrypted hash of the names and contents of the files. The process of writing the encrypted hash value in the manifest is called ‘Signing of an assembly’. Now our shared assembly is ready. To make it available to all the clients we would have to install it in the Global Assembly Cache. All the shared assemblies available on a system are stored in the Global Assembly Cache. This store is located in the :\Windows\Assembly folder.

Installing the shared assembly


To install a shared assembly in the global cache we would have to use the Global Assembly Cache utility tool called gacutil along with the /i option. Here /i stands for install. This is what we must type at the command prompt to install the
assembly.

C:\CSharp\fontassembly\bin\Debug>gacutil /i fontassembly.dll
If the assembly is successfully installed, the following message would appear:

Assembly successfully added to the cache

Building the client
Let us now build a client that would use the assembly that we created above. To create the client select a ‘Windows Application’ project and name it as fontclient

When we click on the form, some text should be displayed at the position where we click. This can be achieved by calling the display( ) method from ‘fontassembly.dll’ in the Form1_MouseDown( ) handler. To have access to this method we have added a reference of the mytext class as a data member of the Form1 class. The Form1_MouseDown( ) handler is shown below.

private void myform_MouseDown ( object sender,
System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
Point pt = new Point ( e.X, e.Y ) ;
t.display ( this, “Hello”, Color.Red, “Comic Sans MS”, 30, pt );
}
}
Here we have first checked whether the left mouse button has been clicked. If so then we have called the display( ) method of the mytext class from the fontassembly assembly.

For the mytext class to become available we have added the statement using fontassembly ;. However this is not enough. We also need to add a reference to the library. To do this we should right click on ‘References’ in the Solution Explorer window and select ‘Add References’. On doing so the ‘Add References’ window would appear.

Execute the program and click on the form, a string “Hello” would appear at the point where mouse is clicked.


C# Assemblies
by Wrox Books


Features of Assembly

The assembly contains MSIL code (from the compilation of your code), resources, and the metadata (which is data that describes the assembly). The metadata defines the following, among other things:
Type information for the methods and public members in the assembly
The name of the assembly
Version information
Strong-name information
Culture that defines the client’s language and cultural preferences
A list of the files in the assembly
A list of referenced assemblies


The assembly is the file that is stored on the disk. As part of that file the metadata defines all the aspects of the assembly and the manifest is the part of the metadata that defines the assembly and its properties. The PE (Portable Executable) file contains metadata, as do all assemblies.Working with a .NET Assembly

The tool used to view the content of an assembly is the MSIL Disassembler (Microsoft Intermediate Language) and to examine any managed module, including any *.exe, *.dll, and *.netmodule. The syntax for running the MSIL Disassembler is as follows:

ildasm [options] filename [options]

To see a short version of the documentation for the ildasm utility use the /? option as in this example:


There are many types of files that are involved when building .NET assemblies:
Source code resides in files with the file extension .cs.
Managed modules are the compiled IL versions of the source code. The extension of the file that is built when making a module from source files is .net module.
Assemblies are either DLLs or .exe files containing managed modules, resources, and metadata.


Creating and Modifying a .NET Assembly

An assembly can be built using the tools supplied with Visual Studio .NET or with the language compilers (such as csc.exe) and linkers (such as al.exe) supplied with the .NET Framework. We will use the command-line tools in this chapter to build the assemblies.
When we build assemblies, they are built either as private or strongly named assemblies (strongly named assemblies are needed for shared deployment). The simplest assembly to build is the private assembly; all the files for the private assembly are deployed in the folder for the application. Private assemblies are not shared with other applications and are not added to the GAC.

The examples in will work with the following source files that will print "Hello World!" on the console for us:

Hello.cs

namespace HelloWorld
{>br>using System;
public class Hello
{
string StrHello = "Hello World!";
public Hello()
{
//empty constructor
}
public void SayHello()
{
Console.WriteLine (strHello)
}
}
}


The following is the welcome.cs source file:

welcome.cs
using system;
using Helloworld;
namespace Helloassembly
{
Public class welcome
{
Public Static Void Main()
{
Hello Welcome;
welcome = new Hello;
Welcome.SayHello();
}
}
}


Setting the /target: module compiler command-line switch will produce a module that can be used to create a multi-file assembly.
The following example builds the Hello.netmodule file:

csc /target:module Hello.cs

To reference another module to be included in the assembly use the /addmodule switch to make the type information available:

csc /addmodule:Hello.netmodule /t:module Welcome.cs
Once this command has been run, the Welcome.netmodule will be created. To finally link the modules together, you use the al.exe utility (the Assembly Linker), as in this example:
al Welcome.netmodule Hello.netmodule /main:WelcomeAssembly.Welcome.Main
/t:exe /out:Hello.exe

This command produces the Hello.exe output file from the two modules. The /main option tells the linker where to find the Main method for the application. Note that the options are case-sensitive.Strongly Named Assemblies and GAC

In order to be able to install an assembly in the GAC, it must be a strongly named assembly. The following steps are involved in creating a strongly named assembly:

1. Create a strong-name key file using the Strong Name tool (sn.exe) as in this example:
2. Add assembly attributes to one of the source files referencing the strong-name key file. The following example adds the AssemblyKeyFile and AssemblyVersion attributes to the Hello.cs source file.
3. Compile the library using the csc compiler. Use the /t:library switch to create a DLL, as in this command: csc /t:library Hello.cs
4. Install the module in the GAC using the gacutil.exe utility, as is shown here:

gacutil -i Hello.dll Microsoft (R) .NET Global Assembly Cache Utility. Version 1.0.3705.0
sn -k Hellokey.snk

using system.reflection;
[assembly: AssemblyKeyFile("WelcomeKey.snk")]
[assembly: AssemblyVersion("12.1.42.0")]
namespace Helloworld
{
using system;
public class Hello
{
string strHello = "Hello World!";
public Hello()
{
//empty constructor
}
public void SayHello()
{
Console.WriteLine(strHello);
}
}
}


Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.
Assembly successfully added to the cache


The -i switch installs the assembly, -l lists all the installed assemblies in the GAC, and -u uninstalls an assembly.

Creating and Implementing Satellite Assemblies

When you wish to localize the application (make the application customizable for different languages and cultures), it can be written in culture-neutral code (code that uses resources from an assembly rather than hard-coding the resources in the program) and distribute the localized modules in separate assemblies called satellite assemblies. The culture is made part of the assembly’s identity, as is the version. When the application searches for the proper assembly to load, that information will be used as the basis for the assembly-binding selection performed by the binding manager. The binding selection is performed at run time when the client’s locale and culture is known - the selection will pick the proper assembly (or best fit).

The object model for the assembly is the hub-and-spoke model where the main assembly (the culture- neutral or default assembly) is the hub and the culture-specific satellite assemblies are the spokes. This means you can deploy the application with the default culture first, and then incrementally add cultures. The locale is a setting that is defined on the client computer and specifies a culture that indicates the language that is spoken (English, for example) and a subculture that identifies the country the client is in (such as the United States). The locale defines the measurement system (metric or imperial) and number and date-formatting rules.

When creating the resources that will make up the satellite assembly, you should work with the naming convention suggested by Microsoft. It uses a culture/subculture string to indicate the locale; for example, for the English culture in Canada, the identifier would be en-CA, while the English culture in the United States would be en-US. When creating the resource files, the filename will be in this format: For example, a resource file with strings specific to the English culture might have any of the following names, depending on whether the resource is

English-language neutral or specific to a culture:.,resource

strings.en.resource
strings.en-JM.resource
strings.en-US.resource

To create the satellite assemblies, you will use the al.exe utility (Assembly Linker) to link your resource file to an assembly, as shown in this example:

al /t:library /embed:strings.en.resources /culture:en /out:MyApp.resources.dll

The /t option will direct al to build a library,
and the /embed option identifies the file to be linked.

Monday, May 25, 2009

Windows Communication Foundation

What Is Windows Communication Foundation?
The global acceptance of Web services, which includes standard protocols for application-to-application communication, has changed software development. For example, the functions that Web services now provide include security, distributed transaction coordination, and reliable communication. The benefits of the changes in Web services should be reflected in the tools and technologies that developers use. Windows Communication Foundation (WCF) is designed to offer a manageable approach to distributed computing, broad interoperability, and direct support for service orientation.

WCF simplifies development of connected applications through a new service-oriented programming model. WCF supports many styles of distributed application development by providing a layered architecture. At its base, the WCF channel architecture provides asynchronous, untyped message-passing primitives. Built on top of this base are protocol facilities for secure, reliable, transacted data exchange and broad choice of transport and encoding options.

The typed programming model (called the service model) is designed to ease the development of distributed applications and to provide developers with expertise in ASP.NET Web services, .NET Framework remoting, and Enterprise Services, and who are coming to WCF with a familiar development experience. The service model features a straightforward mapping of Web services concepts to those of the .NET Framework common language runtime (CLR), including flexible and extensible mapping of messages to service implementations in languages such as Visual C# or Visual Basic. It includes serialization facilities that enable loose coupling and versioning, and it provides integration and interoperability with existing .NET Framework distributed systems technologies such as Message Queuing (MSMQ), COM+, ASP.NET Web services, Web Services Enhancements (WSE), and a number of other functions.

Problem Example

The following example illustrates some of the problems that WCF addresses. A car rental company decides to create a new application for reserving cars. The creators of this rental car reservation application know that the business logic it implements must be accessible by other software running both inside and outside their company. Accordingly, they decide to build it in a service-oriented style, with the application’s logic exposed to other software through a well-defined set of services. To implement these services, and thus communicate with other software, the new application will use WCF.

Over its lifetime, the rental car reservation application will likely be accessed by a range of other applications. When it is designed, however, the architects of the rental car reservation application know that its business logic will be accessed, as shown in the preceding figure, by three other kinds of software:

A call center client application running on the Windows desktops that are used by employees in the organization’s call center. Created specifically for the new reservations system, this application will also be built using the Microsoft .NET Framework and WCF. This application is not truly distinct from the new rental car reservation application, because its only purpose is to act as a client for the new system. From a service-oriented perspective, it is just another client for the reservation system’s business logic.
An existing reservation application built on a J2EE server running on a non-Windows system. Due to a recent merger with another car rental firm, this existing system must be able to access the new application’s logic to provide customers of the merged firms with a unified experience.
Partner applications running on a variety of platforms, each located within a company that has a business arrangement with the car rental firm. Partners might include travel agencies, airlines, and others that have a business requirement to make car rental reservations.
The diverse communication requirements for the new rental car reservation application are not simple. For interactions with the call center client application, for instance, performance is important, while interoperability is straightforward, because both are built on the .NET Framework. For communication with the existing J2EE-based reservation application and with the diverse partner applications, however, interoperability becomes the highest goal. The security requirements are also quite different, varying across local Windows-based applications, a J2EE-based application running on another operating system, and a variety of partner applications coming in across the Internet. Even transactional requirements might vary, with only the internal applications being allowed to make transactional requests. How can these diverse business and technical requirements be met without exposing the creators of the new application to unmanageable complexity?

WCF is designed for this diverse but realistic scenario and is the default technology for Windows applications that expose and access services. This topic provides an introduction to WCF, examining what it provides and showing how it is used. Throughout this introduction, the scenario just described will serve as an example. The goal is to make clear what WCF is, show what problems it solves, and illustrate how it solves those problems.

Addressing the Problem

The foundation for new Windows-based applications is the .NET Framework. Accordingly, WCF is implemented primarily as a set of classes on top of the .NET Framework CLR. Because it extends their familiar environment, WCF enables developers who create object-oriented applications using the .NET Framework today to also build service-oriented applications in a familiar way.



The figure shows a view of a WCF client and service. The two interact using SOAP, the WCF native message representation, so even though the figure shows both parties built on WCF, this is not required. WCF is built on .NET Framework 2.0.

As the scenario described earlier suggests, WCF addresses a range of challenges for communicating applications. Three things stand out, however, as the most important aspects of WCF:

Unification of existing .NET Framework communication technologies.

Support for cross-vendor interoperability, including reliability, security, and transactions.
Explicit service orientation.
Unification of Microsoft Distributed Computing Technologies
In the absence of WCF, the development team that implements the rental car application would need to choose the right distributed technology from the multiple choices offered by the .NET Framework. Yet given the diverse requirements of this application, no single technology would fit the requirements. Instead, the application would probably use multiple existing .NET Framework technologies, such as the following:

ASP.NET Web services (ASMX). An option for communicating with the J2EE-based existing reservation application and with the partner applications across the Internet. Given that basic Web services are supported today on most platforms, this was the most direct way to achieve cross-vendor interoperability before the release of WCF.
.NET Framework remoting. An option for communication with the call center application, because both are built on the .NET Framework. Remoting is designed expressly for tightly coupled .NET-to-.NET communication, so it offers a seamless and straightforward development experience for applications in the local network.
Enterprise Services. Used by the rental car reservation application for managing object lifetimes and defining distributed transactions. These functions could be useful in communicating and integrating with any of the other applications in this scenario, but Enterprise Services supports only a limited set of communication options.
WSE. Could be used along with ASMX to communicate with the J2EE-based reservation application and with the partner applications. Because it implements more recently defined Web services agreements, known collectively as the WS-* specifications, WSE allows for more flexible Web services security, as long as all applications involved support compatible versions of these new specifications.
Microsoft Message Queuing (MSMQ). Used to communicate with Windows-based partner applications that require guaranteed data delivery as well as decoupling of workloads and application lifetimes. The durable messaging that Message Queuing provides is typically the best solution for intermittently connected applications.
Built on .NET Framework, the rental car reservation application must use more than one of these communication technologies to meet its requirements. Although this is technically possible, the resulting application would be complex to implement and challenging to maintain.

With WCF, the solution is much easier to implement. As the figure shows, WCF can be used for all the situations previously described. Accordingly, the rental car reservation application can use this single technology for all of its application-to-application communication. The following shows how WCF addresses each of these requirements:

Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.
You can also configure and extend WCF to communicate with Web services using messages not based on SOAP, for example, simple XML formats like RSS.
Performance is of paramount concern for most businesses. WCF is developed with the goal of being one of the fastest distributed application platform developed by Microsoft. For a high-level performance comparison between WCF and other Microsoft .NET distributed communication technologies, see http://go.microsoft.com/fwlink/?LinkId=94274.
To allow optimal performance when both parties in a communication are built on WCF, the wire encoding used in this case is an optimized binary version of an XML Information Set. Messages still conform to the data structure of a SOAP message, but their encoding uses a binary representation of that data structure rather than the standard angle-brackets-and-text format of the XML 1.0 text encoding. Using this option makes sense for communicating with the call center client application, because it is also built on WCF, and performance is an important concern.
Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise Services are now provided by WCF. They are available to any WCF-based application, which means that the rental car reservation application can use them with any of the other applications it communicates with.
Because it supports a large set of the WS-* specifications, WCF helps provide reliability, security, and transactions when communicating with any platform that also supports these specifications.
The WCF option for queued messaging, built on Message Queuing, allows applications to use persistent queuing without using another set of application programming interfaces.
The result of this unification is greater functionality and significantly reduced complexity.

Interoperability with Applications Built on Other Technologies

While WCF introduces a new development environment for distributed applications, it is designed to interoperate well with the non-WCF applications. There are two important aspects to WCF interoperability: interoperability with other platforms, and interoperability with the Microsoft technologies that preceded WCF. The following section describes both.

Interoperability with Other Web Services Platforms
Enterprises today typically have systems and applications that they purchased from a range of suppliers. In the rental car application, for instance, communication is required with various other software applications written in various languages and running on various operating systems.

Because WCF’s fundamental communication mechanism is SOAP-based Web services, WCF-based applications can communicate with other software running in a variety of contexts. An application built on WCF can interact with all of the following:

WCF-based applications running in a different process on the same Windows machine.
WCF-based applications running on another Windows machine.
Applications built on other technologies, such as J2EE application servers, that support standard Web services. These applications can be running on Windows machines or on machines running other operating systems.
To allow more than just basic communication, WCF implements Web services technologies defined by the WS-* specifications. All of these specifications were originally defined by Microsoft, IBM, and other vendors working together. As the specifications become stable, ownership often passes to standards bodies, such as the World Wide Web Consortium (W3C) or the Organization for the Advancement of Structured Information Standards (OASIS). These specifications address several areas, including basic messaging, security, reliability, transactions, and working with a service’s metadata. For more information, see Interoperability and Integration. For more information about advanced Web services specifications, see http://go.microsoft.com/fwlink/?LinkId=86603.

Grouped by function, those specifications cover:

Messaging: SOAP is the foundation for Web services and defines a basic envelope that contains header and a body sections. WS-Addressing defines additions to the SOAP header for addressing SOAP messages, which frees SOAP from relying on the underlying transport protocol, such as HTTP, to carry addressing information. Message Transmission Optimization Mechanism (MTOM) defines an optimized transmission format for SOAP messages with large binary data contents based on the XML-binary Optimized Packaging (XOP) specification.
Metadata: The Web Services Description Language (WSDL) defines a standard language for specifying services and various aspects of how those services can be used. WS-Policy allows specification of more dynamic aspects of a service’s behavior that cannot be expressed in WSDL, such as a preferred security option. WS-MetadataExchange allows a client to directly request descriptive information about a service, such as its WSDL and its policies, using SOAP.
Security: WS-Security, WS-SecureConversation, WS-Trust, and WS-Federation all define additions to SOAP messages for providing authentication, data integrity, data privacy, and other security features.
Reliability: WS-Reliable Messaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more Web services intermediaries must be traversed.
Transactions: Built on WS-Coordination, WS-Atomic Transaction allows coordinating two-phase commit transactions in the context of Web services conversations.
The rental car reservation application would likely use several of these more advanced technologies. For example, WS-Addressing is essential whenever SOAP is used over a transport mechanism other than HTTP, which might be the case for communication with the .NET Framework-based call center client application. WCF relies on WS-Policy and WS-Metadata Exchange to discover whether the system it is communicating with is also using WCF and for other things. Reliable communication is essential for most situations, so it is likely that WS-Reliable Messaging would be used to interact with many of the other applications in this scenario. Similarly, you might also use WS-Security and the related specifications for securing the communication with one or more of the applications, because all would require some kind of protection against unauthorized access or message modification and interception. For the applications that require transaction integration with the rental car reservation system, WS-Atomic Transaction would be essential. Finally, MTOM could be used whenever an optimized wire format for binary data is necessary (for instance for pictures of fleet examples), and both sides of the communication supported this option.

The key point is that WCF implements interoperable Web services complete with cross-platform security, reliability, transactions, and other services. To provide maximum throughput, WCF-to-WCF communication can be significantly optimized, but all other communication uses standard Web services protocols. In fact, it is possible for a single application to expose its services to both kinds of clients.

Interoperability with Microsoft Technologies
Many Microsoft customers have made significant investments in the .NET Framework technologies that WCF includes. Protecting those investments was a fundamental goal of WCF’s designers. Installing WCF does not break existing technology, so there is no requirement that organizations change existing applications to use it. A clear upgrade path is provided, however, and wherever possible, WCF interoperates with those earlier technologies.

For example, both WCF and ASMX use SOAP, so WCF-based applications can directly interoperate with those built on ASMX. Existing Enterprise Services applications can also be wrapped with WCF interfaces, allowing them to interoperate with applications built on WCF. And because persistent queuing in WCF relies on MSMQ, WCF-based applications can interoperate directly with non-WCF-based applications built using native MSMQ interfaces. In the rental car reservations application, software built using any of these earlier technologies could directly connect to and use the new system’s WCF-based services.

Interoperability is not always possible, however. For example, even though WSE 1.0 and WSE 2.0 implement some of the same WS-* specifications as WCF, these earlier technologies implement earlier versions of the specifications. Version 3.0 of WSE does allow interoperability with WCF, but earlier versions do not. For more information about interoperability, see Migrating WSE 3.0 Web Services to WCF.

Interoperability with Other XML Protocols

The future of the Internet is not predictable and the technologies used today may evolve or be replaced. Today, a popular trend in building Web-centric applications (called by many "Web 2.0"), is an application model based on communication using only simple XML formats that are not SOAP-based and exclusively rely on HTTP as a transport and as an application protocol. For example, the Representational State Transfer (REST) architectural style has no notion of user-defined operations for dealing with data. Instead, application state is associated with HTTP URLs and HTTP methods (such as PUT, POST, DELETE, and GET). This approach is in contrast to the creation of user-defined procedures or functions that most developers are familiar with in an enterprise environment. However, the REST approach is of value in scenarios where services must function as the back end of Web 2.0 applications.

REST is just one example of an evolving Web 2.0 technology. In this environment of experimental programming models and ongoing reinterpretation and refinement of standards, flexibility is required to cope with unforeseeable changes. WCF is flexible. For example, while WCF uses SOAP as an underlying structure, it is not bound to using SOAP for wire communication. In fact, WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON). This flexibility ensures that code written today will be valid in the future, even if protocols change or are replaced. Therefore, WCF was designed for the present and the future.

Friday, August 1, 2008

User Defined Functions

User Defined Functions

This article covers all the basics of User Defined Functions. It discusses how (and why) to create them and when to use them. It talks about scalar, inline table-valued and multi-statement table-valued functions. (This article has been updated through SQL Server 2005.)

With SQL Server 2000, Microsoft has introduced the concept of User-Defined Functions that allow you to define your own T-SQL functions that can accept zero or more parameters and return a single scalar data value or a table data type.

What Kind of User-Defined Functions can I Create?

There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi-statement Table-valued.

How do I create and use a Scalar User-Defined Function?

A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. Below is an example that is based in the data found in the NorthWind Customers Table.

CREATE FUNCTION whichContinent

(@Country nvarchar(15))

RETURNS varchar(30)

AS

BEGIN

declare @Return varchar(30)

select @return = case @Country

when 'Argentina' then 'South America'

when 'Belgium' then 'Europe'

when 'Brazil' then 'South America'

when 'Canada' then 'North America'

when 'Denmark' then 'Europe'

when 'Finland' then 'Europe'

when 'France' then 'Europe'

else 'Unknown'

end

return @return

end

Because this function returns a scalar value of a varchar(30) this function could be used anywhere a varchar(30) expression is allowed such as a computed column in a table, view, a T-SQL select list item. Below are some of the examples that I was able to use after creating the above function definition. Note that I had to reference the dbo in the function name.

print dbo.WhichContinent('USA')

select dbo.WhichContinent(Customers.Country), customers.*

from customers

create table test

(Country varchar(15),

Continent as (dbo.WhichContinent(Country)))

insert into test (country)

values ('USA')

select * from test

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Country Continent

--------------- ------------------------------

USA North America

Stored procedures have long given us the ability to pass parameters and get a value back, but the ability to use it in such a variety of different places where you cannot use a stored procedure make this a very powerful database object. Also notice the logic of my function is not exactly brain surgery. But it does encapsulate the business rules for the different continents in one location in my application. If you were to build this logic into T-SQL statements scattered throughout your application and you suddenly noticed that you forgot a country (like I missed Austria!) you would have to make the change in every T-SQL statement where you had used that logic. Now, with the SQL Server User-Defined Function, you can quickly maintain this logic in just one place.

How do I create and use an Inline Table-Value User-Defined Function?

An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

CREATE FUNCTION CustomersByContinent

(@Continent varchar(30))

RETURNS TABLE

AS

RETURN

SELECT dbo.WhichContinent(Customers.Country) as continent,

customers.*

FROM customers

WHERE dbo.WhichContinent(Customers.Country) = @Continent

GO

SELECT * from CustomersbyContinent('North America')

SELECT * from CustomersByContinent('South America')

SELECT * from customersbyContinent('Unknown')

Note that the example uses another function (WhichContinent) to select out the customers specified by the parameter of this function. After creating the user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets. Also note that I do not have to reference the dbo in my reference to this function. However, when using SQL Server built-in functions that return a table, you must now add the prefix :: to the name of the function.

Example from Books Online: Select * from ::fn_helpcollations()

How do I create and use a Multi-statement Table-Value User-Defined Function?

A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

CREATE FUNCTION dbo.customersbycountry ( @Country varchar(15) )

RETURNS

@CustomersbyCountryTab table (

[CustomerID] [nchar] (5), [CompanyName] [nvarchar] (40),

[ContactName] [nvarchar] (30), [ContactTitle] [nvarchar] (30),

[Address] [nvarchar] (60), [City] [nvarchar] (15),

[PostalCode] [nvarchar] (10), [Country] [nvarchar] (15),

[Phone] [nvarchar] (24), [Fax] [nvarchar] (24)

)

AS

BEGIN

INSERT INTO @CustomersByCountryTab

SELECT [CustomerID],

[CompanyName],

[ContactName],

[ContactTitle],

[Address],

[City],

[PostalCode],

[Country],

[Phone],

[Fax]

FROM [Northwind].[dbo].[Customers]

WHERE country = @Country

DECLARE @cnt INT

SELECT @cnt = COUNT(*) FROM @customersbyCountryTab

IF @cnt = 0

INSERT INTO @CustomersByCountryTab (

[CustomerID],

[CompanyName],

[ContactName],

[ContactTitle],

[Address],

[City],

[PostalCode],

[Country],

[Phone],

[Fax] )

VALUES ('','No Companies Found','','','','','','','','')

RETURN

END

GO

SELECT * FROM dbo.customersbycountry('USA')

SELECT * FROM dbo.customersbycountry('CANADA')

SELECT * FROM dbo.customersbycountry('ADF')

What are the benefits of User-Defined Functions?

The benefits to SQL Server User-Defined functions are numerous. First, we can use these functions in so many different places when compared to the SQL Server stored procedure. The ability for a function to act like a table (for Inline table and Multi-statement table functions) gives developers the ability to break out complex logic into shorter and shorter code blocks. This will generally give the additional benefit of making the code less complex and easier to write and maintain. In the case of a Scalar User-Defined Function, the ability to use this function anywhere you can use a scalar of the same data type is also a very powerful thing. Combining these advantages with the ability to pass parameters into these database objects makes the SQL Server User-Defined function a very powerful tool.

Summary

So, if you have ever wanted to use the results of a stored procedure as part of a T-SQL command, use parameterized non-updateable views, or encapsulate complex logic into a single database object, the SQL Server 2000 User-Defined function is a new database object that you should examine to see if its right for your particular environment.

Thursday, July 31, 2008

Working with Email Using ASP.NET 2.0

Working with Email Using ASP.NET 2.0

Introduction

In ASP.NET 1.x sending email was fairly simple. The only issue was that there were different ways to send email depending on whether the application was web or windows based. Windows developers used MAPI to send emails using an email client like Outlook. Web developers used CDOSYS to send rich emails. Microsoft realized that a change was warranted. In ASP.NET 2.0 Microsoft released a new set of classes to handle email. The only issue is that to many developers, sending email became much more complex. Within this article, we will walk through the changes to the web.config file, the new classes that are available and how to send email using the new MailMessage class.

Examining the Web.config

By now you should be familiar with the system.web section group that is found in the web.config file. In ASP.NET 2.0 a new group was added that contains configurable sections for the System.Net namespace called the system.net section group. This group allows email settings to be established by using the mailSettings section group. Since we are sending emails and not receiving emails, we will use the SMTP protocol. To define the SMTP settings, we will add the SMTP section group to the mailSettings section group. The SMTP section group then contains a network section that specifies attributes for the SMTP network settings. These attributes include host, port, username, and password. An example of the system.net section group can be found in listing 1.

Listing 1

host="mail.contoso.com"

userName="email@contoso.com" password="password" />

Accessing the Web.config from Code

To prevent confusion, in ASP.NET 2.0 the System.Web.Mail namespace has been marked deprecated. All of the classes are still accessible using IntelliSense and will still function properly. However, they too are marked obsolete. Instead, a new namespace found at System.Net.Mail should be used. This new namespace contains classes to manage your mail client and messages. The SmtpClient class is used to establish a host, port, and network credentials for your SMTP server. The MailMessage class is similar to the MailMessage class found in the old System.Web.Mail namespace. This class allows a full email message to be built. There is also an Attachment class that allows an attachment to be generated so it can later be added to the MailMessage object. In addition to these three most commonly used classes, you will find that System.Net.Mail contains an AlternateView and LinkedResource class.

Unfortunately, ASP.NET 2.0 does not provide a clean and easy way to access the system.net section group from the web.config file within code. The SmtpClient object contains a UseDefaultCredentials boolean property, but that specifies whether the SmtpClient object is to use the credentials of the user currently running the application. Before we begin accessing the attributes in the web.config file, we will need to determine what credentials will be required to connect to the SMTP server and ensure that the values we will use will work. In many cases, the credentials that would be used to connect to a Microsoft Exchange server would be different than those to connect to many ISP email systems. In the example to follow we will use a username, password, and hostname.

The first task on our plate is to read the mailSettings section group from the web.config file. To accomplish this task, we will need to create a new object of type System.Configuration.Configuration. This object will store our web.config file. We will assign this new object to the applications web.config by using the OpenWebConfiguration method of the WebConfigurationManager class. The OpenWebConfiguration method will look for a relative path. We will pass in the HttpContext.Current.Request.ApplicationPath since we will want to load the web.config file for the current application.

The second task is to load the specific section group from the object that contains our web.config file into a new object. A new object of type System.Net.Configuration.MailSettingsSectionGroup will be created. This object will be assigned to the mailSettings section in the web.config file. We will use the GetSectionGroup method of our configuration object to obtain this section. ASP.NET does not know that the mailSettings section is found under system.net so we must specify the full section group as system.net/mailSettings. An example of this can be seen in listing 2.

Listing 2

(IN Vb.net)

Dim config As System.Configuration.Configuration = _

WebConfigurationManager.OpenWebConfiguration( _

HttpContext.Current.Request.ApplicationPath)

Dim settings As System.Net.Configuration.MailSettingsSectionGroup = _

CType(config.GetSectionGroup("system.net/mailSettings"), _

System.Net.Configuration.MailSettingsSectionGroup)

(In C#)

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

Creating the SMTP Client

A new object of type SmtpClient will be created to act as the SMTP server for mail being sent out. The SmtpClient object will need to have the network credentials passed into it. Thus, we will need to create a new object of type System.Net.NetworkCredential and pass in the username and password values from the web.config. These values can be found by assessing the Smtp.Network.Username and Smtp.Network.Password properties of the settings object defined earlier. The NetworkCredential object will be assigned to the Credentials property of the SmtpClient object. The other property we must set is the SmtpClient object's host property. This too will be assigned a value from the settings object created earlier. An example of this can be seen in the listing given below.

Listing 3

'Obtain the Network Credentials from the mailSettings section

Dim credential As New System.Net.NetworkCredential( _

settings.Smtp.Network.UserName, settings.Smtp.Network.Password)

'Create the SMTP Client

Dim client As New SmtpClient()

client.Host = settings.Smtp.Network.Host

client.Credentials = credential

Creating a MailMessage Object

The MailMessage object in ASP.NET 2.0 is much more robust than the one found in the CDOSYS libraries in ASP.NET 1.x. The new MailMessage object still contains all of the common properties that an email message has including To, From, Subject, and Body. The To and From properties have changed a bit. The From property is no longer "just a string." Instead, the From property is of type MailAddress. The To property is similar in that it is a collection of MailAddress objects. Since the CC and Bcc properties have the same requirements as the To property, they too are a collection of MailAddress objects. The MailMessage object contains some additional properties including, but not limited to, AlternateViews, Attachments, BodyEncoding, DeliveryNotificationOptions, IsBodyHtml, Priority, and ReplyTo.

The AlternateViews property allows an alternate view to be specified by passing in either a filename or a stream and assigning a MIME type to the view. The Attachments property allows attachments to be added to the message. The BodyEncoding property is a value that can specify the System.Text.Encoding type of the email message. The DeliveryNotificationOptions property specifies when delivery notifications should be received. The IsBodyHtml property is a boolean value signifying whether the email's body is HTML or plain text. The Priority property specifies whether this email is of high, low, or normal importance. The ReplyTo property is the email address that the reply message would go to.

To send the MailMessage object, the object must be passed into the Send method of the SmtpClient object. An example of this can be seen in the listing below.

Listing 4

'Build Email Message

Dim email As New MailMessage

email.From = New MailAddress("email@contoso.com")

email.To.Add("steveb@contoso.com")

email.CC.Add("billg@contoso.com")

email.Subject = "Test Email"

email.IsBodyHtml = True

email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure

email.Body = "Hello Steve!"

'Send Email

client.Send(email)

Conclusion

As you can see now, sending email in ASP.NET 2.0 is much more complex. However, it is also much more robust. Many of the email options that you could not access before without adding an email header to the email message can now be added with properties. Hopefully the team will continue to enhance this namespace and add additional functionality in the future.

Resouse url : http://aspalliance.com/articleViewer.aspx?aId=962&pId=-1