Categories
.NET ASP.NET MVC Setup Umbraco

Umbraco CMS with ASP.NET MVC – Part 3 Inside Visual Studio

In this post for Umbraco CMS we will learn regarding creating Visual Studio Solution. Main motive behind creating VS Solution is to work in proper structured manner and when work in team it is helpful so that Team can Commit their file changes under Source Control when developing with Umbraco CMS.

In the Introduction post you can read the brief roadmap about posts on Umbraco CMS and MVC development. Part 2 of this series describes about Umbraco installation and IIS configurations.

For this post I have used Visual Studio 2013 but 2012 version will also do. This version of Umbraco is using .NET Framework 4.5

Step 1 – Create Blank Solution for UMBRACO CMS

Start Visual Studio and use the shortcut for create new project i.e. Ctrl+Shift+N

Create a Blank Visual Studio Solution.

In Visual Studio 2013, Navigate to ‘Visual C#‘ > ‘Web’ > Select ‘ASP.NET Web Application‘ as can be seen in the screen below.

Create Empty Web Solution

Note: If you are using Visual Studio 2012 or else the step to create Blank Solution may be different. For example in Visual Studio 2012 you can navigate to ‘Visual C#’ > ‘Web’ > Select ‘ASP.NET MVC 5 Empty Project’.

Considering you have followed the Part 2 regarding Umbraco Installation and Site root folder; keep the backup of the Umbraco site root folder specifically web.config, Global.asax and ‘Views’ folder.

Then uncheck the option for “Create directory for solution”

Set the Location to the Umbraco site root folder.

Set the Solution name. Here we have created Solution with name “UmbracoMvc” and then click “OK”

Next in the “New ASP.NET Project” dialog, Select template “Empty” and tick the “MVC” check box option

Select Blank Application Type

Then click “OK”.

Step 2 – Verify the Solution Structure and Physical Files

After this you can verify the folder structure is created as below screen. Here “Umbraco” is the Solution Folder and “UmbracoMvc” is the Project Folder.

Blank Solution Directory View

After we create blank solution, Visual Studio replaces the existing Umbraco web.config and other imp. files due to this behaviour of VS; we need to restore the files and folders (shown in below screen) from the original version that we have in backup, that we took in previous step, to “UmbracoMvc” project folder.

Copy extracted source code to IIS website root directory

Now we have successfully created blank solution and recovered the files needed. So we need to verify that the Umbraco site is still working at URL ‘http://UmbracoMvc/’.

STEP 3 – Include NECESSARY files in the Solution

Open Visual Studio’s Solution Explorer and select option “Show All Files” highlighted in screen below.

Select Show All Files in Visual Studio Solution

Next include the files and folder as required but do not include the folders named “Umbraco” and “Umbraco_Client” because those part we will not work. I have shown in below screen what I have included in my solution.

Files and Folder Included as part of the Umbraco Web Application project

STEp 4 – Umbraco MVC Configurations

In Umbraco MVC, we generally not define routes. For this reason we will clean up the routes definition from “RouteConfig.cs” as shown in screen below.

Remove or Empty the Route Config

Next we will configure the Umbraco site for default rendering to MVC as shown in the screen below.

Open the “umbracoSettings.config” from “Config” folder and change the template’s default Rendering to “Mvc”.

Default Rendering Engine to MVC

Note: This will affect the creation of new Templates from Umbraco Client/Administration region. Also in new version of Umbraco default rendering is ‘Mvc’, so you can skip this part for Umbraco version 7.1.1

Conclusion

So we have completed the exercise to Create Visual Studio Solution for Umbraco Web development and we also did configurations for ASP.NET MVC 5 version. After this much you can add the source files and folders to any Source Control that works for you. Your Team will love to work in Umbraco CMS after these efforts.

In the next post we will see the how Umbraco CMS works with MVC or in other words how to cook the ASP.NET MVC recipe in Umbraco and also migration points for converting existing ASP.NET MVC sites to Umbraco MVC.

 

Keep sharing your ideas and suggestions in the comments.

Liked this post? Then spread this post to your friends.

 

Categories
.NET ASP.NET IIS MVC Setup Umbraco

Umbraco CMS with ASP.NET MVC – Part 2 Installation

In this post we will see how to start with Umbraco CMS website development with ASP.NET MVC.

