Thursday, May 31, 2007

Action Catalog.

Conditionally execute code at run time.

example
An application that shows a view in a workspace only if the current user is associated with a specific role.

The action is the code that shows the view.
The condition is the code that determines the user's role.
Developers register an action catalog as a service.

Endpoint Catalog Application Block

add a <section> node to the <configSections>

<configSections>
<section name="Endpoints" type="Microsoft.Practices.SmartClient.EndpointCatalog.Configuration.EndpointSection, Microsoft.Practices.SmartClient.EndpointCatalog" />
</configSections>



Create the application block configuration section

<Endpoints>
<EndpointItems>
<add Name="WebService1" Address="http://default-host.com/WebService1.asmx" UserName="default-user-name" Password="default-password" Domain="default-domain">
</add>
</EndpointItems>
</Endpoints>


create a new EndpointCatalog and add it to a WorkItem
using Microsoft.Practices.SmartClient.EndpointCatalog;
using System.Net;


// Specify the section name in the configuration file.

IEndpointCatalogFactory catalogFactory = new EndpointCatalogFactory("Endpoints");

IEndpointCatalog catalog = catalogFactory.CreateCatalog();

myWorkItem.Services.Add<IEndpointCatalog>(catalog);
Getting an Endpoint Catalog Instance from a WorkItem


Method 1:
public class MyNewClass
{
private EndpointCatalog catalog;

public MyNewClass([ServiceDependency] EndpointCatalog catalog)
{
this.catalog = catalog;
}
...
}
Method 2:
public class MyNewClass
{
private EndpointCatalog catalog;

[ServiceDependency]
public EndpointCatalog EndpointCatalog
{
get { return this.catalog; }
set { this.catalog = value; }
}
...
}
Method 3:
public class MyNewClass
{
private EndpointCatalog catalog;

public MyNewClass()
{
this.catalog = myWorkItem.Services.Get<EndpointCatalog>();
}
...
}

Listing and Getting Information about Endpoints

To check whether an endpoint exists
String epName = "MyWebServiceEndpoint";
if (catalog.EndpointExists(epName))
{
// Endpoint named MyWebServiceEndpoint does exist in the catalog.
}

To get information about an endpoint
// Get the number of endpoints in the catalog.
int endpointCount = catalog.Count;
// Get the address for an endpoint if it exists.
String epName = "MyWebServiceEndpoint";
String epNetworkName = "MyHost";
if (catalog.AddressExistsForEndpoint(epName, epNetworkName))
{
String epAddress
= catalog.GetAddressForEndpoint(epName, epNetworkName);
// Get the credentials for this endpoint.
NetworkCredential epCredentials
= catalog.GetCredentialForEndpoint(epName, epNetworkName);
String epUsername = epCredentials.UserName;

String epPassword = epCredentials.Password;
String epDomain = epCredentials.Domain;
}

Endpoint Catalog Application Block - Config

<Endpoints>
<EndpointItems>
<add Name="WebService1" Address="http://default-host.com/WebService1.asmx" UserName="default-user-name" Password="default-password" Domain="default-domain">
<NetworkItems>
<add Name="Internet" Address="http://internet-host.com/WebService1.asmx"
UserName="internet-user-name" Password="internet-password" />
<add Name="Work" Address="http://work-host.com/WebService1.asmx"
UserName="work-user-name" Password="work-password" />
</NetworkItems>
</add>
<add Name="WebService2" Address="http://default-host.com/WebService2.asmx" UserName="default-user-name" Password="default-password" Domain="default-domain">
<NetworkItems>
<add Name="Internet" Address="http://internet-host.com/WebService2.asmx"
UserName="internet-user-name" Password="internet-password" />
</NetworkItems>
</add>
</EndpointItems>
</Endpoints>

Disconnected Service Agent Application Block

add references to the following assemblies:
Microsoft.Practices.SmartClient.DisconnectedAgent
Microsoft.Practices.SmartClient.EnterpriseLibrary

