Learning WPF

As a .net developer that has recently spent over a year helping to design and build a SCSF winforms application, I have been looking to branch out into different techniques and technologies to improve my skill set.  With Visual Studio 2010 coming out, the latest support for WPF and a push, by Microsoft, toward its advancement in the development community, I am intrigued to say the least to check it out. I do not consider myself a UI designer, and lack the artistic skills to become one, so learning WPF seems like a daunting task.
I did find the following website to help with my desire to learn WPF: www.wpftutorial.net. There is a great Getting Started section which will get you on your way to understanding the basics. From learning XAML and basic MVVM concepts, the tutorial is presented in an easy-to-understand format. There is also plenty of information that advanced users may find useful.
Stay tuned for additional info as I learn WPF.

-Craig

Posted in General | Leave a comment

Handle asp.net MVC session expiration

Here is a really simple way to handle a session expiration in asp.net MVC using a base controller.  Having all controller inherit from a basecontoller and overriding the OnActionExecuting event allows for checking the session before all actions are executed.

Here is the code

public class BaseController : Controller
{
    protected override void OnActionExecuting
        (ActionExecutingContext filterContext)
    {
        // If session exists
        if (filterContext.HttpContext.Session != null)
        {
            //if new session
            if (filterContext.HttpContext.Session.IsNewSession)
            {
                string cookie =
                    filterContext.HttpContext.Request.Headers["Cookie"];
                //if cookie exists and sessionid index is greater than zero
                if ((cookie !=null) &&
                    (cookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    //redirect to desired session 
                    //expiration action and controller
                    filterContext.Result =
                        RedirectToAction("SessionExpired", "Home");
                    return;
                }
            }
        }
        //otherwise continue with action
        base.OnActionExecuting(filterContext);
    }
}
}

This simple but effective method ensures that no actions will be executed if the session has expired forcing the user to login again

-Craig

Posted in .NET Framework | Tagged | Leave a comment

EF4 and WCF Data Services presentation materials from Hartford Code Camp 3

As some of you know, I presented on Entity Framework 4 and WCF Data Services 4 at Hartford Code Camp back on June 19th. I have posted the material from the code camp here.

For next time, I may try to turn this into two separate presentations and beef each up with more nitty-gritty. I know I have been asked  to dive into item-level and field-level security so I will attempt to do so for the next New England Code Camp in Waltham.

Slide Deck (PPTX): EF4 and WCF Data Services 4 – Max Weber – Tallan

Slide Deck (PPT): EF4 and WCF Data Services 4 – Max Weber – Tallan

Entity Framework project: EF4Presentation.Solution

Entity Framework + WCF Data Services project: BlogModel solution modified

Don’t forget to check out Elisa Flasko’s article on Entity Framework 4.0 and WCF Data Services 4.0 in Visual Studio 2010 – this was the basis for the BlogModel solution and is good at guiding one through setting up a WCF Data Service with EF4.

Posted in .NET Framework, Enterprise .NET, Presentations, User Groups, WCF | Tagged , , , , , | 1 Comment

ASP.NET MVC Primer – Presentation Materials

Here are the links to the material from the ASP.NET MVC 2 Primer presentation given at the 3rd Annual Hartford Code Camp on Saturday, June 19, 2010:

Powerpoint Slides: Primer.pptx

Source Code: PrimerDemoSource.zip

Disclaimer:

I have done some Very Bad Things™ in this code in order to speed up the presentation that are always considered bad practice.   The most egregious violation of best practices is the inclusion of the data access code in the controller’s action methods.  Please do not use this code as a basis for your application design, especially when it comes to best practices.  My next post will include the information covered in the advanced section along with a lot of material we never got to.  This will be a much better demonstration of proper design.

Also, look for upcoming screencasts on ASP.NET MVC2 and other development topics posted here and/or on my personal blog at http://blog.gerety.net , which should be up and running in the next few days.

Posted in .NET Framework, Enterprise .NET, Presentations, User Groups | Tagged , , | 3 Comments

S#arp Architecture

I have been doing some work and research with ASP.NET MVC 2.0.  My first interest was to try to figure out how to get Dependency Injection working with ASP.NET.  I started doing investigating how to link in Springframework.net.  This direction led me down a track that required some manual configuration.  This is when i found S#arp Architecture, which I found very interesting since it gave you the benefits without the configuration up front.

