Feeds:
Posts
Comments

The Simplicity of Complexity – The Mandelbrot Set

The MANDELBROT SET is the most complex object in mathematics, its admirers like to say. An eternity would not be enough time to see it all, its disks studded with prickly thorns, its spirals and filaments curling outward and around, bearing bulbous molecules that hang, infinitely variegated, like grapes on God’s personal vine – James Gleick in Chaos, Making a New Science.

This project was a brief exploration into the mind-boggling and beautiful world of mathematical complexity, by way of the most famous example of fractal geometry, called the Mandelbrot set. Because of the VisualBots built-in color graphics and user-defined coordinate system features, it is actually quite easy to explore this amazing object.

Above are various windows in the complex plane, rendering the Mandelbrot fractal using the built-in graphics capabilities of the VisualBots simulator.

Background

The Mandelbrot set was named after the work of mathematician Benoit Mandelbrot in the 1980′s, who was one of the early researchers in the field of dynamic complexity. The Mandelbrot set has a fractal-like geometry, which means that it exhibits self-similarity at multiple scales. However, the small-scale details are not identical to the whole, and in fact, the set is infinitely complex, revealing new geometric surprises at ever increasing magnification. Belying this mind-boggling complexity is the extremely simple mathematic process used to produce it.

The Mandelbrot set is a set of complex numbers (remember in algebra – the points in the 2D complex plane with real and imaginary axes?). Every complex number is either in the set, or outside of it. The set is generated by applying a simple iterative process to each complex number. In mathematical jargon, it is defined by all of the complex numbers C for which the number sequence

is bounded, or does not tend towards infinity.

In other words, to generate the set, take a complex number, multiply it by itself, and add it to the original number; take that result, multiply it by itself, and add it to the original number; and so on. If the resulting numbers generated during the iteration process grows ever and ever larger, then the original complex number C is not in the Mandelbrot set. If the sequence converges, drifts chaotically, or cycles periodically, then C is in the set. Of course in practice we cannot apply the iteration process an infinite number of times to be sure that C is a member of the set. So instead, the process is applied several hundred or several thousand times, and if the sequence remains relatively small during these iterations, then it is assumed that C is probably a member of the set. Fortunately, there is a very useful criteria for detecting divergence – it can be demonstrated mathematically that if during the iteration process the number sequence exceeds the absolute value of 2, then the sequence will diverge to infinity and the original number C is definitely outside of the set. Many points reach a value that exceeds 2 after only a few iterations.

The typical means of graphically rendering the Mandelbrot fractal is to color points in the complex plane that belong to the set as black, and all other points outside of the set according to how quickly they diverge towards infinity. The speed at which points outside of the set diverge, sometimes referred to as “escape speed”, is measured by how many iterations of the number sequence are required until divergence is detected.

It turns out that the Mandelbrot set lives very close to the origin of the complex plane, within a radius of 2. The most interesting regions are found near the boundaries of the set, where the escape speeds are relatively higher than those farther away. Zooming down into these regions exposes a remarkable variation of self-similar structures.

In the Mandelbrot set, nature (or is it mathematics) provides us with a powerful visual counterpart of the musical idea of ‘theme and variation’: the shapes are repeated everywhere, yet each repetition is somewhat different. It would have been impossible to discover this property of iteration if we had been reduced to hand calculation, and I think that no one would have been sufficiently bright or ingenious to ‘invent’ this rich and complicated theme and variations. It leaves us no way to become bored, because new things appear all the time, and no way to become lost, because familiar things come back time and time again. Because this constant novelty, this set is not truly fractal by most definitions; we may call it a borderline fractal, a limit fractal that contains many fractals. Compared to actual fractals, its structures are more numerous, its harmonies are richer, and its unexpectedness is more unexpected – Benoit Mandelbrot.
Above is the highest-elevation view of the Mandelbrot set (the portions colored black). The set does not extend beyond a radius of 2 in the complex plane.

One amazing aspect of the Mandelbrot set that was proved by Hubbard and Douady of the University of Paris, is that it is connected, meaning that there are no islands of points in the set that are isolated from the rest. Many apparently isolated “molecules” of the set can be observed at high magnification, but the appearance is deceiving, because each of these are connected to the rest of the set by very thin filaments. Other interesting aspects are that the perimeter of the set has an infinite length, and that its area is unknown.

VisualBots Implementation

The algorithm for generating the Mandelbrot fractal is very simple:

1. Cycle through all screen pixels, converting each to its respective complex plane coordinates
2. Determine whether or not the pixels are in the Mandelbrot set
3. If they are in the set, color black, otherwise color based on their escape speed

The following pseudo code renders a specified window in the complex plane:

Set the screen coordinate system to bracket the window of interest
Color the screen background black
maxiter=1000 (setting maxiter to smaller value trades-off resolution for computational speed)
For each screen pixel do the following:
R0 = calculate the real coordinate of pixel
I0 = calculate the imaginary coordinate of pixel
R = R0
I = I0
R2 = R * R
I2 = I * I
iter = 0
While (R2 + I2 < 4) And (iter < maxiter) Do:
I = 2 * R * I + I0
R = R2 – I2 + R0
R2 = R * R
I2 = I * I
iter = iter + 1
Loop
If iter < maxiter Then
color the pixel according to value of iter
End If
Next screen pixel

To assign color to each screen pixel, we created a single Bot object, gave it a point shape, and set its Footprint property to True. With this combination of settings, the Bot imparts a “footprint” of color as it is moved from pixel to pixel. The color of the footprint is calculated using the FillColorPick method of the Bot object, which selects a entry point into the assigned ColorTable based on a variable, in this case, “iter”.

What is MVVM?

MVVM is the most popular architectural pattern used in Windows Presentation Foundation (WPF) and Silverlight. It is designed to make use of specific functions in WPF/Silverlight to better facilitate the separation of View layer development from the rest of the pattern by removing virtually all “code behind” from View layer, taking advantage of Binding Markup Extension from XAML. This separation of roles allows interactive designers to focus on UX needs rather than programming or business logic, allowing for the layers of an application to be developed in multiple work streams.

A MVVM solution consist View as pure XAML with default code-behind implementation. A View Model is declared and initiated somewhere in the XAML with detailed bindings to its properties and commands. Left with Models as the data presentation classes managed by ViewModels.

Now we know that Views should be in pure XAML, and Models are just classes that represent the real state of data. Hence, what is actually in the ViewModel?

To create a ViewModel, we need expose properties and commands required by a View, notify the binding framework when a property needs to reflected in the View, and manage the data underneath.

Exposing Properties and Commands via ViewModel

A ViewModel is responsible for establishing properties required by View from a Model. Say we have a table containing a list of greetings in different languages.

  • English, Hello
  • Taiwanese(Hokkien), Li-ho
  • Mandarin, nǐ hǎo

The model will look like this:

public class Greeting
{
public string LanguageName {get;set;}
public string Dialogue {get;set;}
}

A ViewModel that makes this model available to a view will look like this:

public class GreetingViewModel : System.ComponentModel.INotifyPropertyChanged
{
/// <summary>
/// Implement the INotifyPropertyChanged interface (preferred).
/// For change notification to occur in a binding between a bound client and a data source.
/// </summary>
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public string LanguageName
{
get{return _model.LanguageName; }
set
{
_model.LanguageName = value;
if(PropertyChanged != null)
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("LanguageName"));
}
}
public string Dialogue
{
get{return _model.Dialogue;}
set
{
_model.Dialogue = value;
if(PropertyChanged != null)
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Dialogue"));
}
}
}