Initializing the Request Manager
  1. Invoke any of the two overloads of the static method Initialize.

    // for default database that specified in the Data Access Application Block configuration.
    RequestManager requestManager = DatabaseRequestManagerIntializer.Initialize();

    OR

    RequestManager requestManager = DatabaseRequestManagerIntializer.Initialize("databaseName");


  2. To full control over the objects used to initialize the request manager, manually construct the objects and call the Initialize method

  1. EndpointCatalogFactory catalogFactory = new EndpointCatalogFactory("Endpoints");
    catalog = catalogFactory.CreateCatalog();

    SmartClientDatabase requestQueueDb = new
    SmartClientDatabase(ConfigurationManager.ConnectionStrings["QueueConnectionString"].ConnectionString);

    DatabaseRequestQueue requestQueue = new DatabaseRequestQueue(requestQueueDb, "RequestsQueue");

    SmartClientDatabase deadLetterQueueDb = new SmartClientDatabase(ConfigurationManager.ConnectionStrings["QueueConnectionString"].ConnectionString);

    DatabaseRequestQueue deadLetterQueue = new
    DatabaseRequestQueue(deadLetterQueueDb, "DeadLetterQueue");

    ConnectionMonitorAdapter adapter = new ConnectionMonitorAdapter(ConnectionMonitorFactory.CreateFromConfiguration());

    RequestManager manager = RequestManager.Instance;

    manager.Initialize(requestQueue, deadLetterQueue, adapter, catalog);

Creating a Simple Request
Request req = new Request();
req.MethodName = "DeliveryRouteUpdate";
req.Endpoint = "MyWebServiceHost";
specify the online proxy type for the request. The proxy class is the one that Visual Studio generates when you add a Web reference to your project.
req.OnlineProxyType = typeof(MyWebServiceProxy);
specify the behavior of the request
behavior.ProxyFactoryType = typeof(WebServiceProxyFactory);
other OfflineBehavior properties are Tag, MaxRetries, Stamps

Adding Parameters to a Request
int customerCode = 1234;
string comment = "New value for comment";
req.CallParameters = CallParameters.ToArray(customerCode, comment);
Handling Callbacks for a Request
req.Behavior.ReturnCallback
= new CommandCallback(typeof(MyDisconnectedServiceAgentCallbackClass),
"MyReturnCallbackMethod");

req.Behavior.ExceptionCallback
= new CommandCallback(typeof(MyDisconnectedServiceAgentCallbackClass),
"MyExceptionCallbackMethod");
method that takes references to the Request, an Object array for the parameters (arguments) you submitted to the service, and an Object for any value returned by the Web service.
public void MyReturnCallbackMethod(Request req, Object[] qParams,
Object result)
{
MessageBox.Show("Request succeeded. Return value is: "
+ result.ToString());
}


public OnExceptionAction MyExceptionCallbackMethod(Request req,
Exception ex)
{
MessageBox.Show("Your request failed with error: " + ex.Message);
return OnExceptionAction.Dismiss;
}



Adding a Request to a Queue
requestManager.RequestQueue.Enqueue(req);
Removing a Request from a Queue
requestManager.DeadLetterQueue.Remove(req)
Accessing Requests in a Queue
IRequestQueue theQueue = requestManager.RequestQueue;
// or:
IRequestQueue theQueue = requestManager.DeadLetterQueue;

// Count the number of requests in the queue.
Int32 queueCount = theQueue.GetCount();
// Get a reference to the next request in the queue.
Request nextRequest = theQueue.GetNextRequest();
// Get all the requests in the queue.
IEnumerable>Request> requests = theQueue.GetRequests();
// Get single request iterator by request ID.
Request requestById = theQueue.GetRequest(requestId);
// Get all the requests that have a specified Tag property value.
IEnumerable>Request> requestsByTag = theQueue.GetRequests("SalesOrder");
// Get all the requests that have a specified "stamps" value
// that is greater than or equal to a specified numerical value.
IEnumerable>Request> requestsByPrice = theQueue.GetRequests(5);