S#arp Architecture is a project template for Visual Studio that will set you up with a ASP.NET MVC application that is already wired up for Dependency Injection and using nHibernate for data access.  more information can be found on the S#arp Architecture website and wiki.

My findings so far have been very positive.  Within about 45 minutes I had a web application with some basic CRUD functionality.  This functionality included unit testing at every layer.  It seems like a great way to start a project and easily promote best practices like dependency injection and test driven development.

Posted in Enterprise .NET | Tagged , , | Leave a comment

.NetTiers Architecture – Design Patterns Used

The .NetTiers code generated framework provides a ton of functionality out of the box. I will not go into the Data Tiers such as the Entities, Data, and Data.SqlClient as deep because it’s a typical n-tier Data setup. What I’d like to focus on is the business/component layer.

First, before generating the component layer you can choose in the codesmith template a design pattern. The choices in the drop-down is: ‘Domain Model’, ‘Service Layer’, and ‘None’.
Obviously, if you choose to use .NetTiers for just the CRUD generation then select ‘None’. Selecting ‘None’ basically “draws the system boundary line” to the Data provider tier so the client or your custom business tier will call directly to this generated data tier.
The Domain Model pattern provides a web of interconnected objects. This pattern creates objects that represent both data and behavior. Most of us in the software world has built applications using this model. I will blog more on this option soon. Here is the UML…
The third option ‘Service Layer’ is what I will be focusing on in this blog post. In this type of command pattern, think of the Service Layer as the application’s system boundary. It provides the contract of how the client will interact with your system. Here is a diagram representing where the Service Layer is found:
When the Service Layer is generated, out of the box NetTiers will wrap your Data provider CRUD methods and add the following:

- Authorization – Uses Enterprise Library’s Authorization block. Basically you can set up AD groups and create a XML file that maps Users to the Entities and it’s methods. So for example, if you had a ‘Reader’ AD group and that group can only call the Get… methods.

- Exception Handling – Again, uses Enterprise Library’s Exception block and you can set up Exception polies quite easily.

Even if you do not put any business logic in the Service Layer, generating this tier will still provide the CRUD methods with the Authorization and Exception handling pre-wired. More specifically, the contract will be basically the same as the Data Provider methods with added functionality of Authorization and Exception Handling (which is worth it!).

If you would like to use this Service Layer for more robust business logic, it provides the framework based on some best practice patterns: Command Pattern, Processor Pattern, Routhing Slip Pattern, and Strategy Pattern. The Routing and Strategy is optional if you wanted to implement the processor pattern.

Command Patern: Serves as the workflow pipeline – a service instance provides the workspace for implementing your service type behavior. NetTiers provides the framework that allows you to add processors to the service and those processors are executed in the stated order. For example, let’s say you have a OrderService that would have a CreateOrder behavior. This behavior or use case would include many logical units of work including Validate Inventory, Check Inventory Location, and Place Order. You would load this pipeline up with each logical unit of work and call the OrderService.execute to process each behavior. Each process or behavior is represented by a class in NetTiers called a ‘Processor’. Here is the UML for the command pattern:


Processor Pattern: As I just mentioned, the Processor class represents each logical unit of work in any given Use Case (they could overlap, thus making them more flexible and resuable). For example, a processor called ‘ValidateInventoryProcessor’ may be used in the OrderService.CreateOrder and also OrderService.ManageNightlyOrders. You would create a new Processor class for each logical unit of work. This Processor class will inherit NetTier’s generated class ‘ProcessorBase’ which implements IProcessor interface. Basically, override the Process() method for your custom implementation in your new processor class.

So for new processor classes ValidateInventoryProcessor, LocateInventoryProcessor, and PlaceOrderProcessor you would do something like this to add them to the command/workflow pipeline for that service:
orderService.ProcessorList.Add(new ValidateInventoryProcessor(order));
orderService.ProcessorList.Add(new LocateInventoryProcessor(order));
orderService.ProcessorList.Add(new PlaceOrderProcessor(order));

As you can see, what would normally be coded in the Manager itself is now pulled out and can be used accross any service/use case. Pretty Flexible!!!