Notice that in the ViewModel we implement INotifyPropertyChanged? The aim is to notify the binding framework when a property is updated via the set method, the property will then be reflected in the View without extra effort.

Exposing an property in ViewModel seems to be fairly straight forward. One improvement you might make is to write a method to assist the notification. You will find other advance extension that some nice people have came up on the World Wide Web.

/// <summary>
/// Implement the INotifyPropertyChanged interface (preferred).
/// For change notification to occur in a binding between a bound client and a data source.
/// </summary>
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
public string LanguageName
{
get { return _model.LanguageName; }
set
{
_model.LanguageName = value;
NotifyPropertyChanged("LanguageName");
}
}
public string Dialogue
{
get { return _model.Dialogue; }
set
{
_model.Dialogue = value;
NotifyPropertyChanged("Dialogue");
}
}

Now we have a simple ViewModel, let us look at how we would bind it onto XAML.

<UserControl.Resources>
<vm:GreetingViewModel x:Key="VM"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource VM}">
<StackPanel>
<TextBlock FontWeight="Bold" Text="{Binding Dialogue, Mode=OneWay}"/>
<TextBox Text="{Binding LanguageName, Mode=TwoWay}"/>
</StackPanel>
</Grid>

For more information on Binding visit Binding Markup Extension.

Stores Procedure

A stored procedure is a subroutine available to applications accessing a relational database system. Stored procedures (sometimes called a proc, sproc, StoPro, StoredProc, or SP) are actually stored in the database data dictionary.

Typical uses for stored procedures include data validation (integrated into the database) or access control mechanisms. Furthermore, stored procedures are used to consolidate and centralize logic that was originally implemented in applications. Large or complex processing that might require the execution of several SQL statements is moved into stored procedures, and all applications call the procedures only.We can use nested stored procedures, by executing one stored procedure in another. The maximum level of nesting is 32. [1]

Stored procedures are similar to user-defined functions (UDFs). The major difference is that UDFs can be used like any other expression within SQL statements, whereas stored procedures must be invoked using the CALL statement [2]

CALL procedure(…)

or

EXECUTE procedure(…)

Stored procedures may return result sets, i.e. the results of a SELECT statement. Such result sets can be processed using cursors by other stored procedures by associating a result set locator, or by applications. Stored procedures may also contain declared variables for processing data and cursors that allow it to loop through multiple rows in a table. The standard Structured Query Language provides IF, WHILE, LOOP, REPEAT, CASE statements, and more. Stored procedures can receive variables, return results or modify variables and return them, depending on how and where the variable is declared.

Comparison with dynamic SQL

Overhead: Because stored procedure statements are stored directly in the database, this may remove all or part of the compilation overhead that is typically required in situations where software applications send inline (dynamic) SQL queries to a database. (However, most database systems implement “statement caches” and other mechanisms to avoid repetitive compilation of dynamic SQL statements.) In addition, pre-compiled SQL statements, while avoiding some overhead, add to the complexity of creating an optimal execution plan because not all arguments of the SQL statement are supplied at compile time. Depending on the specific database implementation and configuration, mixed performance results will be seen from stored procedures versus generic queries or user defined functions.

Avoidance of network traffic: A major advantage with stored procedures is that they can run directly within the database engine. In a production system, this typically means that the procedures run entirely on a specialized database server, which has direct access to the data being accessed. The benefit here is that network communication costs can be avoided completely. This becomes particularly important for complex series of SQL statements.

Encapsulation of business logic: Stored procedures allow for business logic to be embedded as an API in the database, which can simplify data management and reduce the need to encode the logic elsewhere in client programs. This may result in a lesser likelihood of data becoming corrupted through the use of faulty client programs. Thus, the database system can ensure data integrity and consistency with the help of stored procedures.

Delegation of access-rights: In many systems, stored-procedures can be granted access rights to the database which the users who will execute those procedures do not directly have. Thus, the stored procedure becomes the only way that these users have, to do whatever the stored procedure does.

Some protection from SQL injection attacks: Stored procedures can be used to protect against this attack. The parameters will be treated as data even if an attacker inserts SQL commands. Also some DBMS will check the parameter’s type.

Comparison with functions

  • A function is a subprogram written to perform certain computations and return a single value.
  • Functions must return a value (using the RETURN keyword), but for stored procedures this is not compulsory.
  • Stored procedures can use RETURN keyword but without any value being passed.
  • Functions could be used in SELECT statements, provided they don’t do any data manipulation. However, procedures cannot be included in SELECT statements.
  • A function can have only IN parameters, while stored procedures may have OUT or INOUT parameters.
  • A stored procedure can return multiple values using the OUT parameter or return no value at all.

Disadvantages

Stored procedures are “defined once, used many times.” If any changes are necessary, the (one and only one) definition of the stored procedure must be replaced. Dynamic SQL, of course, allows any SQL query to be issued at any time. Any change to a stored procedure instantly impacts every other piece of software, report, etc. (inside or outside of the DBMS) which directly or indirectly refers to it. It is not always possible to determine with certainty exactly what those impacts will be, nor what changes can safely be made without adversely impacting something else.

For various reasons, many organizations strictly limit who is allowed to define and issue a query against the database. Programmers and other users may therefore find themselves having no choice but to implement inefficient solutions to their problems using what stored procedures are available to them, whether or not the procedures are appropriate for this particular ancillary task.

Though not directly related to stored procedures, the movement of business logic to the DBMS is problematic since it is the layer with the more complex scalability issues. Furthermore, some modern DBMS systems (notably from Microsoft SQL Server 2000 onwards) don’t offer any performance benefits of using stored procedures against precompiled queries: they are compiled and cached in the same manner as dynamic SQL.

Introduction

It is very important to understand ASP.NET page life cycle for many reasons, mainly for understanding where we should place particular methods and when we should set page related properties. Additionally if we are developing custom server controls then clear understanding of page life cycle is very useful to correct initialization of control, setting properties with view-state data, and control’s code(Control events are subject to ASP.NET page only)

Page life cycle depends on whether it is requested for the first time or it is after postback(page request of itself) and finalize to the web server. When a web page is requested to web server, it goes through a series of sequence of steps/events (like initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering) before it returned back to the web browser.

When we use and manipulate page life cycle events correctly then it becomes a handy and powerful tool for developing web applications.

Background

IIS : It is default web server with Microsoft .NET. Internet Information Server helps to deploy web sites/web application. IIS web server receives request for a web resource (file), it checks the extension of the file (e.g. .aspx, ascx, .ashx and .asmx) and then it determines which ISAPI extension should handle this request and passes this request to proper ISAPI extension

ASPNET_ISAPI.DLL : IIS loads this DLL and sends the page request to this DLL. This DLL loads the HTTPRuntime for further processing.

ASPNET_WP.EXE: It contains an Application Pool. Each Application Pool can contain any number of Applications. Application Pool is also called as AppDomain. When a web page is requested, IIS looks for the application pool under which the current application is running and forwards the request to the respective worker process.

Explanation

General Page Life Cycle Stages Each and every time the browser sends the request, page instance is created. HTTP runtime invokes ProcessRequest and starts page execution.

