Friday, November 30, 2007

BizTalk Server 2006 (14) Activity Monitoring

BAM:

  • The information worker needs to have answers to questions such as:
  • How many orders are there over $10,000.00?
  • How well are our products selling?
  • How long does it take for an order to be delivered to the customer from the time the order is placed?
  • In order to do so, the information worker can use the Business Activity Monitoring (BAM) addin within Excel.

HAT:

  • The administrator needs to answer the following questions:
  • Are all of the orchestrations, pipelines, and maps running?
  • Are the messages being processed in a timely manner?
  • Were any of the orchestration terminated accidentally or abnormally?
  • To do so, the administrator is able to use a tool called the Health and Activity Tracker (HAT) to run predefined queries and view the overall health of a system

Professional BizTalk Server 2006

Thursday, November 29, 2007

BizTalk Server 2006 (13) Business Rules

Vocabulary:

  • Collection of definitions for rule conditions and actions
  • Assigns a friendly name to the definitions

Policy:

  • Contains logical grouping of rules
  • Are published and deployed to a production environment

Rule Store:

  • Place to store policies and vocabularies
  • Stored in SQL Server by default
  • Can be exported and imported to/from SQL Server

Rules Engine:

  • Applies rules to the available facts and evaluates the result
  • Determines the necessary actions to take based on the evaluation
  • Executes the action

Business Rules and Orchestrations

  • You can incorporate business rules within your orchestration to allow flexibility to read and process constantly changing values instead of having to recode/recompile the orchestration
  • Based on a business rule, you can determine when a process requires a delay

Steps to integrate business rules are as follows:

  • Identify the business logic to be represented
  • Identify data sources for rule elements
  • Create rules from vocabulary definitions
  • Test and debug with facts
  • Publish and deploy policy
  • Bind send and receive shapes to ports
  • Call the rule from within an orchestration

Steps to integrate business rules with an orchestration are as follows:

  • Add a reference to the rule engine assembly
  • Make the orchestration transactional
  • Add an atomic scope
  • Add a message assignment shape
  • Create a message instance

Professional BizTalk Server 2006

Tuesday, November 27, 2007

BizTalk Server 2006 (12) Web Services

  • Using BizTalk Server 2006, you are able to publish an entire orchestration or a schema as a web service

In order to cosume a web service you need to:

  • Call a web service from an orchestration
  • Use the Universal Description, Discovery, and Integration (UDDI) to access service information
  • Specify if it will be a request-only (one-way) or a request-response (two-way) comsumption
  • Add a web reference
  • Create a web port
  • Create needed message variables
  • Construct a web message
  • Add send and receive shapes

Message Variables:

  • Used to store information sent and received by a web service
  • By using a web service, the orchestration never deals with the actual schema but rather message instances
  • Needed to construct a message whenever you introduce a message to the orchestration

Web message:

  • Can be either simple or complex .NET types

Send and Receive shapes:

  • Are used to send and receive requests to/from a web service
  • Are created using the Ochestration Designer
  • Are linked to a web port

Professional BizTalk Server 2006

Monday, November 26, 2007

BizTalk Server 2006 (11) Transaction

Using BizTalk Server 2006, multiple tasks can be combined into a unit of work known as a transaction. There are two primary types of transactions supported by BizTalk and they are:

  • Atomic
  • Long-Running

Scopes:

  • A scope is a framework for organizing actions
  • Scopes are primarily used for transactional execution of tasks and exception handling
  • A scope can contain one or more blocks that has a body and can have any number of exception handling blocks

Atomic Transactions:

  • guarantees rollback in the event the transaction process fails
  • Used when ACID properties are required

ACID:

  • Atomic - the entire transaction will succeed or fail as a whole
  • Consistent - provides a consistent view of the data and always leaves the data in a consistent state
  • Isolated - all transactions appear as though they are running by themselves
  • Durable - once the transaction is committed, the data is recoverable in the event of failure

Long-Running Transactions:

  • Are transactions that need to run for extended periods of time
  • Are used when ACID properties are not required
  • Data is not locked and can be modified
  • Individual steps are committed during the time the transaction is being processed
  • The transaction itself is not committed until the last statement has been completed
  • Within them, they can contain both atomic and other L-R transactions

Professional BizTalk Server 2006

Sunday, November 25, 2007

BizTalk Server 2006 (10) Orchestration