The ProcessorList provides the workflow pipeline for the order service. When execute is called it will iterate and call the Process() method for each of the processors loaded in that sequence. Additionally, NetTiers will track the results and state of each processor and store the results in a ServiceResult class. This class will track broken rules and exception errors as it’s iterating each processor. This generated class implements the IProcessorResult and returns a GenericProcessorResult. So the execution of the service works as simple as this:
ServiceResult = orderService.Execute();

If you want to know if any problems occurred, you would simple call the HasErrors:
if( ServiceResult.HasErrors) …{handle them here…}

Here is the diagram of the Processor Manager Pattern: As mentioned earlier, this ProcessManager manages sequence and state of each processor (logical unit of work).

Here is a screen shot of the Generated Service project from NetTiers. Notice the Processor folder and the base/interface classes generated for you. You would simple add your Processors in this directory:

Routing Slip Pattern: This is an extension of the Processor pattern when sequence is not known at design time. Implementing this pattern is optional and can add more flexibility to your application. The idea here is that instead of coding the Manager to load each Processor in a certain sequence you implement the routing slip to instruct the manager what to process next. To implement this, attach a Slip to the message specifying sequence of processing steps (as opposed to the process manager coded for this). Next attach special message router class that reads the Routing Slip. Here is a diagram of the Routing Slip Pattern:

Strategy Pattern: Finally, for even more flexibility you can utilize the Strategy pattern. This pattern utilizes small classes that contain different algorithms. So instead of putting the caculateInventory logic in the Process() method of the ValidateInventoryProcessor class, you can create a strategy class called ‘EasternRegionInventoryStrategy’, ‘CentralRegionInventoryStrategy’, and ‘WesternRegionInventoryStrategy’. Each one of these concrete classes inherits from a base strategy class ‘RegionalInventoryStrategyBase’. Now, any processor class can call the algorithm based on the context.
Class Diagram for Strategy:

 

Example of Strategy class: ‘EasternRegionInventoryStrategy’
Context Class: ValidateInventoryProcessor
Abstract Strategy Class: ‘RegionalInventoryStrategyBase’
Concrete Classes: ‘EasternRegionInventoryStrategy’, ‘CentralRegionInventoryStrategy’, and ‘WesternRegionInventoryStrategy’

Obviously, this adds quite a bit more complexity and can always be implemented later by pulling out the algorithm in the Process() methods. If you are new to patterns or NetTiers you may want to do this later.

Implementing best practice patterns has long been accepted as a way of architecting software. The key is to go ahead and do your homework, understand the patterns, and then implement them. The great thing about NetTiers is that the framework is generated quickly and ready to use.
References used:
http://nettiers.com/ComponentLayer.ashx
http://www.dofactory.com/

Posted in Enterprise .NET | 1 Comment

BizTalk Property Schemas in Different Namespaces

In BizTalk 2006 R2, I have noticed that sometimes the promoted property fields are not available.  This seemed to be a random occurance so I decided to spend a little time investigating.

Problem Scenario:
The property schema field will not show up in a Receive Shape filter. No matter how many times you build, rebuild, and close the solution it will not show up.  Just for kicks, I set the property schema field to “MessageContextPropertyBase” (the default is MessageDataPropertyBase). I then built the project and sure enough the property field now shows up.  Good right?  Wrong – This type is only used for property fields that are promoted that are NOT included in your message.  For example, if you had a custom pipeline that promoted a property not included in the message schema.  The MessageDataPropertyBase should be used for fields included in the message.

Ok, so I started looking into this further and decided to open up an orchestration that was working with the Receive Shape filter.  The property field used as the filter was in the same namespace as my orchestration’s message schema. The previous test that did not work used a message that was in a different BizTalk project than the property schema.

Cause:
A property schema used in a different BizTalk project will not be available in Receive Shape filters. This also applies to intellisense used in the expression shapes.  I am not sure if this a BizTalk bug or Microsoft intended this design.  It seems like a proper design to have one common property schema for the solution where fields are available across projects.

Resolution:
Create a property schema in each BizTalk schema project.

Hope this helps in your future development where the promoted property field is not available.

Posted in BizTalk, Biztalk Tutorial | Tagged , | 1 Comment