Table showing stage and corresponding Events

Stage Events/Method
Initialization of the page Page_Init
Loading of the View State LoadViewState
processing of the Post back data LoadPostData
Loading of Page Page_Load
Notification of PostBack RaisePostDataChangedEvent
Handling of PostBack Event RaisePostBackEvent
Pre Rendering of Page Page_PreRender
Saving of view state SaveViewState
Rendering of Page Page_Render
Unloading of the Page Page_UnLoad
Setting up of the page

ASP.NET determines that the page request by a user requires to be parsing and compiling or to render cached copy of the page to be send. Thus it comes very much before of the beginning of the page life cycle. After this, it is also checked that request is a normal request, postback, cross-page postback or callback. The page constructor creates a tree of controls as soon as the HTTP runtime instantiates the page class to perform the request

Events

PreInit

This event is the beginning of the page life cycle. Every page controls are initialized and the properties are set according to aspx source code.

  • Possible to Change or set Master page, Themes
  • Creates or re-creates dynamic controls.
  • Reads or sets Profile property values.

Init

First, the Init event for the Page object occurs, then Init event occurs for each control on the Page. Viewstate information is not available at this stage.

  • Controls have been initialized zed
  • Theme skins applied if any.
  • Initialize control properties.


InitComplete

This event is used to processing tasks that require all initialization be complete.

PreLoad

This event is used before Perform any processing that should occur before Load. Use this event if you need to perform processing on your page or control before the Load event. Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load

Set properties in controls and establish database connections

Control Events

These are control specific events such as – Button Click, DropDownIndexChanged etc.

Load Complete

This event is used for performing those tasks which require load has been completed.

PreRender

In this event page insures that all child controls are created. Page calls EnsureChildControls for all controls, including itself. Every controls whose datasource/databind property is set calls for its databind method.

SaveStateComplete

This event occurs after viewstate encoded and saved for the page and for all controls.

Render

Every ASP.NET control has render method and the page instance calls this method to output the control’s markup, after this event any changes to the page or controls are ignored.

Unload

Unload event used to do cleanup task like closing the database connections, closing of the open files, completing logging or other requested tasks. Unload events occurs for each control on page control tree first and after that page.

Silverlight
Composite Web Apps With Prism
Kiran Salke
Code download available from the MSDN Code Gallery
Browse the Code Online
This article discusses:

  • Silverlight 2
  • Application composition
  • Dependency injection
This article uses the following technologies:
Silverlight 2, Prism
Your first experience with Silverlight was probably something small: a video player, a simple charting application, or even a menu. These types of applications are simple and straightforward to design, and segmenting them into rigorous layers with separate responsibilities is overkill.
Problems surface, however, when you try to apply a tightly coupled style to large applications. As the number of moving parts grows, the simple style of application development falls apart. Part of the remedy is layering (see my article “Model-View-ViewModel In Silverlight 2 Apps“), but a tightly coupled architecture is just one of a number of problems that need to be solved in large Silverlight projects.
In this article, I show you how to build an application using the composition techniques of the Composite Application Library from the Prism project. The example I develop is a simple editor of database data.
As requirements change and a project matures, it is helpful if you can change parts of the application without having these changes cascade throughout the system. Modularizing an application allows you to build application components separately (and loosely coupled) and to change whole parts of your application without affecting the rest of the code.
Also, you might not want to load all the pieces of your application at once. Imagine a customer management application in which users log on and can then manage their prospect pipeline as well as check e-mail from any of their prospects. If a user checks e-mail several times a day but manages the pipeline only every day or two, why load the code to manage the pipeline until it is needed? It would be great if an application supported on-demand loading of parts of the application, a situation that can be addressed by modularizing the application.
The patterns & practices team at Microsoft created a project called Prism (or CompositeWPF) that is meant to address problems like these for Windows Presentation Foundation (WPF) applications, and Prism has been updated to support Silverlight as well. The Prism package is a mix of framework and guidance for building applications. The framework, called the Component Application Library (CAL), enables the following:
  • Application modularity: Build applications from partitioned components.
  • UI composition: Allows loosely coupled components to form user interfaces without discrete knowledge of the rest of the application.
  • Service location: Separate horizontal services (for example, logging and authentication) from vertical services (business logic) to promote clean layering of an application.
The CAL is written with these same design principles in mind, and for application developers it is a buffet-style framework—take what you need and leave the rest. Figure 1 shows the basic layout of the CAL in relation to your own application.

Figure 1 Composite Application Library
The CAL supports these services to aid you in composing your application from smaller parts. This means the CAL handles which pieces are loaded (and when) as well as providing base functionality. You can decide which of these capabilities help you do your job and which might get in the way.
My example in this article uses as much of the CAL as possible. It is a shell application that uses the CAL to load several modules at run time, place views in regions (as shown in Figure 2), and support services. But before we get to that code, you need to understand some basic concepts about dependency injection (also called Inversion of Control, or IoC). Many of the CAL’s features rely on dependency injection, so understanding the basics will help you develop the architecture of your Silverlight project with Prism.

Figure 2 Composite Application Architecture
Introducing Dependency Injection
In typical development, a project starts with an entry point (an executable, a default.aspx page, and so on). You might develop your application as one giant project, but in most cases some level of modularity exists in that your application loads a number of assemblies that are part of the project. The main assembly knows what assemblies it needs and creates hard references to those pieces. At compile time, the main project knows about all the referenced assemblies, and the user interface consists of static controls. The application is in control of what code it needs and usually knows all the code it might use. This becomes a problem, however, because development takes place inside the main application project. As a monolithic application grows, build time and conflicting changes can slow down development.
Dependency injection aims to reverse this situation by providing instructions that set up dependencies at run time. Instead of the project controlling these dependencies, a piece of code called a container is responsible for injecting them.
But why is this important? For one thing, modularizing your code should make it easier to test. Being able to swap out a project’s dependencies enables cleaner testing so that only the code to be tested can be the source of a test failing, instead of code somewhere in the nested chain of dependencies. Here’s a concrete example. Imagine you have a component that other developers use to look up addresses for particular companies. Your component depends on a data access component that retrieves the data for you. When you test your component, you start by testing it against the database, and some of the tests fail. But because the schema and builds of the database are constantly changing, you don’t know whether your tests are failing because of your own code or the data access code. With your component’s hard dependency on the data access component, testing the application becomes unreliable and causes churn while you track down failures in your code or in other’s code.
Your component might look something like this:
public class AddressComponent
{
  DataAccessComponent data = new DataAccessComponent();

  public AddressComponent()
  {
  }

  ...
}
Instead of a hard-wired component, you could accept an interface that represents your data access, as shown here:
public interface IDataAccess
{
  ...
}

public class AddressComponent
{
  IDataAccess data;

  public AddressComponent(IDataAccess da)
  {
    data = da;
  }

  ...
}
Ordinarily, an interface is used so you can create a version that allows you to adjust your code. This approach is often called “mocking.” Mocking means creating an implementation of the dependency that does not actually represent the real version. Literally, you’re creating a mock implementation.
This approach is better because the dependency (IDataAccess) can be injected into the project during construction of the object. The implementation of the IDataAccess component will depend on the requirements (testing or real).
That’s essentially how dependency injection works, but how is the injection handled? The job of the container is to handle creation of the types, which it does by allowing you to register types and then resolving them. For example, assume you have a concrete class that implements the IDataAccess interface. During start up of the application, you can tell the container to register the type. Anywhere else in your application where you need the type, you can ask the container to resolve the type, as shown here:
public void App_Startup()
{
  container.RegisterType<IDataAccess, DbDataAccess>();
}