To develop a BizTalk Orchestration, you need to complete the following steps:
  • Define schemas to describe message formats
  • Add shapes to represent business process actions
  • Assign or transform data between messages
  • Define send and receive ports for messages
  • Define orchestration variables and types
  • Bind the send and receive shapes to ports
  • Build the orchestration and test it for errors

Professional BizTalk Server 2006

BizTalk Server 2006 (9) Pipelines

Understanding BizTalk Server 2006
Professional BizTalk Server 2006

Pipelines:
  • Components within the BizTalk system that are able to process messages either when they are received or just before they are sent out
  • Pipelines divide processing into several categories, known as processing stages
  • They also specify the sequence in which each stage of the work is performed

Processing stages:

  • Define logical work groups
  • Determine which components can belong to a stage
  • Specify how the pipeline components in the stage are run

Stages in a pipeline include:

  • Encrypting and decrypting
  • Encoding and decoding
  • Assembling and disassembling

Receive Pipeline:

  • Receive pipeline takes the initial message, performs transformations, and disassembles the raw data into zero, one, or multiple messages
  • These are XML messages that are then sent to be processed through the BizTalk server

Receive Pipeline Stages, each receive pipeline consists of the following four stages:

  • Decode: used to decode MIME encoded messages
  • Disassemble: used to normalize messages from native incoming format to BizTalk Server's internal XML format
  • Validate: used to verify an incoming document against a specified schema
  • Resolve party: used to verify that the incoming message was sent from a trusted source

Send Pipeline:

  • Responsible for processing documents before they are sent to their destination
  • Each send pipeline accepts one message and produces one message to be sent

Send Pipelines consist of three empty stages:

  • Pre-assemble: used to conduct processing on the message needed before it is assembled
  • Assemble: used to assemble the BizTalk XML document into a XML, flat-file, or a BizTalk Framework (BTF) format
  • Encode: used to encode the document to MIME/SMIME and to digitally sign messages

Using a Default Pipeline

Pass-through receive:

  • Contains no components
  • No decoding, validation, or disassembling required
  • Used when both send and receive destination are known and is commonly used in conjunction with the pass-through send pipeline

Pass-through send:

  • Contains no components
  • No encoding or assembling required
  • Used for basic message routing
  • Commonly used in conjunction with the pass-through receive pipeline

XML receive:

  • Contains the XML disassembler component
  • Party resolution component for security
  • No decoding or validation stage

XML send:

  • Contains the XML assembler component (Preassembling, Serializing, Encoding)

Saturday, November 24, 2007

BizTalk Server 2006 (8) BizTalk Schema

  • BizTalk utilizes the XML Schema Definition (XSD) to define the structure of all message that it processes
  • The XSD message structures are known as 'schemas' within BizTalk
  • It is by the use of these XML Schemas that BizTalk is able to conduct all of its integration operations

BizTalk supports the following types of schemas:

  • XML - (XSD)
  • Flat-file - structure of a message using flat-files that are delimited or positional
  • Property - special type of schema that identifies specific field elements that you want to make available to a BizTalk Orchestration

Different Types of BizTalk Schemas

BizTalk Server 2006 (7) BTS Maps

Through BTS Maps:
  • You can start creating a map in vs2005, and then open a source schema and open a destination schema
  • Then you can simply drag and drop item from the source item to the destination item to map them.
  • If you need to do furthur tasks when mapping such as string concatenation, multiplication of numbers, you will need to drag a Functoid from toolbox to the mapping grid and drag an item from the source schema to the Functoid, and then drag a line from this Functoid to the destination item.
  • Note that if more than one Functoid is used, the order of the placement of the Functoid matters.
  • You can program your custom Functoid to cater for specific needs.
Functoids in BizTalk

Writing Custom BizTalk Functoids

BizTalk Server 2006 (6) Flat File Schema




This walkthrough shows you how to create a flat file schema from a document instance using the BizTalk Flat File Schema Wizard:
Walkthrough: Creating a Flat File Schema From a Document Instance

BizTalk 2006 Flat File Wizard: How to model a complicated flat file schema

BizTalk Flat File Schema Wizard UI Help

Notes:

  • The Wizard is a very powerful tool that will saves lots of development times
  • You could generate a xsd schema from the flat file, such as a purchase order txt file which may be generated by a SAP system

