Wednesday, October 7, 2009

Build an application with Caliburn And Prism: Part 1 – Getting started

With the release of Caliburn V1 rapidly approaching, I’ve decided to take the time to demonstrate a really great feature in Caliburn V1 – Prism Integration.

In case you are not familiar with Caliburn or Prism I’ll start out with some links.

Check out Prism (also known as Composite WPF or Composite Application Library) – here

Check out Caliburn – here

Let’s begin with some project setup concerns, there are certain ways I like to setup and organize my folder structure which are helpful when you are trying to things like multi-targeting

image

Start with your typical SVN style setup with a src, lib and tools folder, but I’m going to add a Desktop folder under source where all of my Desktop (WPF) projects go. Later I will add a Silverlight folder so I can share a lot of code between the WPF and Silverlight versions of the application.

Take a trip out to codeplex and grab the latest binaries from the Caliburn site and put them in your lib folder. Great thing about Caliburn is that Rob’s included the latest binaries of all your favorite IoC containers and Prism so its a nice one stop shop to get you up and running quickly.

Enough with the boring stuff show me some code already!

So first things first, how do you bootstrap this thing? Well good thing for you Caliburn makes using Prism easier than using it by itself.

Open up visual studio and add a new WPF Application and name it [YourProjectName].Shell.

Add references to:

  • Caliburn.Core
  • Caliburn.PresentationFramework
  • Caliburn.Prism
  • Microsoft.Practices.Composite
  • Microsoft.Practices.Composite.Presentation
  • Microsoft.Practices.ServiceLocation;

Open up your App.xaml.cs file and add the following using statements to the top:

using Caliburn.Core;
using Caliburn.PresentationFramework;
using Caliburn.Prism;
Caliburn is typically configured in the App constructor like this:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
CaliburnFramework
.ConfigureCore()
.AfterStart(() =>
{
var binder = (DefaultBinder)ServiceLocator.Current.GetInstance<IBinder>();
binder.EnableMessageConventions();
binder.EnableBindingConventions();
})
.WithPresentationFramework()
.WithCompositeApplicationLibrary(CreateShell)
.WithModuleCatalog(new ModuleCatalog().AddModule(typeof(ContactsModule)))
.Start();
}

private DependencyObject CreateShell()
{
ServiceLocator.Current.GetInstance<IWindowManager>()
.Show(ServiceLocator.Current.GetInstance<ShellPresenter>(), null, ExecuteShutdownModel);

return MainWindow;
}

private void ExecuteShutdownModel(ISubordinate subordinate, Action completed)
{
completed();
}
}

Now you are probably asking yourself what’s up with CreateShell(), what in the world is a ModuleCatalog and where did this ContactsModule come from? Don’t panic… we’ll get there.

Let’s start with CreateShell(). Prism is expecting a shell view which will basically main window where you will “park” all of your other views into Regions on the shell. This is all very interesting stuff but first you need to add a few folders to your project so that Caliburn knows how to find everything. Add a Views and a Presenters folder to Shell project.


image

Just to get us started we’re not going to get fancy with the ShellView right now. Here a quick snippet using tab control as our region.


<Window x:Class="CaliBrism.Shell.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.codeplex.com/CompositeWPF"
Title="Calibrism" Height="300" Width="300">
<Grid>
<ItemsControl
x:Name="MainControl"
cal:RegionManager.RegionName="MainRegion"
/>
</Grid>
</Window>

Don’t worry about the code-behind right now we won’t need to do anything in there right now. Here’s the ShellPresenter:
namespace CaliBrism.Shell.Presenters
{
public class ShellPresenter : MultiPresenter, IShellPresenter { }

public interface IShellPresenter
{
}
}

Ok so now since we’re using a great composite framework in Prism. We need to add some modules. Start by adding a class library. I like to use a naming convention like [YourProject].Modules.[NameOfModule] so Calibrism.Modules.Contacts is born.

First thing you need to add references to Caliburn and Prism just like you did for the shell project and add a class ContactsModule to initialize your module.

The purpose of the Module class to register any services you may need to register and tell you module’s views which regions they need to park in.