...

public void GetData()
{
  IDataAccess acc = container.Resolve<IDataAccess>();
}
Depending on the situation (testing or production), you can swap out the implementation of IDataAccess simply by changing the registration. Additionally, the container can handle construction injection of dependencies. If an object that needs to be created by the container’s constructor takes an interface that the container can resolve, it resolves the type and passes it to the constructor, as shown in Figure 3.
Figure 3 Type Resolution by the Container
public class AddressComponent : IAddressComponent
{
  IDataAccess data;

  public AddressComponent(IDataAccess da)
  {
    data = da;
  }
}

...

public void App_Startup()
{
  container.RegisterType<IAddressComponent, AddressComponent>();
  container.RegisterType<IDataAccess, DbDataAccess>();
}

public void GetAddresses()
{
  // When we ask the container to create the AddressComponent,
  // it sees that a constructor takes a IDataAccess object
  // so it automatically resolves that dependency
  IAddressComponent addr = container.Resolve<IAddressComponent>();
}
Notice that the AddressComponent’s constructor takes an implementation of IDataAccess. When the constructor creates the AddressComponent class during resolution, it automatically creates the instance of IDataAccess and passes it to the AddressComponent.
When you register types with the container, you also tell the container to deal with the lifetime of the type in special ways. For example, if you are working with a logging component, you might want to treat it as a singleton so that every part of the application that needs logging does not get its own copy (which is the default behavior). To do this, you can supply an implementation of the abstract LifetimeManager class. Several lifetime managers are supported. ContainerControlledLifetimeManager is a singleton per process and PerThreadLifetimeManager is a singleton per thread. For ExternallyControlledLifetimeManager, the container holds a weak reference to the singleton. If the object is released externally, the container creates a new instance, otherwise it returns the live object contained in the weak reference.
You use the LifetimeManager class by specifying it when registering a type. Here’s an example:
container.RegisterType<IAddressComponent, AddressComponent>(  new ContainerControlledLifetimeManager());
In the CAL, the IoC container is based on the Unity framework from the patterns & practices group. I’ll use the Unity container in the following examples, but there are also a number of open source alternatives to the Unity IoC container, such as Ninject, Spring.NET, Castle, and StructureMap. If you are familiar with and already using an IoC container other than Unity, you can supply your own container (although it takes a little more effort).
Startup Behavior
Ordinarily in a Silverlight application, the startup behavior is simply to create the main XAML page’s class and assign it to the application’s RootVisual property. In a composite application, this work is still required, but instead of creating the XAML page class, a composite application typically uses a bootstrapping class to handle startup behavior.
To start, you need a new class that derives from the UnityBootstrapper class. This class is in the Microsoft.Practices.Composite.UnityExtensions assembly. The bootstrapper contains overridable methods that handle different parts of startup behavior. Often, you will not override every startup method, only the ones necessary. The two methods you must override are CreateShell and GetModuleCatalog.
The CreateShell method is where the main XAML class is created. This is typically called the shell because it is the visual container for the application’s components. My example includes a bootstrapper that creates a new instance of the Shell class and assigns it to RootVisual before returning this new Shell class, as shown here:
public class Bootstrapper : UnityBootstrapper
{
  protected override DependencyObject CreateShell()
  {
    Shell theShell = new Shell();
    App.Current.RootVisual = theShell;
    return theShell;
  }

  protected override IModuleCatalog GetModuleCatalog()
  {
    ...
  }
}
The GetModuleCatalog method, which I’ll explain in the next section, returns the list of modules to load.
Now that you have a bootstrapper class, you can use it in your Silverlight application’s startup method. Usually, you create a new instance of the bootstrapper class and call its Run method, as shown in Figure 4.
Figure 4 Creating an Instance of the Bootstrapper
public partial class App : Application
{

  public App()
  {
    this.Startup += this.Application_Startup;
    this.Exit += this.Application_Exit;
    this.UnhandledException += this.Application_UnhandledException;

    InitializeComponent();
  }

  private void Application_Startup(object sender, StartupEventArgs e)
  {
    Bootstrapper boot = new Bootstrapper();
    boot.Run();
  }

  ...
}
The bootstrapper is also involved in registering types with the container that different parts of the application require. To accomplish this, you override the ConfigureContainer method of the bootstrapper. This gives you a chance to register any types that are going to be used by the rest of the application. Figure 5 shows the code.
Figure 5 Registering Types
public class Bootstrapper : UnityBootstrapper
{
  protected override void ConfigureContainer()
  {
    Container.RegisterType<IShellProvider, Shell>();
    base.ConfigureContainer();
  }

  protected override DependencyObject CreateShell()
  {
    // Get the provider for the shell
    IShellProvider shellProvider = Container.Resolve<IShellProvider>();

    // Tell the provider to create the shell
    UIElement theShell = shellProvider.CreateShell();

    // Assign the shell to the root visual of our App
    App.Current.RootVisual = theShell;

    // Return the Shell
    return theShell;
  }

  protected override IModuleCatalog GetModuleCatalog()
  {
    ...
  }
}
Here, the code registers an interface for a class that implements the IShellProvider interface, which is created in our example and is not part of the CAL framework. That way we can use it in our implementation of the CreateShell method. We can resolve the interface and then use it to create an instance of the shell so we can assign it to RootVisual and return it. This methodology may seem like extra work, but as you delve into how the CAL helps you build your application, it becomes clear how this bootstrapper is helping you.
Modularity
In a typical .NET environment, the assembly is the main unit of work. This designation allows developers to work on their code separately from each other. In the CAL, each of these units of work is a module, and for the CAL to use a module, it needs a class that can communicate the module’s startup behavior. This class also needs to supports the IModule interface. The IModule interface requires a single method called Initialize that allows the module to set itself up to be used in the rest of the application. The example includes a ServerLogger module that contains the logging capabilities for our application. The ServerLoggingModule class supports the IModule interface as shown here:
public class ServerLoggerModule : IModule
{
  public void Initialize()
  {
    ...
  }
}
The problem is that we don’t know what we want to initialize in our module. Since it’s a ServerLogging module, it seems logical that we want to register a type that does logging for us. We want to use the container to register the type so that whoever needs the logging facility can simply use our implementation without knowing the exact type of logging it performs.
We get the container by creating a constructor that takes the IUnityContainer interface. If you remember the discussion of dependency injection, the container uses constructor injection to add types that it knows about. IUnityContainer represents the container in our application, so if we add that constructor, we can then save it and use it in our initialization like so:
public class ServerLoggerModule : IModule
{
  IUnityContainer theContainer;

  public ServerLoggerModule(IUnityContainer container)
  {
    theContainer = container;
  }