The wizard will help you do the following:

  • Import a complex flat file

  • Specify a tag identifier

  • Define child elements
  • Define repeating records

  • Select Record Format Page: relative positions is very powerful

  • Validate the schema and the flat file instance
  • View the instance
  • The 'Allow Early Termination' property of the schema is very useful, it allows the repeating record to have a flexible number of digits in a certain element in a record row.


BizTalk Server 2006 (5) Architecture


The primary purpose of a BizTalk application is to receive a messagefrom a system and taking it through the various channels of BizTalk and finally sending it to its destination.

BizTalk Server 2006 (4) Configuration




After installation, you will need to config the BizTalk server.


BizTalk Server 2006 (3) What's New?

For Management and Operations:

  • Microsoft Management Console (MMC) integration for enterprise management
  • Single view of operations and monitoring
  • Application-level management
  • Engine and infrastructure changes

For Business Users:

  • Real-time Business Activity Monitoring (BAM) alerting and notification
  • BAM portal and resuable web components
  • SharePoint Adapter for more native integration with Windows SharePoint Services

On Windows Server Systems:

  • Support for Window 64-bits (x86)
  • SQL Server 2005
  • Visual Studio 2005 / .Net Framework 2.0
  • Microsoft Virtual Server 2005

For Setup, Migration, and Deployment:

  • Simplified setup
  • Built-in tools for enterprise deployments
  • Seamless migration from BizTalk Server 2004

BTS Core Engine:

  • Improved support for large message transformations
  • Processing failed messages
  • Recoverable interchange processing
  • Per-instance pipeline configuration
  • In-order delivery on any send port
  • Flat-file schema generation wizard
  • Calling pipelines from orchestration
  • Engine throttling
  • Granular performance counters
  • Resumable suspension scenarios
  • Event-based configuration changes

Adapters:

  • MSMQ and MQSeries in the box
  • Windows SharePoint Services (WSS) Adapter
  • POP3 Adapter
  • SMTP email composing

Development Tools:

  • Development redeployment
  • Orchestration zoom support
  • Preserving of collapsed shapes in Orchestration Designer

What's New in BizTalk Server 2006

BTS 2006 Core Engine Enhancements

Friday, November 23, 2007

BizTalk Server 2006 (2) BizTalk Server vs WWF

Use BizTalk Server when:

  • Solving an EAI problem
  • B2B services are required
  • BPM services such as BAM are needed
  • A complete management infrastructure and support for increased scalability are necessary

Use WWF when:

  • An application will itself host workflows
  • The business process being implemented requires human workflow
  • The workflow will execute on a client system

Understanding BizTalk Server 2006

BizTalk Server 2006 (1) Intro

What is BizTalk Server (BTS)?

  • Integration Services & Tools

Services and tools include:

  • Messaging and Orchestration
  • Application development
  • Business Rules framework
  • Message activity tracking
  • Web services integration
  • Business activity monitoring
  • Trading partner integration

Why?

  • EAI (Enterprise Application Integration) : BizTalk allows the integration of applications within the same organisation.
  • Integrate your web portals with your organisation's ERP/CRM systems
  • Vendors and business partners: comply with their needs

Security Features:

  • Encryption certificates
  • Signing certificates
  • Integrated logon
  • Kerberos
  • Public Key Infrastructure (PKI)
  • Secure Sockets Layer (SSL)
  • Enterprise Single Sign-On (ESSO): single logon for all the systems, without the need to type your password repeatly
  • Web Services Enhancements (WSE)

Understanding BizTalk Server 2006

BizTalk Server 2006 Security Features

BizTalk Server 2004 (3) Enabling Message Routing



In this lab, you will learn:
  1. Create a Receive Port and a Receive Location
  2. Create Send Ports and Define Message Filters
  3. Start the Send Ports and Test the Configuration

BizTalk Server 2004 (2) Creating a Schema Map







This lab will teach you the following:
  1. Creating a Schema Map using BizTalk Mapper Scenario
  2. Adding Functoids to a Map
  3. Validating and Testing the Map
  4. Building the Schema Map Project





Thursday, November 22, 2007

BizTalk Server 2004 (1) Creating Schemas







I have gone through the lab, it will teach the following:
  1. Creating a New BizTalk Project
  2. Creating an XML Schema using the BizTalk Editor
  3. Promoting Schema Properties
  4. Creating a Flat File Schema using the BizTalk Editor
  5. Validating Schemas and Generating Instance Messages
  6. Assigning a Strong Name to the Assemblies
  7. Building the Schema Project