namespace Calibrism.Modules.Contacts
{
public class ContactsModule : IModule
{
private readonly IServiceLocator _serviceLocator;
private readonly IRegionManager _regionManager;
private readonly IBinder _binder;
private readonly IViewStrategy _viewStrategy;

public ContactsModule(IServiceLocator serviceLocator,
IRegionManager regionManager,
IBinder binder,
IViewStrategy viewStrategy
)
{
_serviceLocator = serviceLocator;
_regionManager = regionManager;
_binder = binder;
_viewStrategy = viewStrategy;
}

public void Initialize()
{

var model = _serviceLocator.GetInstance<IContactsListPresenter>();
var view = _viewStrategy.GetView(model, null, null);

_binder.Bind(model, view, null);

_regionManager.RegisterViewWithRegion("MainRegion", () => view);
}


}
}

So now you may be asking what’s IRegionManager, IBinder, IViewStrategy, and IServiceLocator? Ugh so many many things. Well don’t worry for the most part you will only have to deal with this stuff in the ContactsModule after this Caliburn will take over alot of this complicated stuff. So here’s the quick and dirty on all these things

IRegionManager – Don’t let the name fool you. This guy manages Regions (gasp) basically your telling Prism “Hey put this view in the Main Region”

IViewStrategy – This one a little more tricky. This is the way Caliburn figures out what view belongs to a presenter you can read more about that here

IBinder – this guy binds your view to your presenter you can read more here

Ok so now you need to add the contacts list view… you know the drill not much different that the ShellView.

image

Xaml:

<UserControl x:Class="Calibrism.Modules.Contacts.Views.ContactsListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid Background="AliceBlue">

</Grid>
</UserControl>

Code:

namespace Calibrism.Modules.Contacts.Presenters
{
[Singleton(typeof(IContactsListPresenter))]
public class ContactsListPresenter : Presenter, IContactsListPresenter
{
public ContactsListPresenter()
{

}

}
}

namespace Calibrism.Modules.Contacts.Presenters.Interfaces
{
public interface IContactsListPresenter: IPresenter
{
}
}


Right now we just have a blank canvas. Next time we’ll add the fun stuff…



Stay tuned

Tuesday, August 18, 2009

How to send an email with an attachment in a SharePoint Workflow

SharePoint 2007 comes with several workflow activities out-of-the-box but the SendEmail activity does not allow you to send an email with an attachment.



You can however send an email using the standard System.Net.Mail SmtpClient. I'm not going to go into detail on how to enable outgoing email. Just open up the Central Administration site, click on the Operations tab, and click on Outgoing e-mail settings in the Topology and Services section.





The trick is finding the outgoing mail settings.


private string _outgoingMailServer;
private string _outgoingMailAddress;
private string _replyToAddress;

public Guid workflowId = default(System.Guid);

public SPWorkflowActivationProperties workflowProperties =
SPWorkflowActivationProperties();
public ArchiveBoxLabelWorkflow()
{
InitializeComponent();
}

private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
{
workflowId = workflowProperties.WorkflowId;
var webApp = workflowProperties.Site.WebApplication;

_outgoingMailAddress = webApp.OutboundMailSenderAddress;

_outgoingMailServer =

webApp.OutboundMailServiceInstance.Server.Address;

_replyToAddress = webApp.OutboundMailReplyToAddress;
}

private void SendEmailWithAttachment()
{
SmtpClient client = new SmtpClient()
{
Host = _outgoingMailServer,
UseDefaultCredentials = true,
DeliveryMethod = SmtpDeliveryMethod.Network
};

MailMessage message = new MailMessage(_outgoingMailAddress,
workflowProperties.OriginatorEmail)
{
Body = "<html><body>HelloWorld!</body></html>",
IsBodyHtml = true
};

byte[] bytes = Encoding.ASCII.GetBytes("Hello World!");

using (Stream stream = new MemoryStream(bytes))
{
message.Attachments.Add(new Attachment(stream, "test.htm"));
client.Send(message);
}
}


Wednesday, February 18, 2009

Neat Trick: Taking screen shots with snipping tool

So I accidentally stumbled apon a really cool trick (feature) in Windows Vista this morning!

In case you didn't know already Windows Vista has a screen capture tool built in called Snipping Tool. You can find it under your Start Menu -> All Programs -> Accesories -> [Snipping Tool]

So have you ever tried to take a screen shot of the pop up menu before? If you have you will find that if you try and print screen just the open window [Alt+PrintScreen] the pop menu will disappear.