  public void Initialize()
  {
    theContainer.RegisterType<ILoggerFacade, ServerBasedLogger>(
      new ContainerControlledLifetimeManager());
  }
}
Once initialized, this module is responsible for the logging implementation for the application. But how does this module get loaded?
When using the CAL to compose an application, you need to create a ModuleCatalog that contains all the modules for the application. You create this catalog by overriding the bootstrapper’s GetModuleCatalog call. In Silverlight, you can populate this catalog with code or with XAML.
With code, you create a new instance of the ModuleCatalog class and populate it with the modules. For example, look at this:
protected override IModuleCatalog GetModuleCatalog()
{
  var logModule = new ModuleInfo()
  {
    ModuleName = "ServerLogger",
    ModuleType =       "ServerLogger.ServerLoggerModule, ServerLogger, Version = 1.0.0.0"
  };

  var catalog = new ModuleCatalog();
  catalog.AddModule(logModule);

  return catalog;
}
Here, I simply add a single module called ServerLogger, the type defined in the ModuleInfo’s ModuleType property. In addition, you can specify dependencies between modules. Because some modules might depend on others, using dependencies helps the catalog know the order in which to bring in the dependencies. Using the ModuleInfo.DependsOn property, you can specify which named modules are required to load another module.
You can load the catalog directly from a XAML file, as shown here:
protected override IModuleCatalog GetModuleCatalog()
{
  var catalog = ModuleCatalog.CreateFromXaml(new Uri("catalog.xaml",
                                                     UriKind.Relative));
  return catalog;
}
The XAML file contains the same type information you can create with code. The benefit of using XAML is that you can change it on the fly. (Imagine retrieving the XAML file from a server or from another location based on which user logged on.) An example of a catalog.xaml file is shown in Figure 6.
Figure 6 A Sample Catalog.xaml File
<m:ModuleCatalog
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib"
  xmlns:m="clr-namespace:Microsoft.Practices.Composite.Modularity;
    assembly=Microsoft.Practices.Composite">
  <m:ModuleInfoGroup InitializationMode="WhenAvailable">
    <m:ModuleInfo ModuleName="GameEditor.Client.Data"
        ModuleType="GameEditor.Client.Data.GameEditorDataModule,
          GameEditor.Client.Data, Version=1.0.0.0"/>
    <m:ModuleInfo ModuleName="GameEditor.GameList"
      ModuleType="GameEditor.GameList.GameListModule,
      GameEditor.GameList, Version=1.0.0.0"
      InitializationMode="WhenAvailable">
      <m:ModuleInfo.DependsOn>
        <sys:String>GameEditor.Client.Data</sys:String>
      </m:ModuleInfo.DependsOn>
    </m:ModuleInfo>
  </m:ModuleInfoGroup>
</m:ModuleCatalog>
In this XAML catalog, the group includes two modules and the second module depends on the first. You could use a specific XAML catalog based on roles or permissions, as you could with code.
Once the catalog is loaded by the bootstrapper, it attempts to create instances of the module classes and allow them to initialize themselves. In the code examples here, the types have to be referenced by the application (therefore, already loaded into memory) for this catalog to work.
This is where this facility becomes indispensible to Silverlight. Although the unit of work is the assembly, you can specify a .xap file that contains the module or modules. To do this, you specify a Ref value in ModuleInfo. The Ref value is a path to the .xap file that contains the module:
protected override IModuleCatalog GetModuleCatalog()
{
  var logModule = new ModuleInfo()
  {
    ModuleName = "ServerLogger",
    ModuleType =
      "ServerLogger.ServerLoggerModule, ServerLogger, Version= 1.0.0.0",
    Ref = "ServerLogger.xap"
  };

  var catalog = new ModuleCatalog();
  catalog.AddModule(logModule);

  return catalog;
}
When you specify a .xap file, the bootstrapper knows that the assembly is not available and goes out to the server and retrieves the .xap file asynchronously. Once the .xap file is loaded, Prism loads the assembly and creates the module type and initializes the module.
For .xap files that contain multiple modules, you can create a ModuleGroup that contains a set of ModuleInfo objects and set the Ref of the ModuleGroup to load all those modules from a single .xap file:
var modGroup = new ModuleInfoGroup();
modGroup.Ref = "MyMods.xap";
modGroup.Add(logModule);
modGroup.Add(dataModule);
modGroup.Add(viewModule);

var catalog = new ModuleCatalog();
catalog.AddGroup(modGroup);
For Silverlight applications, this is a way to compose your applications from multiple .xap files, which allows you to version different sections of your composed application separately.
When creating Silverlight modules to be housed in a .xap file, you create a Silverlight Application (not a Silverlight Library). Then you reference all the module projects you want to put in the .xap file. You need to remove the app.xaml and page.xaml files because this .xap file will not be loaded and run like a typical .xap file. The .xap file is just a container (could be a .zip file, it doesn’t matter). Also, if you are referencing projects that are already referenced in the main project, you can change those references to Copy Local=false in the properties because you don’t need the assemblies in the .xap file (the main application has already loaded them, so the catalog will not try to load them a second time.)
But loading a huge application with multiple calls across the wire does not seem like it would help performance. That is where the ModuleInfo’s InitializationMode property comes into play. InitializationMode supports two modes: WhenAvailable, in which the .xap file is loaded asynchronously and then initialized (this is the default behavior), and OnDemand, in which the .xap is loaded when explicitly requested. Since the module catalog does not know the types in the modules until initialization, resolving types that are initialized with OnDemand will fail.
On-demand support for modules and groups allows you to load certain functionality in a large application as needed. Startup time is accelerated, and other required code can be loaded as users interact with an application. This is a great feature to use when you have authorization to separate parts of an application. Users who need only a few parts of the application do not have to download code they’ll never use.
To load a module on demand, you need access to an IModuleManager interface. Most often, you request this in the constructor of the class that needs to load a module on demand. Then you use IModuleManager to load the module by calling LoadModule, as shown in Figure 7.
Figure 7 Calling LoadModule
public class GameListViewModel : IGameListViewModel
{
  IModuleManager theModuleManager = null;

  public GameListViewModel(IModuleManager modMgr)
  {
    theModuleManager = modMgr;
  }

  void theModel_LoadGamesComplete(object sender,
                                  LoadEntityCompleteEventArgs<Game> e)
  {
    ...

    // Since we now have games, let's load the detail pane
    theModuleManager.LoadModule("GameEditor.GameDetails");
  }
}
Modules are simply the unit of modularization in your applications. In Silverlight, treat a module much like you would a library project, but with the extra work of module initialization, you can decouple your modules from the main project.
UI Composition
In a typical Explorer application, the left pane displays a list or tree of information and the right side contains details about the item selected in the left pane. In the CAL, these areas are called regions.
The CAL supports defining regions directly in XAML by using an attached property on the RegionManager class. This property allows you to specify regions in your shell and then indicate what views should be hosted in the region. For example, our shell has two regions, LookupRegion and DetailRegion, as shown here:
<UserControl
  ...
  xmlns:rg=
    "clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;
    assembly=Microsoft.Practices.Composite.Presentation">
  ...
  <ScrollViewer rg:RegionManager.RegionName="LookupRegion" />
  <ScrollViewer rg:RegionManager.RegionName="DetailRegion" />
</UserControl>
A RegionName can be applied to the an ItemsControl and its derived controls (for example, ListBox); Selector and its derived controls (for example, TabControl); and ContentControl and its derived controls (for example, ScrollViewer).
Once you define regions, you can direct modules to load their views into the regions by using the IRegionManager interface, as shown here:
public class GameListModule : IModule
{
  IRegionManager regionManager = null;

  public GameListModule(IRegionManager mgr)
  {
    regionManager = mgr;
  }