Tuesday, November 20, 2007

HTTP Handlers and HTTP Modules (1)

HTTP Handlers and HTTP Modules in ASP.NET

<%@ Page language="c#" Codebehind="Index.aspx.cs" AutoEventWireup="True" Inherits="AspnetHttp.ModuleExample.Index" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

<HEAD>

<title>Index</title>

<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">

<meta name="CODE_LANGUAGE" Content="C#">

<meta name="vs_defaultClientScript" content="JavaScript">

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

</HEAD>

<body>

<form id="Index" method="post" runat="server">

<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 178px; POSITION: absolute; TOP: 236px" runat="server" Width="329px" Height="132px" Font-Size="XX-Large">Test Page!</asp:Label>

</form>

</body>

</HTML>



using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace AspnetHttp.ModuleExample

{

public partial class Index : System.Web.UI.Page

{

protected void Page_Load(object sender, System.EventArgs e)

{

//Response.Write(Application["Timer"].ToString());

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

InitializeComponent();

base.OnInit(e);

}

private void InitializeComponent()

{

}

#endregion

}

}



using System;

using System.Web;

using System.Security.Principal;

namespace ModuleExample

{

public class CustomAuthenticationModule : IHttpModule

{

public CustomAuthenticationModule()

{

}

public void Init(HttpApplication r_objApplication)

{

// Register our event handler with Application object.

r_objApplication.AuthenticateRequest += new EventHandler(this.AuthenticateRequest);

}

public void Dispose()

{

}

private void AuthenticateRequest(object r_objSender, EventArgs r_objEventArgs)

{

// Authenticate user credentials, and find out user roles.

HttpApplication objApp = (HttpApplication)r_objSender;

HttpContext objContext = (HttpContext)objApp.Context;

if ((objApp.Request["userid"] == null) (objApp.Request["password"] == null))

{

objContext.Response.Write("Credentials not provided");

objContext.Response.End();

}

string userid = "";

userid = objApp.Request["userid"].ToString();

string password = "";

password = objApp.Request["password"].ToString();

string[] strRoles;

strRoles = AuthenticateAndGetRoles(userid, password);

if ((strRoles == null) (strRoles.GetLength(0) == 0))

{

objContext.Response.Write("We are sorry but we could not find this user id and password in our database");

objApp.CompleteRequest();//end a http request

}

GenericIdentity objIdentity = new GenericIdentity(userid, "CustomAuthentication");

objContext.User = new GenericPrincipal(objIdentity, strRoles);

}

private string[] AuthenticateAndGetRoles(string r_strUserID, string r_strPassword)

{

string[] strRoles = null;

if ((r_strUserID.Equals("aaa")) && (r_strPassword.Equals("111")))

{

strRoles = new String[1];

strRoles[0] = "Administrator";

}

else if ((r_strUserID.Equals("bbb")) && (r_strPassword.Equals("222")))

{

strRoles = new string[1];

strRoles[0] = "User";

}

return strRoles;

}

}

}



<?xml version="1.0"?>

<configuration>

<system.web>

<compilation defaultLanguage="c#" debug="true"/>

<!-- <httpHandlers>

<add verb="*" path="*.apx"

type="MyHandler.NewHandler,MyHandler" />

<add verb="*" path="*"

type="MyHandler.NewHandlerSession,MyHandlerSession" />

</httpHandlers> -->

<httpModules>

<add name=" Test1 " type="ModuleExample.CustomAuthenticationModule, CustomAuthenticationModule"/>

<!-- <add name=" Test " type="TimerModule.TimerModule, TimerModule" />

<add name=" MultiTest1 " type="MultiModuleTest1.Test1Module, MultiModuleTest1" />

<add name=" MultiTest2" type="MultiModuleTest2.Test2Module, MultiModuleTest2" />-->

</httpModules>

<customErrors mode="RemoteOnly"/>

<authentication mode="None"/>

<authorization>

<deny users="?"/>

</authorization>

<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>

<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20"/>

<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>

<xhtmlConformance mode="Legacy"/></system.web>

</configuration>

In this code, we create a http handler to validate user credentials.

Visual Studio 2008 and .NET 3.5 Released

Visual Studio 2008 and .NET 3.5 Released on Mon 19Nov07.