To remove a request from the queue, pass a reference to that request to the Remove method of the queue.
theQueue.Remove(req);
Dispatching a Single Request Immediately
requestManager.RequestQueue.Enqueue(req);
requestManager.DispatchRequest(req);

Dispatching All Pending Requests
requestManager.DispatchAllPendingRequests();
Dispatching Specific Pending Requests
requestManager.DispatchPendingRequestsByTag("Sales Order");
Starting and Stopping the Dispatcher Service
if (requestManager.Running)
{
reqManager.StopAutomaticDispatch();

OR

reqManager.StartAutomaticDispatch();
}




Conclustion

RequestManager requestManager = DatabaseRequestManagrerInitializer.Initialize();

Request req = new Request();
req.MethodName = "DeliveryRouteUpdate";
req.EndPoint = "MyWebServiceHost";
req.OnlineProxyType = typeof(MyWebServiceProxy);
behavior.ProxyFactoryType = typeof(WebServiceProxyFactory);

int customerCode =1234;
string comment = "New value for cooment";
req. Callparametars=CallParameters.ToArray(customerCode,Comment);

requestManager.RequestQueue.Enqueue(req);
requestManager.DispatchRequest(req);

Wednesday, May 30, 2007

Connection Monitor Application Block

Configure the Connection Monitor Application Block
add a <section> node to the <configSections>
<configSections>
<section name="ConnectionMonitor" type="Microsoft.Practices.SmartClient.ConnectionMonitor.Configuration.ConnectionSettingsSection, Microsoft.Practices.SmartClient.ConnectionMonitor" />
</configSections>
To use the Connection manager Application Block,
Add configuration information to the application configuration file.
It defines the logical networks and physical network adapters that you want to monitor.
<ConnectionMonitor>
<Networks>
<add Name="Intranet" Address="http://contoso"/>
<add Name="Internet" Address="http://www.microsoft.com"/>
</Networks>
<Connections>
<add Type="WiredConnection" Price="1"/>
</Connections>
</ConnectionMonitor>

Instantiate the ConnectionMonitor service and store it in a WorkItem

Call the static CreateFromConfiguration method of the ConnectionMonitorFactory class.

// Use the default section name "ConnectionMonitor."
ConnectionMonitor sampleMonitor
= ConnectionMonitorFactory.CreateFromConfiguration();

// Instead, you can specify the section name in the configuration file.
String configurationName = "SampleConnectionSection";
ConnectionMonitor sampleMonitor
= ConnectionMonitorFactory.CreateFromConfiguration(configurationName);