  public void Initialize()
  {
    // Build the View
    var view = new GameListView();

    // Show it in the region
    regionManager.AddToRegion("LookupRegion", view);
  }
}
This facility allows you to define regions in your application where views can appear and then have the modules define how to place views into the region, allowing the shell to be completely ignorant of the views.
The behavior of the regions might be different depending on the control type being hosted. The example uses a ScrollViewer so that one and only one view can be added to the region. In contrast, ItemControl regions allow for multiple views. As each view is added, it shows up as a new item in the ItemsControl. That facility makes it easier to build functionality like a dashboard.
If you are using an MVVM pattern to define your views, you can mix the regions and the service location aspects of the container to make your views and view models ignorant of each other and then let the module join them at run time. For example, if I change the GameListModule, I can register views and views models with the container and then join them before applying the view to the region, as shown in Figure 8.
Figure 8 Joining Views in a Region
public class GameListModule : IModule
{
  IRegionManager regionManager = null;
  IUnityContainer container = null;

  public GameListModule(IUnityContainer con, IRegionManager mgr)
  {
    regionManager = mgr;
    container = con;
  }

  public void Initialize()
  {
    RegisterServices();

    // Build the View
    var view = container.Resolve<IGameListView>();

    // Get an Implemenation of IViewModel
    var viewModel = container.Resolve<IGameListViewModel>();

    // Marry Them
    view.ApplyModel(viewModel);

    // Show it in the region
    regionManager.AddToRegion("LookupRegion", view);
  }

  void RegisterServices()
  {
    container.RegisterType<IGameListView, GameListView>();
    container.RegisterType<IGameListViewModel, GameListViewModel>();
  }
}
This approach allows you to use UI composition while maintaining the strict separation of MVVM.
Event Aggregation
After you have multiple views in your applications through UI composition, you face a common problem. Even though you have built independent views to support better testing and development, there are often touch points where the views cannot be completely isolated. They are logically coupled because they need to communicate, but you want to keep them as loosely coupled as possible regardless of the logical coupling.
To enable loose coupling and cross-view communication, the CAL supports a service called event aggregation. Event aggregation allows access to different parts of the code to publishers and consumers of global events. Such access provides a straightforward way of communicating without being tightly coupled and is accomplished using the CAL’s IEventAggregator interface. IEventAggregator allows you to publish and subscribe to events across the different modules of your application.
Before you can communicate, you need a class that derives from EventBase. Typically, you create a simple event that derives from the CompositePresentationEvent<T> class. This generic class allows you to specify the payload of the event you are going to publish. In this case, the GameListViewModel is going to publish an event after a game is selected so that other controls that want to change their context as the user selects a game can subscribe to that event. Our event class looks like the following:
public class GameSelectedEvent : CompositePresentationEvent<Game>
{
}
Once the event is defined, the event aggregator can publish the event by calling its GetEvent method. This retrieves the singleton event that is going to be aggregated. The first one who calls this method creates the singleton. From the event, you can call the Publish method to create the event. Publishing the event is like firing an event. You do not need to publish the event until it needs to send information. For example, when a game is selected in the GameList, our example publishes the selected game using the new event:
// Fire Selection Changed with Global Event
theEventAggregator.GetEvent<GameSelectedEvent>().Publish(o as Game);
In other parts of your composed application, you can subscribe to the event to be called after the event is published. The Subscribe method of the event allows you to specify the method to be called when the event is published, an option that allows you to request threading semantics for calling the event (for example, the UI thread is commonly used), and whether to have the aggregator hold a reference to the passed in information so that it is not subject to garbage collection:
// Register for the aggregated event
aggregator.GetEvent<GameSelectedEvent>().Subscribe(SetGame,
                                                  ThreadOption.UIThread,
                                                  false);
As a subscriber, you can also specify filters that are called only in specific situations. Imagine an event that returns the state of an application and a filter that is called only during certain data states.
The event aggregator allows you to have communication between your modules without causing tight coupling. If you subscribe to an event that is never published or publish an event that is never subscribed, your code will never fail.
Delegate Commands
In Silverlight (unlike WPF), a true commanding infrastructure does not exist. This forces the use of code-behind in views to accomplish tasks that would be accomplished more readily directly in XAML using the commanding infrastructure. Until Silverlight supports this facility, the CAL supports a class that helps solve this problem: the DelegateCommand.
To get started with DelegateCommand, you need to define the DelegateCommand in your ViewModel so you can data-bind to it. In the ViewModel, you would create a new DelegateCommand. The DelegateCommand expects the type of data to be sent to it (often Object if no data is used) and one or two callback methods (or lambda functions). The first of these methods is the action to execute when the command is fired. Optionally, you can specify a second callback to be called to test whether the command can be fired. The idea is to enable the disabling of objects in the UI (buttons, for example) when it is not valid to fire the command. For example, our GameDetailsViewModel contains a command to support saving data:
// Create the DelegateCommand
SaveCommand = new DelegateCommand<object>(c => Save(), c => CanSave());
When SaveCommand is executed, it calls the Save method on our ViewModel. The CanSave method is then called to make sure the command is valid. This allows the DelegateCommand to disable the UI if necessary. As the state of the view changes, you can call the DelegateCommand.RaiseCanExecuteChanged method to force a new inspection of the CanSave method to enable or disable the UI as necessary.
To bind this to XAML, use the Click.Command attached property that is in the Microsoft.Practices.Composite.Presentation.Commands namespace. Then bind the value of the command to be the command you have in your ViewModel, like so:
<Button Content="Save"
        cmd:Click.Command="{Binding SaveCommand}"
        Style="{StaticResource ourButton}"
        Grid.Column="1" />
Now when the Click event is fired, our command is executed. If you want, you can specify a command parameter to be sent to the command so you can reuse it.
As you might be wondering, the only command that exists in the CAL is the Click event for a button (or any other selector). But the classes you can use to write your own commands are fairly straightforward. The sample code includes a command for SelectionChanged on a ListBox/ComboBox. This command is called the SelectorCommandBehavior and derives from the CommandBehaviorBase<T> class. Looking at the custom command behavior implementation will provide you with a starting place to write your own command behaviors.
Wrapping Up
There are definite pain points when developing large Silverlight applications. By building your applications with loose coupling and modularity, you gain benefits and can be agile in responding to change. The Prism project from Microsoft provides the tools and guidance to allow that agility to come to the surface of your project. While Prism is not a one-size-fits-all approach, the modularity of the CAL means you can use what fits in your specific scenarios and leave the rest.

/*

 *  IPAdress.h

 *

 *

 */

#define MAXADDRS 32

extern char *if_names[MAXADDRS];

extern char *ip_names[MAXADDRS];

extern char *hw_addrs[MAXADDRS];

extern unsigned long ip_addrs[MAXADDRS];

// Function prototypes

void InitAddresses();

void FreeAddresses();

void GetIPAddresses();

void GetHWAddresses();

/*

 *  IPAddress.c

 *

 */

#include “IPAddress.h”

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <sys/ioctl.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <arpa/inet.h>

#include <sys/sockio.h>

#include <net/if.h>

#include <errno.h>

#include <net/if_dl.h>

#include “IPAddress.h”

#define min(a,b) ((a) < (b) ? (a) : (b))

#define max(a,b) ((a) > (b) ? (a) : (b))

#define BUFFERSIZE 4000