BizTalk File Backup

Business or system constraints may force you to leverage BizTalk for File backups.  BizTalk can actually handle this pretty well if it’s planned out carefully.

Here is a diagram of the overall design:

One way to implement this is to set up a receive port and location to poll the original drop location of the files.  This receive location will be set up as PassThruReceive where no disassembling of the message will occur (actually there are no pipeline components for PassThru).

Receive Port

General

Name

FileReceive

Receive Locations

New (see below table)

Receive Location

General

Name

FileReceive.FTP

Type

FTP

Configure FTP (note this can be any adapter type)

Receive Handler

BizTalkServerApplication

Receive Pipeline

PassThruReceive

Next, create two new Send PassThru ports that subscribes to that receive port using Filters.  The first Send port will send the message to a backup folder.  The second port sends the message to a new file receive location that will be polled for incoming messages for processing.

Use the follow configurations for the Send PassThru for backup files.  Use the macro %datetime% and %SourceFileName% for the backup directory file names.  The %SourceFileName% retains the original file name including the extension.  Remember that macros are case sensitive.

Send Port

General

Name

BackupFileCopySend

Type

File

Configure file location to backup directory

File name = %datetime%_%SourceFileName%

Send Handler

BizTalkServerSend

Send Pipeline

PassThruTransmit

Filters

Property ‘BTS.ReceivePortName’

Operator ‘==’

Value ‘FileReceive’

The second send port will send the file to the new file drop location.  Your receive ports for processing will poll this new location.  Use only %SourceFileName% macro to cary over the original file name.

Send Port

General

Name

FileInSend

Type

File

Configure file location to new file drop directory.

File name = %SourceFileName%

Send Handler

BizTalkServerSend

Send Pipeline

PassThruTransmit

Filters

Property ‘BTS.ReceivePortName’

Operator ‘==’

Value ‘FileReceive’

Set both of these ports up by changing the Send pipeline to PassThruTransmit.  Messages that are processed via BizTalk have context properties even though it’s PassThru.  Use one of the context properties in in the Filter property: BTS.ReceivePortName == ‘FileReceive’ (name should match rcv port above).  Now, every message that arrives from our receive port will be copied to the backup file directory and the new incoming file drop directory.

The last step is to set up a receive port that polls the new file drop location.

Posted in Biztalk Tutorial | Tagged , | 1 Comment

Transform System.Drawing.ContentAlignment property to System.Drawing. StringFormat Alignment property

Recently we had the need to transform System.Drawing.ContentAlignment property to System.Drawing. Stringformat alignment property for creating a Graphic object with text drawn on it inside a given rectangle.  Assuming that you want the text printed from left to right, you can use the ContentAlignment Enum values to obtain the desired StringAlignment Enum value.  For example:
   1: public StringFormat TransformProperty(ContentAlignment alignment)

   2:         {

   3:             StringFormat myStringFromat  = new StringFormat();

   4:             switch(alignment)

   5:             {

   6:                 case ContentAlignment.MiddleLeft:

   7:                     myStringFromat.Alignment = StringAlignment.Near;

   8:                     break;

   9:                 case ContentAlignment.MiddleRight:

  10:                     myStringFromat.Alignment = StringAlignment.Far;

  11:                     break;

  12:                 default:

  13:                     myStringFromat.Alignment = StringAlignment.Center;

  14:                     break;

  15:             }

  16:             return myStringFromat;

  17:         }

Craig

Posted in General | Leave a comment

Adding SQLite to a Windows Mobile Application

Using SQLite in a Windows Mobile Application provides a simple way to add pre-populated data for consumption by the application.  There are a couple of configuration considerations when adding the database to the project.

1. Adding reference to SQLite.dll. After installing SQLite there will be a Compact Framework folder in the following path :C:\ProgramFiles\SQLite.NET\bin.  This folder contains the System.Data.SQLite.dll that needs to be referenced.

2 The same path will also contain the dll which Windows Mobile will need to invoke the methods contained in the SQLite.dll.  The following file needs to be added to the project which contains the main executable,  SQLite.Interop.065.DLL.

Once the interop dll is in the project you can start using SQLite in the Mobile Application just as you would for any other application.

Craig

Posted in General | Leave a comment