You can do it with Snipping Tool.

Ok. Open snipping tool. When you open snipping tool your screen will fog over and you will be able to use your cursor to draw a rectangle to capture anything on your screen.

If you want to grab a drop-down menu, like when you right click on your My Computer icon. Open snipping tool and click cancel so your cursor returns to normal but leave snipping tool running, do not close it. Right click the My Computer icon and hover over the menu item you would like highlighted.

Now press [Ctrl+Print Screen]. Snipping tool is activated and your screen remains exactly as it looked when you pressed [Ctrl+Print Screen].



Sunday, December 21, 2008

How to make your blog wider

I really like the look of the rounders template on blogspot... the only wart on its nose for me is that is wasn't wide enough to post code examples.

I recently learned how to use CSS.

If you have firefox, I would recommend downloading the Firebug add-on it is a very useful tool for playing with CSS on a page in real time.

I would love to give a lesson on CSS and the wonderous power that lies with in, but to tell you the truth... CSS is best learned by "Trial and Error"

My recommendations are:

1. Download firebug or web developer for ie

2. go to cssZen Garden http://www.csszengarden.com

3. Play, play, play... that is the only way to figure things out.


Anyways here is the modified template for the rounders template to make it wider. I haven't altered the images yet to keep the nice rounded corners. I just took them out, to be honest I don't really care if they are rounded or not...

If anyone really misses them I would be willing to put a day in altering the images for you... (if I get enough comments requesting it)

go to this link, and download mytesttemplate.xml-1.ivn scouts honor it is not a virus or any thing. I tried to just provide the link to download but for some reason firefox will view and download it fine but ie doesn't link it at all. So if you have trouble with it use firefox.
Download my template

Thanks, God bless

Thursday, September 11, 2008

LinqPad - A must have tool!

Recently our development team has made some major advancements toward Test Driven Development and ORM Mapping. We have decided to go in the direction of .NET 3.5 Entity Framework and LINQ to SQL. A member of my team stumbled across LINQPad and has fallen in love with it.

I am just beginning to learn it myself, but I need to take a break and share with you BillKrat's blog post: LINQPAD - Using Stored Procedures / Accessing a DataSet

It gives you a step by step example of how to call a store procedure and return a queryable object.

Saturday, September 6, 2008

Getting Started



This marks my very first blog post, so I would like to take this opportunity tell you all a little about myself.

The purpose of this blog is to get my name recognized in the .NET community and to share with the world my experiences as I learn the vast majority of new technologies released with .NET framework 3.5

I have started this blog at the request of a very valued coworker, mentor, and friend, BillKrat. http://www.global-webnet.net/BlogEngine/default.aspx

I am 24 years old, I was born in Canyon, TX. My parents split when I was very young, so I grew up living with my mother and step father in Cresco, IA. I graduated High School in 2002 from Crestwood High School. After going to a few different colleges and a few different majors, I ending up majoring in computer information systems at Waldorf College in Forest City, IA.

My dad lives in Amarillo, TX, so while growing up I didn't get to spend a lot of time with him. Mostly holidays and a week or so every summer.

This summer I got an internship as .NET developer at Zachry Engineering Corp (formally known as Utility Engineering Corp) in Amarillo. As of August 25th ZEC extended me a full-time position, so now I am a full time developer there.

In my short three months working at ZEC I have learned far too much put into one blog post, hence the purpose of starting this blog. I have dabbled in ADO.net, WCF, Window services, Smart Client Software Factory(SCSF), Web Client Software Factory(WCSF), Web Service Factory(WSF), and much much more.



In my spare time I enjoy playing racquetball, learning, programming, and most of all MMA. One of my #1 passions is Mixed Martial Arts. I joined a MMA gym in July and managed to rope my Dad and my little brother to go as well. I am currently a white belt in Brazilian Jiu-Jitsu under Edgar Santos. Edgar is second degree black belt in BJJ under one of the Gracies, (Royler I think, but not for sure) he is from Rio de Janeiro. He only speaks Portuguese, so in my spare time I'm learning Portuguese too.


As I progress as a Developer I plan to post about my experiences and hopefully I can help some people out. Its not easy being on the leading edge and I hope to help everyone in the .NET community.

Thanks for reading...
God bless you all,

Ryan