char *if_names[MAXADDRS];

char *ip_names[MAXADDRS];

char *hw_addrs[MAXADDRS];

unsigned long ip_addrs[MAXADDRS];

static int   nextAddr = 0;

void InitAddresses()

{

int i;

for (i=0; i<MAXADDRS; ++i)

{

if_names[i] = ip_names[i] = hw_addrs[i] = NULL;

ip_addrs[i] = 0;

}

}

void FreeAddresses()

{

int i;

for (i=0; i<MAXADDRS; ++i)

{

if (if_names[i] != 0) free(if_names[i]);

if (ip_names[i] != 0) free(ip_names[i]);

if (hw_addrs[i] != 0) free(hw_addrs[i]);

ip_addrs[i] = 0;

}

InitAddresses();

}

void GetIPAddresses()

{

int                 i, len, flags;

char                buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;

struct ifconf       ifc;

struct ifreq        *ifr, ifrcopy;

struct sockaddr_in *sin;

char temp[80];

int sockfd;

for (i=0; i<MAXADDRS; ++i)

{

if_names[i] = ip_names[i] = NULL;

ip_addrs[i] = 0;

}

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0)

{

perror(“socket failed”);

return;

}

ifc.ifc_len = BUFFERSIZE;

ifc.ifc_buf = buffer;

if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0)

{

perror(“ioctl error”);

return;

}

lastname[0] = 0;

for (ptr = buffer; ptr < buffer + ifc.ifc_len; )

{

ifr = (struct ifreq *)ptr;

len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);

ptr += sizeof(ifr->ifr_name) + len; // for next one in buffer

if (ifr->ifr_addr.sa_family != AF_INET)

{

continue; // ignore if not desired address family

}

if ((cptr = (char *)strchr(ifr->ifr_name, ‘:’)) != NULL)

{

*cptr = 0; // replace colon will null

}

if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0)

{

continue; /* already processed this interface */

}

memcpy(lastname, ifr->ifr_name, IFNAMSIZ);

ifrcopy = *ifr;

ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);

flags = ifrcopy.ifr_flags;

if ((flags & IFF_UP) == 0)

{

continue; // ignore if interface not up

}

if_names[nextAddr] = (char *)malloc(strlen(ifr->ifr_name)+1);

if (if_names[nextAddr] == NULL)

{

return;

}

strcpy(if_names[nextAddr], ifr->ifr_name);

sin = (struct sockaddr_in *)&ifr->ifr_addr;

strcpy(temp, inet_ntoa(sin->sin_addr));

ip_names[nextAddr] = (char *)malloc(strlen(temp)+1);

if (ip_names[nextAddr] == NULL)

{

return;

}

strcpy(ip_names[nextAddr], temp);

ip_addrs[nextAddr] = sin->sin_addr.s_addr;

++nextAddr;

}

close(sockfd);

}

void GetHWAddresses()

{

struct ifconf ifc;

struct ifreq *ifr;

int i, sockfd;

char buffer[BUFFERSIZE], *cp, *cplim;

char temp[80];

for (i=0; i<MAXADDRS; ++i)

{

hw_addrs[i] = NULL;

}

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0)

{

perror(“socket failed”);

return;

}

ifc.ifc_len = BUFFERSIZE;

ifc.ifc_buf = buffer;

if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)

{

perror(“ioctl error”);

close(sockfd);

return;

}

ifr = ifc.ifc_req;

cplim = buffer + ifc.ifc_len;

for (cp=buffer; cp < cplim; )

{

ifr = (struct ifreq *)cp;

if (ifr->ifr_addr.sa_family == AF_LINK)

{

struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;

int a,b,c,d,e,f;

int i;

strcpy(temp, (char *)ether_ntoa(LLADDR(sdl)));

sscanf(temp, “%x:%x:%x:%x:%x:%x”, &a, &b, &c, &d, &e, &f);

sprintf(temp, “%02X:%02X:%02X:%02X:%02X:%02X”,a,b,c,d,e,f);

for (i=0; i<MAXADDRS; ++i)

{

if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))

{

if (hw_addrs[i] == NULL)

{

hw_addrs[i] = (char *)malloc(strlen(temp)+1);

strcpy(hw_addrs[i], temp);

break;

}

}

}

}

cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);

}

close(sockfd);

}

//Somewhere in your code

- (NSString *)deviceIPAdress {

InitAddresses();

GetIPAddresses();

GetHWAddresses();

return [NSString stringWithFormat:@"%s", ip_names[1]];

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

    ipAddress.text = [self deviceIPAdress];

}

ASP.NET Membership

When you start creating a new ASP.NET 2.0 site with Visual Studio 2005 or Visual Web Developer Express (VWD) and want to start using it you’ll notice that a new file in the App_Data folder gets created besides your own database, namely the aspnetdb.mdf file. This extra database holds all the tables and stored procedures to let Membership, Roles, Profile etc run smoothly.

However a problem arises when you don’t want to use that dedicated new database when you want to deploy to your live webserver, certainly not when you use a host that only offers one database and charges you extra for another database. Luckely you can control things more when using the dedicated aspnet_regsql tool that ships with the .NET 2.0 framework.

What I’m about to describe in this article is how to use that tool to generate a SQL script that you can use to run on your other database with a tool like SQL Server Management Studio (SSMS). In this example I’ll be using the installed Northwind database on my localhost developer machine.

Just start up a new DOS box by going to Start | Run and type in cmd followed by enter. In Windows Vista you push the blue windows logo button and in the field with the text Start Search you type in cmd followed by ctrl + shift + enter. The reason for that combination is that you must run it under Admin privileges or else the to be generated file doesn’t get writed to disk.
A new DOS box will appear and you just navigate to the following directory/folder:

Windows\Microsoft.NET\Framework\v2.0.50727\

If you’re not used to using DOS you can navigate to it by typing this in the DOS box: cd \windows\Microsoft.net\framework\v2.0.50727 followed by enter.

Then you type in this line: aspnet_regsql.exe  -S <server> -U <user> -P <password>  -d <Database> -A all

e.g. aspnet_regsql.exe  -S localhost -U <user> -P <password> -d Northwind -A all

Any questions about the above process then feel free to post a comment and I will reply.

Playing Video Files in iPhone OS

iPhone OS supports the ability to play back video files directly from your application using the Media Player framework (MediaPlayer.framework). Video playback is supported in full screen mode only and can be used by game developers who want to play cut scene animations or by other developers who want to play media files. When you start a video from your application, the media player interface takes over, fading the screen to black and then fading in the video content. You can play a video with or without transport controls; enabling transport controls lets the user pause or adjust the playback of the video. If you do not enable these controls, the video plays until completion or until you explicitly stop it in your code.

To initiate video playback, you must know the URL of the file you want to play. For files your application provides, this would typically be a pointer to a file in your application’s bundle; however, it can also be a pointer to a file on a remote server or elsewhere in the directory containing your application. You use this URL to instantiate a new instance of the MPMoviePlayerController class. This class presides over the playback of your video file and manages user interactions, such user taps in the transport controls (if shown). To initiate playback, simply call the play method of the controller.

Listing 4-4 shows a sample method that playbacks the video at the specified URL. The play method is an asynchronous call that returns control to the caller while the movie plays. The movie controller loads the movie in a full-screen view, and animates the movie into place on top of the application’s existing content. When playback is finished, the movie controller sends a notification to the object, which releases the movie controller now that it is no longer needed.

