Pages

Sunday, January 6, 2008

What is a web service

Web services make software functionality available over the Internet so that programs like PHP, ASP, JSP, JavaBeans, the COM object, and all our other favorite widgets can make a request to a program running on another server (a web service) and use that program’s response in a website, WAP service, or other application.

So when I need to get some programming task done, and am too busy (or not crazy enough) to attempt it myself, I can make use of a web service by calling it over the Internet. By passing parameter data with the request, I can expect to receive a response containing the result generated by the web service.

Anyone who has used Hotmail recently has had a brush with web services: the passport authentication system is one of the web services in Microsoft’s .NET initiative, and is available without charge for the moment, so developers can use passport authentication within their own sites.

The principles behind web services are stunningly simple, and are nothing new in the world of distributed computing and the Internet:

the web service provider defines a format for requests for its service and the response the service will generate
a computer makes a request for the web services across the network
the web service performs some action, and sends the response back
This action might be retrieving a stock quote, finding the best price for a particular product on the net, saving a new meeting to a calendar, translating a passage of text to another language, or validating a credit card number.

Saturday, January 5, 2008

Using the Domain Objects Persistence Pattern in .NET

Domain objects in an application represent the core data and business validation rules relating to it. And, domain objects are usually central to the entire application and used by most subsystems. Therefore, their good design is critical for a good application design that is robust, high performing, and yet flexible.

When it comes to developing object oriented applications that use relational databases, the domain object design has to be consistent with the database design. This make them easier to understand because they represent real-life "entities" and their relationships with each other. Therefore, in many situations, the domain objects are "mapped" to the relational database tables and relationships between tables. However, it is very easy to get this mapping wrong and end up with an undesirable domain object design. A good design for domain objects requires a solid understanding of object oriented and relational fundamentals on the part of developers.

Domain Objects Persistence Pattern attempts to provide a solution for domain object mapping to the relational databases that decouples the domain objects from the persistence logic. The domain objects in this pattern are unaware of the objects that persist them because the dependency is only one-way (from persistence objects to domain objects). This makes the domain objects design much simpler and easier to understand. It also hides the persistence objects from other subsystems in the application that are using the domain objects. This also works in distributed systems where only the domain objects are passed around. In this context, an attempt is made to incorporate the Factory Pattern into this pattern to help decouple domain objects and persistence logic.



Problem Definition

Domain objects form the backbone of any application. They capture the core data model from the database and also the business rules that apply to this data. It is very typical for most subsystems of an application to rely on these common domain objects. This means that the closer the domain objects map to the data model in the database, the easier it is for the application developers to understand and use them because they mimic real-life "entities" and "relationships" as represented in the database.

If domain objects are not separated from the rest of the application, we end up with duplication of code everywhere. Similarly, if domain objects are not separated from the persistence code, we face situations where any subsystem using the domain objects also knows and depends on the persistence objects. And, any change in persistence objects affects the entire application, hence a bad design.


Solution
One way to achieve the above mentioned goals is to separate the domain objects into a separate subsystem and let the entire application use them wherever it needs domain data. Additionally, we should separate domain objects from the persistence code. This double-decoupling allows us on one hand to avoid code duplication and on the other to hide the persistence details from the domain objects and make it more flexible in case it needs to change. The domain objects and the rest of the application is totally unaffected whether the data is coming from a relational database or any other source (e.g. XML, flat files, or Active Directory/LDAP).

In separating the persistence logic from domain objects, we ensure that the domain objects have no dependency on the persistence code. This allows the domain objects to become available in environments where we don't even want to expose our persistence code.


Sample Code

In this sample, we will look at a Customer object from Northwind database mapped to the "Customers" table in the database.

public class Customer {
// Private data members
String _CustomerID;
String _companyName;
String _contactName;
String _contactTitle;

public Customer() {}

// Properties for Customer object
public String CustomerId {
get { return _customerId; } set { _customerId = value;}
}

public String CompanyName {
get { return _companyName; } set { _companyName = value;}
}

public String ContactName {
get { return _contactName; } set { _contactName = value;}
}

public String ContactTitle {
get { return _contactTitle; } set { _contactTitle = value;}
}
}

public interface ICustomerFactory
{
// Standard transactional methods for single-row operations
void Load(Customer cust);
void Insert(Customer cust);
void Update(Customer cust);
void Delete(Customer cust);

// Query method to return a collection
ArrayList FindCustomersByState(String state);

}

public class CustomerFactory : ICustomerFactory
{
// Standard transactional methods for single-row operations
void Load(Customer cust) { /* Implement here */ }
void Insert(Customer cust) { /* Implement here */ }
void Update(Customer cust) { /* Implement here */ }
void Delete(Customer cust) { /* Implement here */ }

// Query method to return a collection
ArrayList FindCustomersByState(String state) { /* Implement here */ }
}
Below is an example of how a client application will use this code.

public class NorthwindApp
{
static void Main (string[] args) {
Customer cust = new Customer();
CustomerFactory custFactory = new CustomerFactory();

// Let's load a customer from Northwind database.
cust.CustomerId = "ALFKI";
custFactory.load(cust);

// Pass on the Customer object
FooBar(cust);

// custList is a collection of Customer objects
ArrayList custList = custFactory.FindCustomersByState("CA");
}
}

As you can see above, the "load" method loads the Customer object from the database based on the CustomerId. Once the Customer is loaded, then it can be passed on to any subsystem in the application without exposing the persistence code. Similarly, if you get an ArrayList of Customer objects, you can pass on the ArrayList which has no persistence code dependency

Thursday, January 3, 2008

With Check Option

This clause is very important because it prevents changes that do not meet the view's criteria.

Example: Create a view on database pubs for table authors, that shows the name, phone number and state from all authors from California. This is very simple:

CREATE VIEW dbo.AuthorsCA
AS
SELECT au_id, au_fname, au_lname, phone, state, contract
FROM dbo.authors
WHERE state = 'ca'

This is an updatable view and a user can change any column, even the state column:

UPDATE AuthorsCA SET state='NY'

After this update there will be no authors from California. This might not be the desired behavior.

Example: Same as above but the state column cannot be changed.

CREATE VIEW dbo.AuthorsCA2
AS
SELECT au_id, au_fname, au_lname, phone, state, contract
FROM dbo.authors
WHERE state = 'ca'
With Check Option

The view is still updatable, except for the state column:

UPDATE AuthorsCA2 SET state='NY'

This will cause an error and the state will not be changed.

Encrypting Configuration Information in ASP.NET 2.0 Applications

The .NET Framework 2.0 libraries include the capabilities to encrypt most any configuration sections within the Web.config or machine.config files. Configuration sections are those XML elements that are children of the or elements.

Encryption Options
Protecting configuration sections in ASP.NET 2.0 uses the provider model, which allows for any implementation to be seamlessly plugged into the API. The .NET Framework 2.0 ships with two built-in providers for protecting configuration sections:

The Windows Data Protection API (DPAPI) Provider (DataProtectionConfigurationProvider) - this provider uses the built-in cryptography capabilities of Windows to encrypt and decrypt the configuration sections. By default this provider uses the machine's key. You can also use user keys, but that requires a bit more customization.Since the keys are machine- or user- specific, the DPAPI provider does not work in settings where you wan to deploy the same encrypted configuration file to multiple servers.
RSA Protected Configuration Provider (RSAProtectedConfigurationProvider) - uses RSA public key encryption to encrypt/decrypt the configuration sections. With this provider you need to create key containers that hold the public and private keys used for encrypting and decrypting the configuration information.

Programmatically Encrypting Configuration Sections
The System.Configuration.SectionInformation class abstractly represents a configuration section. To encrypt a configuration section simply use the SectionInformation class's ProtectSection(provider) method, passing in the name of the provider you want to use to perform the encryption. To access a particular configuration section in your application's Web.config file, use the WebConfigurationManager class (in the System.Web.Configuration namespace) to reference your Web.config file, and then use its GetSection(sectionName) method to return a ConfigurationSection instance. Finally, you can get to a SectionInformation object via the ConfigurationSection instance's SectionInformation property.

private void ProtectSection(string sectionName,
string provider)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section =
config.GetSection(sectionName);

if (section != null &&
!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}

private void UnProtectSection(string sectionName)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section =
config.GetSection(sectionName);

if (section != null &&
section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}

Partial Classes

Partial classes allows you to have multiple pieces of a class definition. Functionally, partial classes are not at all different from classes written as full classes. Which means you can have one single class definition or a class written as a few distinct parts, without breaking existing functionality.

How Partial Classes Work

The basic idea of a partial class is very easy to understand. You keep the definition of a class split into pieces. During the compilation of the code, the compiler will finds all of the pieces of the class and lump them together. This task accomplished by the compiler removes that separation, so functionally there is no difference between a class made of partial classes and a whole class.

Creating Partial Classes
Partial classes allow you to separate code for a class into multiple class definitions. So as an example I will write a few class definitions. One will be a whole definition of a class without using partial classes, and the other one will be the same class split into two partial classes.My single definition class of AIPlayer.

Listing 1: A Standard Class

public class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
public Move GetMove()
{
// Choose the best move and return it.
}
}


Listing 2: A Class Split Into Two Partial Classes

public partial class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
}
public partial class AIPlayer
{
public Move GetMove()
{
// Choose the best move and return it.
}
}Without having the partial keyword in there I would probably get a compiler error. The reason for this is that I would be declaring two different classes in the same namespace with the same name, and that would generate the error. Since I have the partial keyword there, the compiler knows that I am just extending the existing class. It will take that into account and will combine the code before trying to compile it.

As a note, make sure to use the partial keyword on ALL definitions of the class even the original one. This is not necessary for VB, but in C# all of the classes must have the partial keyword. I think it is great that this is included, because it is a hint to a programmer that there might be another piece of a class somewhere else. If you ever see the partial keyword on classes you're working with, it is a nice warning that there might be more to the class elsewhere.

When to Use Partial Classes
There are plenty of cases where a partial class can assist you in developing your applications. Most people have already seen them and might not have noticed them in ASP.NET pages, because you don't actually need to know that it is using these partial classes in order to use them. They're also quite popular being used alongside generated code, because it lets people modify the generated code. Sometimes people will also use it when working in larger groups who will not be committing code often. This is because it lets them make large amounts of changes without having painful merges later.

Send emails with dynamic contents through asp.net 2.0.

These two namespaces plays a major role in sending emails with dynamic content :

System.Web.Mail Namespace

The System.Web.Mail namespace contains classes that enable you to construct and send messages using the CDOSYS (Collaboration Data Objects for Windows 2000) message component. The mail message is delivered either through the SMTP mail service built into Microsoft Windows 2000 or through an arbitrary SMTP server. The classes in this namespace can be used from ASP.NET or from any managed application.

System.IO Namespace
The System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.