In previous Introduction post here you can read the brief roadmap about posts on Umbraco MVC.

Step 1 – Download Latest Umbraco release

Download fresh installation of Umbraco CMS from Official Umbraco Site. For this post Umbraco version 7.1.1 is used and use full source code release package highlighted in bold “UmbracoCms.7.1.1.zip” in screen below.

Download Umbraco full source code release package

Step 2 – Extract the package

After downloading release package in ‘.zip’ format extract the package to temporary location.

Extract Umbraco source code to temporary location

 

Step 3 – Setup the website in IIS

After extracting the release package, the next step is to copy the extracted content to IIS web root directory by creating new folder for the Umbraco MVC website or configure the extracted folder in IIS directly in next steps.

The extracted content will look something as shown below screenshot

Copy extracted source code to IIS web root directory

Now Add a new Website in IIS. To open IIS manager you may use the cmd command ‘inetmgr.exe’.

Add a Website in IIS

Now the Add Website configuration dialog will show up. Configure the Website as below with local domain binding ‘umbracomvc’ on port ’80’

Add a Website - Configuration Dialog in IIS

Now the IIS Website is configured.

Step 4 – Create Local-only domain binding

We have configured the IIS Website with local binding definition in above steps but to correctly resolve and browse host name ‘http://umbracomvc/’ we need to configure the hosts entry in the local system with local IP address. Hosts file configuration and file path is shown in screenshot below.

Edit hosts file to point to local only domain

Note: Open the notepad or notepad++ in Administrator mode. Additionally after this configuration use the cmd command ‘ipconfig /flushdns’

Step 5 – Start Umbraco Installation

After above steps browse the website in browser at URL ‘http://umbracomvc/’ (refer ‘Host Name’ configured in IIS Website Configuration Dialog for the URL if changed in your case). When browsing for first time Umbraco will automatically initiate the Installation wizard and ask for following – Configure the licence (if any), Database connection, User credentials for Umbraco Admin, Starter Kit theme.

Few excerpts from the installation wizard are shown below:

1. Installation Welcome screen

Open browser and start umbraco installation

2. Select ‘No thanks, do not install a Starter Kit’ in Starter Kit Selection Step

Select No Starter Kit

3. Final step screen

Umbraco Installation final step

4. Verify the Umbraco Admin panel access at http://UmbracoMvc/Umbraco/ with configured user credentials in Installation wizard

Umbraco Administration

Note: Above Installation wizard screenshot were captured using Umbraco CMS version 7.0.4 but later upgraded to Umbraco CMS version 7.1.1

Conclusion

In this post we went thru steps to download & install Umbraco CMS on local system. In the next post we will see how to create Visual Studio Solution for this website.

 

I hope this post was easy to understand and screenshot images helped you to visually connect with the minimum required steps.

If you liked this kindly like or subscribe. Keep comments flowing if you have any ideas or suggestions.

Categories
.NET C# Utility

Serialize and Deserialize POCO classes in XML

Serialize and Deserialize the Plain Old CLR Object (POCO) class is the theme of this post and I will be discussing regarding XML-based Serialization and Deserialization.

Note: This post is purely about Serialization and not regarding how to write Serializable POCO classes.

Image Illustration

Serialization Mechanism
Shows overall process of Serialization

POST Index

  1. Serialization
  2. Deserialization
  3. Uses
  4. Download Source code

 

For Serialization

DEFINITION

Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment. Also known as deflating or marshalling.

Source: Wikipedia

Conversion

POCO class to String

Steps

  1. Input POCO class instance
  2. Declare Encoding such as ASCII, UTF-8, and BigEndianUnicode, or else
  3. Declare Stream for In-Memory Serialization
  4. Declare Serializer
  5. Execute Serialization method
  6. Fetch the serialized XML
  7. Output is String value ( XML value )

Source Code

public static string XmlSerialize(T sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (sourceValue == null)
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	string targetValue;

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream())
	{
		// Declare Stream with required Encoding
		using (var streamWriter = new StreamWriter(memoryStream, encoding))
		{
			// Declare Xml Serializer with source value Type (serializing type)
			var xmlSerializer = new XmlSerializer(sourceValue.GetType());

			// Perform Serialization of the source value and write to Stream
			xmlSerializer.Serialize(streamWriter, sourceValue);

			// Grab the serialized string
			targetValue = encoding.GetString(memoryStream.ToArray());
		}
	}

	// Return the resultant value;
	return targetValue;
}

 