Monday, November 19, 2007

ASP.NET 2.0 Caching (4) Data Caching

<%@ Page Language="vb" %>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<html>

<script runat="server">

Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)

Dim Source As DataView

' try to retrieve item from cache

' if it's not there, add it

Source = Cache("MyDataSet")

If Source Is Nothing Then

Dim MyConnection As SqlConnection

Dim MyCommand As SqlDataAdapter

MyConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("pubsConnectionString").ConnectionString)

MyCommand = New SqlDataAdapter("select * from Authors", MyConnection)

Dim ds As New DataSet

MyCommand.Fill(ds, "Authors")

Source = New DataView(ds.Tables("Authors"))

Cache("MyDataSet") = Source

CacheMsg.Text = "Dataset created explicitly"

Else

CacheMsg.Text = "Dataset retrieved from cache"

End If

MyGrid.DataSource = Source

MyGrid.DataBind()

End Sub

</script>

<body>

<form id="Form1" runat="server">

<h3>

<font face="Verdana">Caching Data</font></h3>

<asp:GridView ID="MyGrid" runat="server">

</asp:GridView>

<p>

<i>

<asp:Label ID="CacheMsg" runat="server" /></i>

</p>

</form>

</body>

</html>

You may find caching data this way is a bit faster than the output caching metioned in the previous posts.

Sunday, November 18, 2007

ASP.NET 2.0 Caching (3) Fragment Caching




<%@ Control Language="VB" ClassName="FragCtrlwithAPI" %>

<%@ OutputCache Duration="60" VaryByControl="pickstate" %>

<script runat="server">

Private duration As TimeSpan

Sub Page_Load(ByVal sender As Object, ByVal E As EventArgs)

If (pickstate.SelectedValue = "CA") Then

duration = New TimeSpan(0, 0, 10)

CachePolicy.Duration = duration

End If

End Sub

Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)

Label1.Text = Now.ToString("G")

Label2.Text = Now.Add(CachePolicy.Duration).ToString("G")

End Sub

</script>

<div style="border: dotted 1px blue; padding: 5px; background-color: #eeeeee;">

<asp:DropDownList ID="pickstate" runat="server" AutoPostBack=true>

<asp:ListItem Text="CA" Value="CA" />

<asp:ListItem Text="UT" Value="UT" />

<asp:ListItem Text="MD" Value="MD" />

<asp:ListItem Text="OR" Value="OR" />

<asp:ListItem Text="MI" Value="MI" />

<asp:ListItem Text="TN" Value="TN" />

</asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"

SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] where state=@state"

ProviderName="System.Data.SqlClient">

<SelectParameters>

<asp:ControlParameter ControlID="pickstate" DefaultValue="CA" Name="state" PropertyName="SelectedValue" />

</SelectParameters>

</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" DataSourceID="sqldatasource1" />

<p>

Control cache starts at <asp:Label ID="Label1" runat="server" Text="Label"/><br />

Control cache expires at <asp:Label ID="Label2" runat="server" Text="Label"/><br />

</p>

</div>



<%@ Page Language="VB" %>

<%@ Register Src="datactrlnew.ascx" TagName="FragCtrl" TagPrefix="acme" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<acme:FragCtrl ID="FragCtrl1" runat="server" />

Current Time:

<%=Now.ToString("G") %>

<asp:Button ID="Button2" runat="server" Text="Refresh" />

</div>

</form>

</body>

</html>

In this code, only the user control is cached, so only the user control will not reflect the changes when you click refresh.

ASP.NET 2.0 Caching (2) Substitution Control

Up to now ASP.NET provided three kinds of caching
1. output-caching to cache a whole page
2. fragment caching to cache a part of a page
3. Data caching

The last post we talked about output caching. In this post, we will talk about one of the application on fragment caching: the Substitution Control.


<%@ Page Language="VB" %>

<%@ OutputCache Duration="60" VaryByParam="none" %>

<script runat="server">

Shared Function GetCurrentDate(ByVal context As HttpContext) As String

Return Now.ToString()

End Function

</script>

<html>

<head id="Head1" runat="server">

<title>Post Cache Substitution</title>

</head>

<body>

<form id="form1" runat="server">

<h4>

This page uses post cache substitution to insert a dynamic value into a cached page.</h4>

<p>

Time:

<%= DateTime.Now.ToString() %>

</p>

<p>

