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.
Thursday, May 31, 2007
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
Method 1:
Listing and Getting Information about Endpoints
To check whether an endpoint exists
To get information about an endpoint
<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;Getting an Endpoint Catalog Instance from a WorkItem
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);
Method 1:
public class MyNewClassMethod 2:
{
private EndpointCatalog catalog;
public MyNewClass([ServiceDependency] EndpointCatalog catalog)
{
this.catalog = catalog;
}
...
}
public class MyNewClassMethod 3:
{
private EndpointCatalog catalog;
[ServiceDependency]
public EndpointCatalog EndpointCatalog
{
get { return this.catalog; }
set { this.catalog = value; }
}
...
}
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">
<add Name="WebService2" Address="http://default-host.com/WebService2.asmx" UserName="default-user-name" Password="default-password" Domain="default-domain">
</EndpointItems>
</Endpoints>
<EndpointItems>
<add Name="WebService1" Address="http://default-host.com/WebService1.asmx" UserName="default-user-name" Password="default-password" Domain="default-domain">
<NetworkItems></add>
<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 Name="WebService2" Address="http://default-host.com/WebService2.asmx" UserName="default-user-name" Password="default-password" Domain="default-domain">
<NetworkItems></add>
<add Name="Internet" Address="http://internet-host.com/WebService2.asmx"
UserName="internet-user-name" Password="internet-password" />
</NetworkItems>
</EndpointItems>
</Endpoints>
Disconnected Service Agent Application Block
add references to the following assemblies:
Initializing the Request Manager
Creating a Simple Request
Adding Parameters to a Request
Adding a Request to a Queue
To remove a request from the queue, pass a reference to that request to the Remove method of the queue.
Microsoft.Practices.SmartClient.DisconnectedAgent
Microsoft.Practices.SmartClient.EnterpriseLibrary
Initializing the Request Manager
- 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"); - To full control over the objects used to initialize the request manager, manually construct the objects and call the Initialize method
- 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();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.MethodName = "DeliveryRouteUpdate";
req.Endpoint = "MyWebServiceHost";
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;Handling Callbacks for a Request
string comment = "New value for comment";
req.CallParameters = CallParameters.ToArray(customerCode, comment);
req.Behavior.ReturnCallbackmethod 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.
= new CommandCallback(typeof(MyDisconnectedServiceAgentCallbackClass),
"MyReturnCallbackMethod");
req.Behavior.ExceptionCallback
= new CommandCallback(typeof(MyDisconnectedServiceAgentCallbackClass),
"MyExceptionCallbackMethod");
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);Dispatching All Pending Requests
requestManager.DispatchRequest(req);
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>
Add configuration information to the application configuration file.
It defines the logical networks and physical network adapters that you want to monitor.
Instantiate the ConnectionMonitor service and store it in a WorkItem
Call the static CreateFromConfiguration method of the ConnectionMonitorFactory class.
Add the ConnectionMonitor instance to the Services collection of your WorkItem
Get a reference to the Connection Monitor service from another class
Detect and handle changes to networks and connectivity
1. Connect your event handler to the StateChanged event of the Connection or Network
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
Creating Connections and Networks.
Create a new connection instance
add a <section> node to the <configSections>
<configSections>To use the Connection manager Application Block,
<section name="ConnectionMonitor" type="Microsoft.Practices.SmartClient.ConnectionMonitor.Configuration.ConnectionSettingsSection, Microsoft.Practices.SmartClient.ConnectionMonitor" />
</configSections>
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
- 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;
}
...
} - 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; }
}
...
} - 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;2. Network and the Connection classes both raise a StateChanged event when their state changes.
netwk.StateChanged += StateChangeHandler;
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.Use the Add method of the ConnectionCollection class
NicConnection conn = new NicConnection("NicConnection", 6);
// Add it to the ConnectionMonitor Connections collection.It can also use the other methods of the KeyedCollection and Collection classes to check for the presence of a specific connection
sampleMonitor.Connections.Add(conn);
// 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 .
Create and show the view
Create a Interface named IMyView.cs in the MyModule project and change as .
public interface IMyViewCreate a SmartPart user control
{
event EventHandler Load;
string Message { get; set; }
}
- add a User Control named MyView.cs
- Drag a Label control.
- Implement the IMyView interface
- add IMyView interface t othe class MyView
public partial class MyView : UserControl, IMyView
- right-click IMyView and click Implement Interface, then click Implement Interface in the fly-out menu.
- modify property for Message in Interface.
public string Massage
{
get { return this.label1.Text;}
set { this.label1.Text = value;}
}
- Create a class named MyPresenter.cs
- add a variable of type IMyView
public class MyPresenter
{
IMyView view; - Create a contructor for the class
public MyPresenter(IMyView view)
{
this.view = view;
view.Load += new EventHandler(view_Load);
} - Create a event handler for the Load event
get a reference to the WorkItemvoid view_Load(object sender, EventArgs e)
{
view.Message = "Hello World from a Module";
}
- Open the MyModuleInit.cs add the following after the myCatalogService declaration.
The variable will contain a reference to the root ShellWorkItemprivate WorkItem parentWorkItem;
[ServiceDependency]
public WorkItem ParentWorkItem
{
set { parentWorkItem = value; }
} - 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
- In MyWorkItem.cs, add
using Microsoft.Practices.CompositeUI.SmartParts;
- 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
- Drag a SplitContainer control onto the form ShellForm.cs .
- 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. - Drag a TabWorkspace onto the form and drop it onto the left-hand panel of the SplitContainer control.
Subscribe to:
Posts (Atom)