FOR DESERIALIZATION

DEFINITION

The opposite operation of Serialization, i.e. extracting a data structure from a series of bytes, is deserialization. Also known as inflating or unmarshalling.

Source: Wikipedia

CONVERSION

String to POCO Class

STEPS

  1. Input String value ( XML value )
  2. Declare Encoding
  3. Declare Serializer
    • Same Serializer class is used for Serializing and Deserializing
  4. Declare Stream for In-Memory Deserialization
  5. Execute Deserialization method
  6. Type cast the return Object to POCO type
  7. Output is POCO class instance

Source CODE

public static T XmlDeserialize(string sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (string.IsNullOrWhiteSpace(sourceValue))
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	T targetValue;

	// Declare Xml Serializer with target value Type (serialized type)
	var xmlSerializer = new XmlSerializer(typeof(T));

	// Get the source value to bytes with required Encoding
	byte[] sourceBytes = encoding.GetBytes(sourceValue);

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream(sourceBytes))
	{
		// Read stream into XML-based reader
		using (var xmlTextReader = new XmlTextReader(memoryStream))
		{
			// Perform Deserialization from the stream and Convert to target type
			targetValue = xmlSerializer.Deserialize(xmlTextReader) as T;
		}
	}

	// Return the resultant value;
	return targetValue;
}

 

Uses

  1. For Deep Cloning the objects
  2. For integrating with RESTful API and Remoting Services
  3. For persisting the User Data for Offline apps which later uses various Synchronization methods
  4. In .NET apps, Serialization is used for saving and accessing settings from web.config or app.config
  5. Remote procedure calls ( RPC )
  6. In Distributed Memory Applications, such AppFabric for Windows Server which is used for Middle tier caching in Load balancing situation
  7. For Data Exchange in cross-platform applications such as .NET apps integration with Android apps or Windows Phone apps.

 

Download Source Code

 

Categories
.NET ASP.NET C# Winforms

Getting started with Multifile assembly – Part II

Some brief before we continue

Hi! In the last article on this topic here MULTIFILE ASSEMBLY part – I, I had talked conceptually about creating multi-file assembly and possible usages.

In this post we will have more insights on the implementation part regarding multi-file assembly and using MEF to apply the concept practically in the applications using Directory Catalog technique.

Table Of Contents

  • History on multiple file assembly
  • What is MEF
  • General Architecture of Extensible Application
  • Implementing Windows Forms Application using MEF

History of multiple file assembly

To implement the multiple file assembly aka plugin application approach in past was very tedious work (I believe multiple file assembly is which uses more than one assemblies). Like in .NET application programs we had to use Reflection and Dynamic assembly loading and types tactics which were not reliable i.e. In case if any exception happens in the referencing assembly while loading into main program it would result in either a minor failure of a sub program or whole program leading to crash. However today we have a very good tool at hand from Microsoft, the name is Managed Extensibility Framework i.e. MEF in short name which I would be discussing in next few paragraphs.

What is MEF?

The answer is MEF is a composition layer or class library for .NET that improves the flexibility, maintainability and testability of applications of any size. MEF is used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to our applications. It also lets extension or plugin developers easily encapsulate code and avoid fragile hard dependencies between the applications. In the next section we would be directly going to architecture overview and implementation information.

General Architecture of Extensible Applications

Sample Architecture Overview

Here there are three major components

  • Main Assembly
  • Infrastructure Assembly
  • Plugin Repository

Main Assembly

Main Assembly is comprised of UI and Wire Line or Skeletal code to combine the building block of the application. This defines the Features and Functional limits regarding extensibility of our application. Controlling the program flow and loading plugins from the repository such as from local directory or download from global repository and so on.

Infrastructure Assembly

In Infrastructure assembly, we have interfaces and abstract classes defined which stands for two purposes:

  • Define the basic skeleton of the plugins assemblies which are to be plugged in the main application.
  • Enables the loose-coupling and balanced cohesion between the main program and plugin assemblies.