<b>Real Time:

<asp:Substitution ID="Substitution1" runat="server" MethodName="GetCurrentDate" />

</b>

</p>

</form>

</body>

</html>

Cached regions execute only once and are replayed from the cache until the cache expires. Dynamic regions (Substitution control places) execute each time the page is requested.

.NET Framwork Versions



.NET Framework

ASP.NET 2.0 Caching (1) VaryByPostBack



<%@ Page Language="VB" %>

<%@ OutputCache Duration="60" VaryByParam="state" %>

<script runat="server">

Sub page_Load(ByVal sender As Object, ByVal e As EventArgs)

TimeMsg.Text = Now.ToString("G")

End Sub

</script>

<html>

<body>

<form id="Form1" runat="server">

<h3>

<font face="Verdana">Using the Output Cache</font></h3>

<b>Authors by State:</b>

<table cellspacing="0" cellpadding="3" rules="all" style="background-color: #AAAADD;

border-color: black; border-color: black; width: 700px; border-collapse: collapse;">

<tr>

<td>

<a href="varybypostback.aspx?state=CA">CA</a></td>

<td>

<a href="varybypostback.aspx?state=IN">IN</a></td>

<td>

<a href="varybypostback.aspx?state=KS">KS</a></td>

<td>

<a href="varybypostback.aspx?state=MD">MD</a></td>

<td>

<a href="varybypostback.aspx?state=MI">MI</a></td>

<td>

<a href="varybypostback.aspx?state=OR">OR</a></td>

<td>

<a href="varybypostback.aspx?state=TN">TN</a></td>

<td>

<a href="varybypostback.aspx?state=UT">UT</a></td>

</tr>

</table>

<p>

</p>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"

SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] where state=@state">

<SelectParameters>

<asp:QueryStringParameter Name="state" QueryStringField="state" DefaultValue="CA" />

</SelectParameters>

</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" DataSourceID="sqldatasource1" />

<p>

<i>Last generated on:</i>

<asp:Label ID="TimeMsg" runat="server" />

</p>

</form>

</body>

</html>

In this code, when you click the CA link, it will show 'Last generated on: 2007-11-18 10:23:35 ', when you click the IN link the next second, it will show 'Last generated on: 2007-11-18 10:23:36'. Now when you click CA link again, the time is still the same until after 60 seconds, it will refresh the data and the time. Same as all other links.

Two things to note:

1. if there is no caching, then say we have this page called VaryByPostBack.aspx, so if users all over the world are requesting it, the IIS will exexcute all the request and for each request IIS will send back a html to it.

2. if there is caching, for the first request, the IIS will produce a html, and cache it, then within the Duration, the page that all users all over the world requested will be the same html, the IIS is not producing a new html until after the duration.

Friday, November 16, 2007

.NET Remoting (5) Value vs RefObject

using System;

using System.Collections.Generic;

using System.Text;

namespace RemotingSamples

{

public class HelloServer : MarshalByRefObject

{

public HelloServer()

{

Console.WriteLine("HelloServer activated");

}

public String HelloMethod(String name)

{

Console.WriteLine(

"Server Hello.HelloMethod : {0}", name);

return "Hi there " + name;

}

public MySerialized GetMySerialized()

{

return new MySerialized(4711);

}

public MyRemote GetMyRemote()

{

return new MyRemote(4712);

}

}

}

using System;

using System.Collections.Generic;

using System.Text;

namespace RemotingSamples

{

[Serializable]

public class MySerialized

{

public MySerialized(int val)

{

a = val;

}

public void Foo()

{

Console.WriteLine("MySerialized.Foo called");

}

public int A

{

get

{

Console.WriteLine("MySerialized.A called");

return a;

}

set

{

a = value;

}

}

protected int a;

}

public class MyRemote : System.MarshalByRefObject

{

public MyRemote(int val)

{

a = val;

}

~MyRemote()

{

Console.WriteLine("MyRemote destructor");

}

public void Foo()

{

Console.WriteLine("MyRemote.Foo called");

}

public int A

{

get

{

Console.WriteLine("MyRemote.A called");

return a;

}

set

{

a = value;

}

}

protected int a;

}

}


using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels.Http;

namespace RemotingSamples