Add the ConnectionMonitor instance to the Services collection of your WorkItem
myWorkItem.Services.Add(sampleMonitor);
if (sampleMonitor.Connections.Contains("Internet"))
{
// Check the connection status.
Connection conn = sampleMonitor.Connections["Internet"];
if (!conn.IsConnected)
{
}

Get a reference to the Connection Monitor service from another class

  1. use a [ServiceDependency] attribute on a parameter of the class constructor to accept an injected reference
    public class MyNewClass
    {
    private ConnectionMonitor sampleMonitor;
    public MyNewClass([ServiceDependency] ConnectionMonitor cm)
    {
    this.sampleMonitor = cm;
    }
    ...
    }

  2. Expose a public property for the ConnectionMonitor
    public class MyNewClass
    {
    private ConnectionMonitor sampleMonitor;
    [ServiceDependency]
    public ConnectionMonitor ConnectionMonitor
    {
    get { return this.sampleMonitor; }
    set { this.sampleMonitor = value; }
    }
    ...
    }

  3. Query the Services collection of the WorkItem to obtain a reference to the service
    public class MyNewClass
    {
    private ConnectionMonitor sampleMonitor;
    public MyNewClass();
    {
    this.sampleMonitor = myWorkItem.Services.Get<ConnectionMonitor>();
    }
    ...
    }


Detect and handle changes to networks and connectivity

1. Connect your event handler to the StateChanged event of the Connection or Network
conn.StateChanged += StateChangeHandler;
netwk.StateChanged += StateChangeHandler;
2. Network and the Connection classes both raise a StateChanged event when their state changes.
public void StateChangeHandler(object sender, StateChangedEventArgs e)
{
if (e.IsConnected)
{ MessageBox.Show("Now connected"); }

}

3. The Connection class exposes a method named UpdateStatus that you can call to raise the StateChanged event and obtain information through your event handler on the connectivity status
conn.UpdateStatus();

Creating Connections and Networks.


Create a new connection instance
// Create a new NicConnection instance.
NicConnection conn = new NicConnection("NicConnection", 6);
Use the Add method of the ConnectionCollection class
// Add it to the ConnectionMonitor Connections collection.
sampleMonitor.Connections.Add(conn);
It can also use the other methods of the KeyedCollection and Collection classes to check for the presence of a specific connection
// See if a connection named Internet exists.
if (sampleMonitor.Connections.Contains("Internet"))
{
// Check the connection status.
Connection conn = sampleMonitor.Connections["Internet"];
if (!conn.IsConnected)
{
// Display the price and remove it from the Connections collection.
MessageBox.Show("Removing connection with price "
+ conn.Price.ToString());
sampleMonitor.Connections.Remove(conn);
}
}

Tuesday, May 29, 2007

Stage 4: Creating and Showing the SmartPart

create an interface for the view and the presenter to communicate

Create a Interface named IMyView.cs in the MyModule project and change as .
public interface IMyView
{
event EventHandler Load;
string Message { get; set; }
}
Create a SmartPart user control
  1. add a User Control named MyView.cs
  2. Drag a Label control.
  3. Implement the IMyView interface
    1. add IMyView interface t othe class MyView
      public partial class MyView : UserControl, IMyView
    2. right-click IMyView and click Implement Interface, then click Implement Interface in the fly-out menu.
    3. modify property for Message in Interface.
public string Massage
{
get { return this.label1.Text;}
set { this.label1.Text = value;}
}
    Create the presenter class
    1. Create a class named MyPresenter.cs
    2. add a variable of type IMyView
      public class MyPresenter
      {
      IMyView view;
    3. Create a contructor for the class
      public MyPresenter(IMyView view)
      {
      this.view = view;
      view.Load += new EventHandler(view_Load);
      }
    4. Create a event handler for the Load event
    void view_Load(object sender, EventArgs e)
    {
    view.Message = "Hello World from a Module";
    }
    get a reference to the WorkItem
    1. Open the MyModuleInit.cs add the following after the myCatalogService declaration.
      The variable will contain a reference to the root ShellWorkItem
      private WorkItem parentWorkItem;
      [ServiceDependency]
      public WorkItem ParentWorkItem
      {
      set { parentWorkItem = value; }
      }
    2. Modify the load method.
      public override void Load()
      {
      base.Load();
      MyWorkItem myWorkItem =
      parentWorkItem.WorkItems.AddNew<MyWorkItem>();
      myWorkItem.Run(parentWorkItem.Workspaces["tabWorkspace1"]);
      }

    Create and show the view

    1. In MyWorkItem.cs, add
      using Microsoft.Practices.CompositeUI.SmartParts;
    2. Create a public Run method that accepts as a parameter a reference to the TabWorkspace.
      public void Run(IWorkspace TabWorkspace)
      {
      IMyView view = this.Items.AddNew<MyView>();
      MyPresenter presenter = new MyPresenter(view);
      this.Items.Add(presenter);
      TabWorkspace.Show(view);
      }

    Stage 3: Adding the TabWorkspace

    1. Drag a SplitContainer control onto the form ShellForm.cs .

    2. Right-click the Toolbox, click Items..., and then click Browse.....
      In the \Src\CS\CompositeUI.WinForms\bin\Debug\ subfolder of the folder where you installed the CAB files, select the file Microsoft.Practices.CompositeUI.WinForms.dll.

    3. Drag a TabWorkspace onto the form and drop it onto the left-hand panel of the SplitContainer control.