We have to design and implement the Infrastructure assembly modules step before we start implementing the plugin modules, and design decisions are based on the features and extensibility of the application. It purely depends on the Infrastructure assembly that we do not have to recompile the main application assembly, in case of any changes to accommodate any new requirement or extensibility of the plugins into the Infrastructure assembly.

Plugin Repository

In Plugin Repository, we can have many different implementations based-on the Infrastructure assembly. Each and every plugin may or may not have all the types definition that we have in the Infrastructure design. The plugin repository can be online like Nuget Gallery and Atlassian JIRA or may be offline based on the needs of the application.

Implementing Windows Application using MEF

Sample Architecture Overview from Visual StudioHere we have one visual studio solution named “DynamicAssemblyApp” and four projects in that:

  • DynamicAssembly.Infrastructure – It is Infrastructure assembly.
  • DynamicAssemblyApp – It is Main assembly.
  • DynamicAssembly.FedEx – It is an Plugin assembly for FedEx specific shipping implementations.

DynamicAssembly.USPS – It is an Plugin assembly for USPS specific shipping implementations.

So how is this application loosely coupled and how plugins work in application ?

Here the layer diagram below shows the strong-coupling between the different assemblies. On closely inspecting we can observe that the Main Assembly aka DynamicAsssemblyApp does not have connector to any of the plugins we have created. We make it possible using the MEF to load the plugin assemblies at runtime into the infrastructure instance models in the main application’s memory.

Layer Diagram

How does Sample Main Application looks ?

Main Assembly

As we click the Load Assembly button the application would lookup the plugin directory and load the different shipping methods into the main assembly and List them in the ListBox control placed on left-hand side.

Please note currently in MEF approach there is no easy way to unload the plugins once we have them loaded into memory as mentioned in one of the www.StackOverflow.com question here.

To understand the dynamism happening in the main assembly, I would like to show it in some steps as below

  1. Define the Export or ExportMany in the plugin assembly on the class definition which inherits from IShipping type (Only those classes which inherits from Interface defined in Infrastruture assembly can be marked as Export, so application would know that where the plugin instance fits).
  2. Define the location to load the dynamic parts into our application, i.e. a public variable or property of the Interface type from the Infrastructure assembly. Here is is IShipping type.
  3. Define the trigger for loading the plugins such as
    • At the start up of main application in background thread so as to not slow down the startup time (recommended).
    • On click of a button or dropdown selection (shown in the example).
    • On File Directory changes with using some File System watcher.
  4. After the trigger check the variable or property having the imports, and use in the application appropriately as per the requirements.

Please note: Import/ImportMany or Export/ExportMany can be based on three different ways

  1. String Key i.e. [Export(“MyTypeKey”)].
  2. Type Definition such as Interface i.e. [Export(typeof(IInterface))].
  3. Both from above (recommended, As this will help to uniquely identify the Import happening in the main application and we can Import the target type in different forms from one plugin assembly and in less strict manner) i.e. [Export(“MyTypeKey”, typeof(IInterface))].

Defining Export in plugin based on the type.

/// 
/// Define the FedEx method for Shipping
/// 
// Export attribute here declares that the assembly is,
// ready to provide this class to external application to use
[Export(typeof(IShipping))]
public class FedExShipping : IShipping

We import the plugin instances for FedEx and USPS Shipping Methods in Property ShippingList in the main application and declaration is decorated with ImportMany attribute which would import and instantiate all the class types inheriting from IShipping interface from the plugin assemblies into the specified property.

// Defining the imports from the plugin directory.
// Using ImportMany as we would be loading all the assemblies,
// containing the Export for the specified interface type.
[ImportMany(typeof(IShipping))]
public List<IShipping> ShippingList { get; set; }

On click of the button ‘Load Assembly’ we trigger the loading of plugins assemblies from the plugin directory in the application directory. The code for this as below

/// 
// Clean up previous Shipping Methods.
lstboxShippingMethod.Items.Clear();

// Using the directory approach for pluging/loading the assemblies dynamically.
// DirectoryCatalog constructor takes the input filepath for the plugins
// Here it is in the application directory i.e. /bin/plugin/*.dll
var catalog = new DirectoryCatalog("plugin");

// Compose container using DirectoryCatalog instance
var container = new CompositionContainer(catalog);

// Finally load the plugins
// Here we might face exceptions in loading and exception information
// is usually in the InnerException of the Exception.
container.ComposeParts(this);