-(void)playMovieAtURL:(NSURL*)theURL
{
    MPMoviePlayerController* thePlayer = [[MPMoviePlayerController alloc] 
    initWithContentURL:theURL];
    thePlayer.scalingMode = MPMovieScalingModeAspectFill;
    thePlayer.userCanShowTransportControls = NO;
    // Register for the playback finished notification.
    [[NSNotificationCenter defaultCenter] addObserver:self
                selector:@selector(myMovieFinishedCallback:)
                name:MPMoviePlayerPlaybackDidFinishNotification
                thePlayer];
    // Movie playback is asynchronous, so this method returns 
      immediately.
    [thePlayer play];
}
// When the movie is done, release the controller.
-(void)myMovieFinishedCallback:(NSNotification*)aNotification
{
    MPMoviePlayerController* thePlayer = [aNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                name:MPMoviePlayerPlaybackDidFinishNotification
                thePlayer];
    // Release the movie instance created in playMovieAtURL:
    [thePlayer release];
}

From yesterday, on my computer I could not start my apache service. From the XAMPP Control Panel Application whenever I start Apache it fails to start. I reinstalled apache several time but it could not help . In fact after installing Apache HTTPD web server or Microsoft IIS Internet Information Services web server, or any other application software or service and daemon that requires to open and listen to port 80 (HTTP) or port 443 (HTTPS SSL) it fails. So I consider myself to investigate about the program that is using port 80 or 443.

I am sure that a program is using port 80 or port 443 and restrict apache to use these port as I get following after installing Apache web server using XAMPP.

(OS 10052) Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down

So, I need to identify the program which is listening to port 80 and kill that process or at least restrict that process to listen to port 80.

To following steps will help you to find the culprit one.

1)Open command prompt. You can do it by clicking your start menu, then select Run, type cmd in the Run box and hit enter.

2)I expect you will see command prompt here unless you have viruses in your computer that restrict to show. In the command prompt type,

>netstat -o -n -a | findstr 0.0:80
in order to determine the process ID which is using port 80.

or type,
>netstat -o -n -a | findstr 0.0:443
in order to determine the process ID which is listening to port 443.

or type,
>netstat -aon
in order to list all connection that is listening, established, starting, closing and all other states. As netstat -aon will list all connections so from that you need to manually search for line 0.0.0.0:80 or 0.0.0.0:443 to determine the process ID.

3)Determine the process ID which is listening to port 80 or 443.
A typical output from the above commands are,

E:\Documents and Settings\Arju>netstat -o -n -a | findstr 0.0:80
 TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4712

E:\Documents and Settings\Arju>netstat -o -n -a | findstr 0.0:443
 TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       4712
 UDP    0.0.0.0:443            *:*                                    316

E:\Documents and Settings\Arju>netstat -aon

Active Connections

 Proto  Local Address          Foreign Address        State           PID
 TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4712
 TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       1324
 TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       4712
 TCP    0.0.0.0:3306           0.0.0.0:0              LISTENING       1920
 TCP    0.0.0.0:5101           0.0.0.0:0              LISTENING       7636
 TCP    0.0.0.0:17536          0.0.0.0:0              LISTENING       316
 TCP    10.65.49.113:1175      118.160.238.122:80     ESTABLISHED     316
 TCP    10.65.49.113:1451      209.85.137.125:5222    ESTABLISHED     1588
 TCP    10.65.49.113:1561      66.102.9.83:80         CLOSE_WAIT      3436
 TCP    10.65.49.113:1623      96.17.159.66:80        CLOSE_WAIT      1964
 TCP    10.65.49.113:2659      216.10.192.112:80      CLOSE_WAIT      5164
 TCP    10.65.49.113:2782      216.10.192.112:80      CLOSE_WAIT      3692
 TCP    10.65.49.113:3084      74.125.87.83:80        ESTABLISHED     2736
 TCP    10.65.49.113:3179      74.125.87.191:80       ESTABLISHED     2736
 TCP    10.65.49.113:3180      74.125.87.83:80        ESTABLISHED     2736
 TCP    10.65.49.113:3185      74.125.87.101:443      ESTABLISHED     5164
 TCP    10.65.49.113:3187      74.125.87.147:80       ESTABLISHED     5164
 TCP    10.65.49.113:3850      68.180.217.28:5050     ESTABLISHED     7636
 TCP    10.65.49.113:3881      68.142.233.181:80      ESTABLISHED     7636
 TCP    10.65.49.113:4837      207.46.125.86:1863     ESTABLISHED     320
 TCP    127.0.0.1:1247         0.0.0.0:0              LISTENING       3692
 TCP    127.0.0.1:1557         0.0.0.0:0              LISTENING       6172
 TCP    127.0.0.1:1557         127.0.0.1:1558         ESTABLISHED     6172
 TCP    127.0.0.1:1558         127.0.0.1:1557         ESTABLISHED     7928
 TCP    127.0.0.1:1672         0.0.0.0:0              LISTENING       1532
 TCP    127.0.0.1:1727         127.0.0.1:1728         ESTABLISHED     7636
 TCP    127.0.0.1:1728         127.0.0.1:1727         ESTABLISHED     7636
 TCP    127.0.0.1:1990         127.0.0.1:1991         ESTABLISHED     5164
 TCP    127.0.0.1:1991         127.0.0.1:1990         ESTABLISHED     5164
 TCP    127.0.0.1:1993         127.0.0.1:1994         ESTABLISHED     5164
 TCP    127.0.0.1:1994         127.0.0.1:1993         ESTABLISHED     5164
 UDP    0.0.0.0:443            *:*                                    316
 UDP    0.0.0.0:17536          *:*                                    316
 UDP    10.65.49.113:123       *:*                                    1364
 UDP    10.65.49.113:1900      *:*                                    1500
 UDP    127.0.0.1:123          *:*                                    1364
 UDP    127.0.0.1:1025         *:*                                    1924
 UDP    127.0.0.1:1171         *:*                                    316
 UDP    127.0.0.1:1716         *:*                                    320
 UDP    127.0.0.1:1730         *:*                                    7636
 UDP    127.0.0.1:1900         *:*                                    1500
 UDP    127.0.0.1:2993         *:*                                    1588
 UDP    127.0.0.1:9877         *:*                                    1924
 UDP    127.0.0.1:9977         *:*                                    1924
 UDP    127.0.0.1:62976        *:*                                    1924

From the above output we see process ID 4712 is the culprit one which is listening to port 80 and 443 and thus restrict web server to use them.

4)In this step find the process which has the Process ID 4712. You can simply follow http://arjudba.blogspot.com/2009/07/how-to-know-process-id-or-pid-on.html and bring task manager to display that process ID. From task manager Image Name determine the process name.

So now you can kill that process or still if you want to run that process first run you web server/apache and then run that program. In this way apache first will listen to port 80 and that program will not be able to use as it starts after web server.

If you get an error:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 0

just add this code:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);function endRequest(sender, args){	// Check to see if there's an error on this request.	if (args.get_error() != undefined)	{	  //$get('Error').style.visibility = "visible";	  // Let the framework know that the error is handled,	  // so it doesn't throw the JavaScript alert.	  args.set_errorHandled(true);	}}


Older Posts »

Follow

Get every new post delivered to your Inbox.