{

public class Server

{

public static int Main(string [] args)

{

TcpChannel chan1 = new TcpChannel(8085);

HttpChannel chan2 = new HttpChannel(8086);

ChannelServices.RegisterChannel(chan1);

ChannelServices.RegisterChannel(chan2);

RemotingConfiguration.RegisterWellKnownServiceType

(

typeof(HelloServer),

"SayHello",

WellKnownObjectMode.SingleCall

);

System.Console.WriteLine("Press Enter key to exit");

System.Console.ReadLine();

return 0;

}

}

}



using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels.Http;

using System.IO;

namespace RemotingSamples

{

public class Client

{

public static void Main(string[] args)

{

TcpChannel chan1 = new TcpChannel();

ChannelServices.RegisterChannel(chan1);

HelloServer obj1 = (HelloServer)Activator.GetObject(

typeof(RemotingSamples.HelloServer),

"tcp://localhost:8085/SayHello");

if (obj1 == null)

{

System.Console.WriteLine(

"Could not locate TCP server");

}

MySerialized ser = obj1.GetMySerialized();

if (!RemotingServices.IsTransparentProxy(ser))

{

Console.WriteLine("ser is not a transparent proxy");

}

ser.Foo();

MyRemote rem = obj1.GetMyRemote();

if (RemotingServices.IsTransparentProxy(rem))

{

Console.WriteLine("rem is a transparent proxy");

}

rem.Foo();

System.Console.ReadLine();

}

}

}

Thursday, November 15, 2007

.NET Remoting (4) Singleton vs SingleCall

using System;

using System.Collections.Generic;

using System.Text;

namespace RemotingSamples

{

public class HelloServer : MarshalByRefObject

{

public int callCounter = 0;

public HelloServer()

{

Console.WriteLine("HelloServer activated");

}

public String HelloMethod(String name,

out int counter)

{

counter = ++callCounter;

Console.WriteLine(

"Server Hello.HelloMethod : {0} Counter :{1}",

name, callCounter);

return "Hi there " + name;

}

}

}



using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels.Http;

namespace RemotingSamples

{

public class Server

{

public static int Main(string [] args)

{

TcpChannel chan1 = new TcpChannel(8085);

HttpChannel chan2 = new HttpChannel(8086);

ChannelServices.RegisterChannel(chan1);

ChannelServices.RegisterChannel(chan2);

RemotingConfiguration.RegisterWellKnownServiceType

(

typeof(HelloServer),

"SayHello",

WellKnownObjectMode.Singleton

);

System.Console.WriteLine("Press Enter key to exit");

System.Console.ReadLine();

return 0;

}

}

}



using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels.Http;

using System.IO;

namespace RemotingSamples

{

public class Client

{

public static void Main(string[] args)

{

TcpChannel chan1 = new TcpChannel();

ChannelServices.RegisterChannel(chan1);

HelloServer obj1 = (HelloServer)Activator.GetObject(

typeof(RemotingSamples.HelloServer),

"tcp://localhost:8085/SayHello");

if (obj1 == null)

{

System.Console.WriteLine(

"Could not locate TCP server");

}

HttpChannel chan2 = new HttpChannel();

ChannelServices.RegisterChannel(chan2);

HelloServer obj2 = (HelloServer)Activator.GetObject(

typeof(RemotingSamples.HelloServer),

"http://localhost:8086/SayHello");

if (obj2 == null)

{

System.Console.WriteLine(

"Could not locate HTTP server");

}

int counter;

Console.WriteLine(

"Client1 TCP HelloMethod {0} Counter {1}",

obj1.HelloMethod("Caveman1", out counter),

counter);

Console.WriteLine(

"Client2 HTTP HelloMethod {0} Counter {1}",

obj2.HelloMethod("Caveman2", out counter),

counter);

Console.WriteLine(

"Client2 HTTP HelloMethod {0} Counter {1}",

obj2.HelloMethod("Caveman3", out counter),

counter);

Console.ReadLine();

}

}

}

In this code, if WellKnownObjectMode.Singleton then the result will be shown as:

Client1 TCP HelloMethod Caveman1 Counter 1

Client2 HTTP HelloMethod Caveman2 Counter 2

Client2 HTTP HelloMethod Caveman3 Counter 3

if WellKnownObjectMode.SingleCall then the result will be shown as:
Client1 TCP HelloMethod Caveman1 Counter 1
Client2 HTTP HelloMethod Caveman2 Counter 1
Client2 HTTP HelloMethod Caveman3 Counter 1