// If we found no Exports from the plugins for the Shipping Methods
// then return empty handed.
if (ShippingList == null) return;

// Iterate thru each of the shipping methods and add to the ListBox Collection
// PS: We could do many other sort of things with the Imported the Shipping List.
foreach (IShipping item in ShippingList)
{
	lstboxShippingMethod.Items.Add(item.ShippingName);
}

The NameSpace for ImportMany attribute and DirectoryCatalog are as below respectively,

using System.ComponentModel.Composition
using System.ComponentModel.Composition.Hosting

So getting in action,

  1. Rebuild the solution.
  2. Rebuilding solution will copy the FedEx assembly in the main application plugin directory automatically, as it is coded in the plugin’s Post-Build commands (see in Project’s Properties) to copy it there in the plugin directory.
  3. Execute the main application.
  4. Click the ‘Load Assembly’ button.
  5. FedEx would be listed in the ListBox.
  6. Now copy manually the USPS plugin assembly (/bin directory contents) into the plugin directory.
  7. One more time click the ‘Load Assembly’ button.
  8. This time FedEx and USPS both would be listed in the ListBox.

And we are done with sample!

Download the sample application from SkyDrive here.

I hope this was pretty good to know & understandable regarding plugin applications and MEF. At the point now I think that I would publish the MEF version of the HB Code application in future.

Do comment below regarding what you think on plugin applications and using MEF.

Keep reading and keep your thoughts coming to the world out.

Some Recommended articles and questions regarding MEF and plugin applications.

 

Categories
.NET Setup

Installing .NET 3.5 service pack 1 along with application setup

Many of us would have been creating setups for applications either using WinForms or WPF and other such, but we really ignore the fact that users might not have all the prerequisites that our application requires to work.

Possibilities for that might be one or more as below:

  1. User do have .NET framework even installed.
  2. Users .NET framework installation is older or newer but not the required one.
  3. For example, user have .NET framework version 3.5 but not 3.5 SP1
  4. You have disabled to check .NET framework exists before application installs so application will not start all after installation, so users frusts and uninstalls your application.
  5. You have enabled to check and install .NET framework along with your application online, but you have ignored the fact that user might have no internet access on their system.
So what could we do for this ?
Solution is to include the .NET framework standalone setup installation in your application setup.
And steps to install the .NET framework 3.5 with the application are as follows:

Step 1 – Download the combined installation package for the .NET Framework 3.5 from Microsoft download site dotnetfx35.exe.
Folder view

 

Step 2 – After downloading this package, you have to extract the contents by running dotnetfx35.exe /x and it will prompt you with a location to extract the contents to a path.

Command prompt

 

Step 3 – Copy the contents of files and folder from {extracted path}\WCU\dotNetFramework to C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX35SP1
please note that to change ‘Program Files’ to ‘Program Files (x86)’ in above path if working on 64-bit system.

 

Step 4 – If you wish to get rid of the build warnings, you can update your PublicKey in the Product.XML with the following value: 3082010A0282010100A2DB0A8DCFC2C1499BCDAA3A34AD23596BDB6CBE2122B794C8EAAEBFC6D526C232118BBCDA5D2CFB36561E152BAE8F0DDD14A36E284C7F163F41AC8D40B146880DD98194AD9706D05744765CEAF1FC0EE27F74A333CB74E5EFE361A17E03B745FFD53E12D5B0CA5E0DD07BF2B7130DFC606A2885758CB7ADBC85E817B490BEF516B6625DED11DF3AEE215B8BAF8073C345E3958977609BE7AD77C1378D33142F13DB62C9AE1AA94F9867ADD420393071E08D6746E2C61CF40D5074412FE805246A216B49B092C4B239C742A56D5C184AAB8FD78E833E780A47D8A4B28423C3E2F27B66B14A74BD26414B9C6114604E30C882F3D00B707CEE554D77D2085576810203010001
Use this for both of the XPSEPSC* files.
Product.xml is located in ‘DotNetFX35SP1’ directory itself

 

Step 5 – In Visual Studio 2010, right-click on Setup project > Properties -> Prerequisites -> Select .NET Framework 3.5 SP1 > Below select the option “Download the prerequisites from the same location as my application” > Save changes

 

Step 6 – And last step is to rebuild the setup project and Test.

 

Reference links: