LinkedIn



Friday, 21 December 2012

Sitecore 6.6 MVC3 and view models with MVC layout.cshtml


All,

I am posting what I have done here as I am not sure if it is correct. If it is correct, let me know but if not, feel free to comment so I can make it more best practice.

Firstly, my site is built in MVC3 using Sitecore 6.6.

I have a _MyMazdaMainLayout.cshtml which is my master page for my site. As you can see I am passing in a view model:


So originally I was hard coding the part shown in the above image but I wanted to read the details for my nav links from Sitecore.

I have some constants stored in my code pointing to my Sitecore items:


Here is my view model:


I tell Sitecore about my view model:


And I tell Sitecore that my _MyMazdaMainLayout.cshtml should use this view model:



It all works and seems fine.

Note there is no controller used here but I don't see my self needed any c# logic for my _MyMazdaMainLayout.cshtml. If I do, ill add partial views for that functionality.

So, does this look ok?

Questions / Comments?

thanks
RuSs

Monday, 10 December 2012

My Journey with Sitecore and MVC - View model builders

Hello,

Here is a small post on my experience with MVC controllers and view models. This post is not about Sitecore.

At times you will find that, due to the complexity of a View Model, your controller become a bit long winded. Controllers are called controllers for a reason, they control stuff. In my mind I see them as small traffic controller. Controllers get some data (parameters or view models) decide what to do with it and then direct the some data (view model) to a view or redirect.

Some view models may be simple. For example, you might have a view model with:

public class LogOnViewModel
{
    [Display(Name = "CustomerId")]
    public string CustomerId { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me when I log in again?")]
    public bool RememberMe { get; set; }
}

This is not a very complete view model so in theory your could just get your controller to build it up. I still recommend using a view model builder as you never know when you will need more complexity. Later, if you don't use a view model builder, you might get lazy and just dirty up your controller and wish you had a builder. I say, use one from the beginning.

If you have a more complex view model (the following is not that complex but you can see what i'm getting at) then you will start to find the need to put more code in your controller to build up collections for drop down lists (there may be a few of these in the form you are trying to render in your view), custom string formats or collections for other rendering needs.

public class DashboardViewModel
{
    public LogOnViewModel LogOnModel { get; set; }
    public IEnumerable < VehicleViewModel > VehicleModels { get; set; }
}

Here is an Index action on my DashboardController:

public ActionResult Index()
{
    var dashboardViewModelBuilder = new DashboardViewModelBuilder(VehicleManager);
    var dashboardViewmodel = dashboardViewModelBuilder.Build();

    return View(dashboardViewmodel);
}

As you can see I am using my own custom DashboardViewmodelBuilder which abstracts all the work that is required to build up my DashboardViewModel.

This means that my ViewModelBuilder can get as complex as I like whilst my controller stays nice and clean.

Here is my DashboardViewModelBuilder.

public DashboardViewModel Build()
{
    List < VehicleViewModel > vehicleModels = new List < VehicleViewModel > ();

    DashboardViewModel dashboardViewModel = new DashboardViewModel { LogOnModel = new LogOnViewModel() };
    var vehicles = VehicleManager.GetVehiclesByCustomerId(1);  //Yes I know, hard coding, ignore this

    foreach (var vehicle in vehicles)
    {
        var vehicleViewModel = Mapper.Map < Vehicle, VehicleViewModel > (vehicle);
        vehicleModels.Add(vehicleViewModel);
    }

    dashboardViewModel.VehicleModels = vehicleModels;

    return dashboardViewModel;
}

As you can see, it gets a IVehicleManager injected into it. I need this VehicleManager to get data from a database for my view.
I also use Automapper to map the Domain model Vehicle to my VehicleViewModel.
you don't really need to follow all this, i'm just trying to make a point that having all your logic to build up your view model inside a builder is much better than cluttering up your controller.

What you reckon?

thanks
RuSs

Tuesday, 13 November 2012

Upgrading an existing instance (Sitecore.NET 6.5.0 (rev. 111230)) to Sitecore to 6.6 (120918 => 121015)

Ok,

So I have done this a couple of time already but it always failed. After talking to Sitecore we realized that our existing Sitecore instance had file paths that were too long so the 6.6 installer was failing because of the 256 char. file path limit in windows:

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path isMAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string" where "" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
So after talking to Sitecore they suggested moving our Sitecore instance to something shorter like:
d:\S66
They also suggested giving full access to IIS_IUSER and the account the app pool runs under to the existing Sitecore instance website folder. Done!
Also Note: I dont have DMS installed on the existing Sitecore instance. I will install this after I upgrade.
First thing I am going to do is backup my Sitecore databases: Core, Master and web. Probably don't need to care about web but I did it anyway. Done.
Note: I will check that my current Sitecore instance runs correctly before I upgrade. Done.
Right so now I am ready to run the upgrade installer.
http:///sitecore/admin/UpdateInstallationWizard.aspx
I choose the package to upgrade from 6.5 to 6.6:
Sitecore 6.6.0 rev. 120918_fromv650rev110602.update
Then I click "View package information" and then "Analyse and install the package".
Ill analyse it first to see if there are any obvious issues before installation. It says it is running 5448 action.
The analysis of the results says:
730 potential problems were found, including 709 collisions and 21 warnings.
I am not sure what I can do with this information as, even when I "filter by message types" there is no obvious information on errors etc.
Next i'll click "Install the package" and see what happens. Note that, as I mentioned, I have done this a few times and it failed but hopefully with the new shorter path it will work.
Again, it says it is processing 5448 actions and in the "More information" section I can see it installing Sitecore bits and pieces. (go get a coffee as it looks like it is going to take an hour!)

Installer stopped on 119 actions and SQL processor was at 1.5GB so I rebooted my machine.
I ran the installer again and it seems to be running correctly now but again it failed at the end saying it could not find Lucene.NET.

I checked a fresh version of 6.6 for Lucene and all the version numbers are identical to my version but the file sizes are different so i'll copy the version from 6.6 into mine and try upgrading again ... ppphhhhht.

Ok, contacting Sitecore support again as it is failing on:

System.IO.FileLoadException: Could not load file or assembly 'Lucene.Net, Version=2.3.1.3, Culture=neutral, PublicKeyToken=null' or one of its dependencies

Ill post more when they reply and I try again.

Ok so I got some feedback from the Guys at Sitecore. We were using a Shared source crawler for our indexes. for now I have disabled /App_Config/Include/Indexing.config to /App_Config/Include/Indexing.config.disabled.

I ran the installer again and it worked, although I have 2500 warnings but it looks like it was just alerting me that it was overwriting files.
Right, next step run the upgrade script on master, web and core databases: CMS660_AfterInstall.sql. This worked. It seems to just create and update  the SQL tables ArchivedVersions and ArchivedFields.

After this I went through and did all the config changes required for 120918 and 121015 mentioned in the SDN posts above.

Note: Read the instructions for each config change very carefully, one mistake and you will have a world of pain.

So this all went fine. I did notice that I had a couple of config sections missing when comparing to the Sitecore original files on SDN so I amended where required. For example, step 17 here: 
http://sdn.sitecore.net/SDN5/Products/Sitecore%20V5/Sitecore%20CMS%206/ReleaseNotes/webConfig/660_120918/660_120918_65.aspx

says:
In the section, add three new settings related to the Page Preview feature, after the "PageStateStore" setting:
I was missing PageStateStore so I added it in. 

After that I needed to make my site run with MVC. As john West states, the latest Sitecore 6.6 installer (exe) enables MVC by default:
http://www.sitecore.net/deutsch/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/11/Sitecore-ASPNET-CMS-6-6-Installer-Enables-MVC-by-Default.aspx

But as I was doing an upgrade and not using the EXE I need to do some stuff with config files. I followed the instructions here:
http://sdn.sitecore.net/upload/sitecore6/66/sitecore_mvc_developer_guide-a4.pdf
At point 1.1.3 How to install Sitecore MVC.

Right, all done. 

The next step is to make sure it all works. I followed Sitecore John West's post here:
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/06/Sitecore-MVC-Playground-Part-1-Enable-MVC.aspx
Scroll down to the little heading: "To confirm MVC is working:" and follow his instructions.

Right, now I can get back to actually writing some code.

More to come on Sitecore with MVC in other posts.

thanks
RuSs

My Journey with Sitecore and MVC : part1

I thought i'd start a post about my journey with a green field project for a large client. 

The project is an web application that existing customers of a large vehicle manufacturer can log on to to view details of vehicles the customer owns. This includes service history
The project will be built in asp.net MVC3 and will be driven by an existing client database wrapped by a Java web service which I will consume.

The site will use content from an existing Sitecore instance that the client already uses to populate their current site.

There is a possibility of other custom data stores being needed as the requirements become clearer. These extra data stores will be in Sql server and I will use Entity Framework 5 as my ORM.

Here is a list of technology I will be using:

  • ASP.NET MVC3 with a possible mixture of web forms where required.
  • WCF
  • Sql server 2008
  • Ninject as my DI container
  • Moq for unit testing
  • Glimpse.MVC for debugging
  • Automapper - mapping my domain entities to my MVC view models
  • Glass.Sitecore.Mapper - for mapping my Sitecore content items to my domain model. This also gives me Sitecore context in my domain.
  • Sitecore 6.6
My architecture will be somewhat as follows:
  • MVC UI
  • Viewmodel per view 
  • View model builder abstraction to keep my view model code construction out of my controllers
  • A manager / business layer
  • A caching layer
  • I will use the repository pattern with unit of work where required although from the spec, there is no real immediate need for a Unit of work but I will put it in there anyway.
  • A service layer to consume the external service that is hosted at the client.
  • An ORM layer using EF for any custom data stores
  • Sitecore 6.6 that supports MVC3
  • My DI container will take care of IOC so every layer right up to my controllers will be unit testable (I will test where needed but not just do testing for the sake of testing.)
This first post is just a summary. I will post more as I continue.

RuSs




Tuesday, 21 August 2012

Attach Sql Database

This is just a little reminder to me on how to attach an existing database:

EXEC sp_attach_db @dbname = 'MazdaCleanSitecore_WebTarget',
@filename1 = 'D:\Data\Mazda\MazdaCleanSitecore_WebTarget.mdf', @filename2 = 'D:\Data\Mazda\MazdaCleanSitecore_WebTarget_1.ldf'
 
Fixing an orphaned user.
This used to be a pain to fix, but currently (SQL Server 2000, SP3) there is a stored procedure that does the heavy lifting.

All of these instructions should be done as a database admin, with the restored database selected.
First, make sure that this is the problem. This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
Thanks
RuSs 

Thursday, 15 March 2012

ASP.NET Membership System.Web.Providers. Can&apos;t log in to my siteon Azure but can locally.

Hi there,

I had an interesting issue last night. I deployed my local Azure emulated MVC 3 role and worker role to my Windows Azure instance. All worked perfectly locally and in particular the logon page I built allows me to log onto the secure area of my MVC 3 site using System.WebProviders (ASP.Membership).

I found an issue when I tried to log onto my remote Azure site using my deployed logon view.
The logon on the server failed and told me my user name or password was wrong.

Ok, so I then pointed my local instance ASP.NET configuration (the built in membership, role etc.. tool for setting up members and roles) at my Azure SQL database and tried to manage my members from there and it worked. 

Even when I changed my local connection string to point to my Azure SQL database and tried logging on, it worked. WEIRD!!! (ie.. local browser, remote Azure database).

So then today I fould this blog: 
and then this one:

The part of the post in particular that caught my attention was this:
I tracked it down, thanks to some info in this article by David Hoerster. The problem is that the default password hashing algorithm on Azure is different from the .NET 4.0 defaults. It is set to SHA1 on Azure, and HMACSHA256 is the new standard setting on 4.0.
The rest of the post is here:
This can be fixed by specifying the hash type explicitly in web.config. If you decide to use a method like HMACSHA256, make sure you also specify a machine key - otherwise you will run into similar problems as the autogenerated machine key will differ from server to server.
The configuration element you need to change is under :
<machineKey decryptionKey="PUT_DECRYPTION_KEY_HERE" 
            validationKey="PUT_VALIDATION_KEY_HERE"            
decryption="AES"            
validation="HMACSHA256" />
You can use this machine key generator to generate random keys in the proper format.

I will go home tonight and try this and update this post in the morning.......time passes.......ok, so went home last night and tried a few things. My password hashing algorithm was different between my local and azure. I just used the Azure machine config setting on my local and it all works fine now. Good times!!!

RuSs

Thursday, 8 March 2012

A look at ASP.NET MVC 4

Morning,

I am currently getting up to speed on MVC 4. Thought i'd post Scot Guthrie's video on the subject.












Here is the real link as I didn't want to embed the video as the width was to large:
http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2364

RuSs

Monday, 20 February 2012

My weekend (I'm a geek) of deploying my new Kite Boarding site to Windows Azure with an Azure SQL database, membership and blob storage

Good Morning,

I just thought I'd post to my blog after a long period of being to lazy to do it and also being too busy at work to get around to it.

I spent part of the weekend deploying my latest side project to Azure. I won't tell you what it's all about until I have it all polished and shiny as right now it's a definite work in progress.

What I have deployed:
  • MVC 3, Html5, Razor website - I'm thinking about moving to MVC 4 as I think the beta just came out.
  • The site runs off Entity Framework 4.3 and I used code first poco classes with DBContext.
  • Users and Roles are managed by  http://nuget.org/packages/System.Web.Providers 
  • My custom data is stored an an Azure Sql relational database 
I posted the following questions on MSDN and have now got the answers I need so i'll update the questhions with answers. As I was an Azure newbie a 2 weeks ago, these questions now seem a bit lame to me!!

Questions:
  • I have used an Azure SQL relational database for my database. They talk a lot about table storage. I assume I have done the right thing in using a relational database?
    Ok, so this one was easy. Whilst I could probably use table storage to store me data (xxx.table.core.windows.net) I am not ready to ditch my relational database way of thinking. My site will have many tables with relationships so for now I am playing it safe and using SQL Azure. I have, however, used blob storage (xxx.blob.core.windows.net) to store the gallery images I need for my site. So, and I may be wrong here, if I had a list of people whom each had a picture attached to their relational database record, I think I could store the blob Url in a field in their record and, when rendering, iterate the records and retrieve the blob image from my storage account.
  • I have used the http://nuget.org/packages/System.Web.Providers to manage users and roles. Once I deployed to Azure using the same database in my web.release.config for my custom data AND the membership tables it all works great. I can register a new user using the standard MVC 3 register user view and I can see this new user in my Users table inside the asp membership table.
    My question here then: and I have Googled this but cant find it, is how do I manage my users and roles on the azure server as I would when I use the asp.netwebadminfiles/default.aspx in Visual Studio? Do I, and I plan to this anyway down the line, write my own custom membership management code to do this or can I use an instance of asp.netwebadminfiles/default.aspx on the server somewhere?
    I figured this one out too. Although there are ways to use the netwebadminfiles tool to manage users and there is also third party code that can do this for you, ultimately I want to manage these users myself. I will build all my user and role code into the site.
  • When I deployed for the first time it created my web svc role on Azure AND my Sql database mentioned above. Lets say I have the site live for a few months and want to redeploy, will my membership and custom data get wiped out? What if a deploy schema changes to my database, will this be taken care of without affecting my data. I know I can use a one way data sync to get the data onto local but im sure I would not have to worry about this?Not 100% sure on this one but I now know that firstly, I don't have to redeploy / publish the whole site, storage and database every time I make a change. I can use Visual Studio WebDeploy to push new changes to my site. If I needed to sync data from my local I think I could use the Data Sync in the Azure portal and I assume I could manage my users via SQL mambership stored procs. until I get all my membership screens written.
thanks
RuSs

Tuesday, 6 December 2011

Saving the internet

All,

Quote from: http://www.avaaz.org/en/save_the_internet/?mzla

"As concerned global citizens, we call on you to stand for a free and open Internet and vote against both the Protect IP Act and the Stop Online Piracy Act. The Internet is a crucial tool for people around the world to exchange ideas and work collectively to build the world we all want. We urge you to show true global leadership and do all you can to protect this basic pillar of our democracies worldwide."

Please sign up to save the internet. This is important for all of us to continue to have an open and uncensored internet. Imagine if the police monitored all your phone calls, you wouldn't like that would you?

http://www.avaaz.org/en/save_the_internet/?mzla

thanks
RuSs

Monday, 7 November 2011

Explanation of Ninject Bindings and where we used them in our MVC Website (Part 1 - MVC Website)

Afternoon,

Im going to summarize what we have done with our Ninject bindings and injection which allows us to follow the "Inversion of Control (IOC Container)" principle in a project we are working on. 

As mentioned we are using Ninject as our IOC container: http://ninject.org/

The project architecture looks much like the following diagram:

Architecture Diagram

I will work my way from the top to the bottom of the architecture. Starting with the MVC web site all the way through to the Microsoft Crm layer.(This post  (Part 1 - MVC Website) just refers to the web site.)

One of the 2 BIG reasons we are using an IOC container (Ninject) is to allow us to separate all our layers (separation of concerns) so that they are Unit testable and also so that we can swap components out at a later date. We may want to replace our Crm later with a Sql server layer, doubtful but we are catering for this anyway as you never know what will be a requirement in the future. As long as our Sql server repository layer implements the same interface as our existing Crm repository layer, we can more or less swap out the Crm Repository with a new Sql Repository.

Mvc Website:
On the website layer we will be using Ninject to inject the following:
  • A GatewayAgent layer into our controller - the GatewayAgent layer separates the concerns of the controller from the concerns of our WCF SOA layer. 
  • An AutoMapper implimentation into our GatewayAgent - the mapper will map our presentation entities to our Domain entities.
  • Our presentation entity validation classes into our presentation entities - as we are using Fluent validation, we may want to ditch this later and inject a different type of validation.
The following diagram show part of the web site's global.asax file. This code uses Ninject to inject the above 3 items.

The Ninject Binding in the Global.asax class
Obviously, the web site has a reference to the Ninject.dll.

Most of this is set in stone for our site but one thing to note. As more development is done we will need to add more validators as we add more presentation entities to our site. So when we add an Invoice presentation entity to the site a related Invoice Validator class will need to be added to the ConfigureKernel method, shown above, in our global.asax file.

Note: the line:
- kernel.Bind<IValidator<Contact>>().To<ContactValidator>(); 
means, when we call validate on a Contact presentation entity, 
we would like to use the ContactValidator class to carry out the validation

Sample Contact Validator
You can see in the ConfigureKernel method above that we also inject a ContactGateway.
The following line shows this:
kernel.Bind<IContactGateway>().To<ContactGateway>();

This means that when we refer to IContactGateway we would like to use the concrete class ContactGateway.
So in our controller we see the following code:
Sample controller


Why is this good? Because you can then mock up a ContactGateway in a unit test to test your controller.

A unit test for the controller
As mentioned above, we also inject a mapper implementation into our web site:
kernel.Bind<IMapper>().To<AutoMapperMapper>();
This is used to map our domain entities to our presentation entities on the way up and our  presentation entities to our domain entities on the way down.

Why is this good? We may way to use a different mapping tool other than AutoMapper in the future. Injection will enable us to swap AutoMapper out for a different mapper tool.

This is the end of Part 1 - Explanation of Ninject Bindings and where we used them in our MVC Website

I will do another couple of posts on the other layers mentioned in the architecture diagram at the start of this post.

RuSs




Monday, 3 October 2011

How Jimmy Bogard does MVC

Bonjour,

Following is a link to a very good post called "How we do MVC" on some DOs and DON'Ts of MVC. We are about to start a fresh enterprise level project and this article is great for getting a few things done correctly from the start.


There is also another article he has written on "How we do view models":

Hope you find this useful.
RuSs

Monday, 26 September 2011

Entity validation, unit testing and MVC 3 with Fluent - RuleSets and Predicates


Morning all,

I have been looking at validation for my current project. We are building an MVC 3 site that calls a wcf service later that is wrapped around Crm 2011.

Initially I was looking at data annotations out of the box. These work really well and MVC 3 works seamlessly with these with client validation and unobtrusive JQuery. 

 When  I came to look at rulesets however it seems a lot more complicated. I them stumbled upon Fluent validation:

This is a very user friendly clean way of writing validation on your entities in the same way that data annotations are written. The difference came when I started to look at rule sets which you will see in my attached screen shots.

Firstly I defined 2 classes in my domain model. Thsese are called ContactForValidationPOC and AddressForValidationPOC as shown below:

 ----------------------------------------------------------------------------------------------------------



As you can see there are no data annotations and ContactForValidationPOC has a complex property of Addresses.

We are going to write some rulesets that will validate the contact for a STAFF ruleset and a public ruleset. (Note that there are not real world validation needs as of yet,it's just proof of concept code.)

You will notice that at the top of the ContactForValidationPOC class we have an attribute shown as follows:
[Validator(typeof(ContactValidator))] 
This tells the class that there is a validator class call ContactValidator somewhere.
Also please note that I have referenced the correct Fluent  validation dlls in my project. 
You can find the details of this here:
http://fluentvalidation.codeplex.com/ 
So back to the ContactValidator. Here it is:
You can see that we have 2 rule sets. The first is a staff rule set and the second is a public rule set. 
They are quite similar and the only difference really is that the Age must be over 18 for a staff member. 
Both rule sets also use a .Must predicate validator. 
This is a great place to put more complex logic.

Here we need to ensure that there is at least 1 address in the Addresses collection that is marked as IsPrefferedAddress.
Ok, so that is all done, now we need to unit test or validation rules.  
 
So I have a unit test written here. Firstly I set up a new ContactForValidationPOC entity and add a couple of addresses to it. 
I then call Validate on it and ask it to validate using the Staff rule set. After validation we check that the ValidationResult (result) is valid 
and then do a simple check for the number of validation errors. Obviously my test could be more detailed in a real world example. 
As I debug through my test I can see that my entity is not valid (IsValid = false
and it has a collection of validation errors on it.


This is good as we didn't enter a first name, our Age is under 18 and we set all AddressForValidationPOC's in the Addresses collection to IsPrefferedAddress = false.

Ok so we now know that our validation is working correctly on the server side.
We haven't even touched the MVC code yet.

I have whipped up a quick MVC controller with a view and have disabled the settings 
in the web.config that make client side validation work as shown in the following picture:


Note: they should be set to false to prove that server side validation is still working correctly now that we are validating through MVC.

Here are my controller and view: 
Note: I have just forced 2 addresses into the ContactForValidationPOC entity to make things easier, these are both set to IsPrefferedAddress = false 

Here is the view that kicked off the validation:


You can see that, when debugging the controller we get the same validation results. 
IsValid = false and a number of errors relating to our Staff rule set.

Note that in our controller we could have control over what rule set is loaded if we so desired:


We could use some logic to check what type of rule set to load, staff or public.

Now I will change the web.config setting to ensure that client side validation gets included:

We now can fire up the view in a web browser and see client side validation in action:

Well that is it, a high level explanation of domain entity server and client validation using Fluent, unit tests and MVC.

Some positive points:
Some possible negatives:
  • Only the following validators are supported on the client:
    - NotNull/NotEmpty

    - Matches (regex)
    -
    InclusiveBetween (range)
    - CreditCard

    - Email

    - EqualTo (cross-property equality comparison)

    - Length
  • Cant think of any more at the moment.
I hope this was helpful.


RuSs

Tuesday, 6 September 2011

EDMX or DbContext API

Hi all,

I have used EF for a while. I am used to using an EDMX file for my model. I have also recently used Code First and the DbContext API and I really like this.
Last night I started building an app. and was thinking, am I starting on the right foot? Do I use EDMX or DbContext API? If the thing i'm building turns out to be big, will I have chosen the right technology.

What if I use DbContext API and get it to generate my database. Obviously I don't want this to keep generating my database down the track when i'm at a stable point in development (or do I?). Then if I want to tweak my database or domain model will all the strings come un done?

The DbContext API is a simplified version. Will it do everything I need? I dont think ill need stored procedures as I can do everything with linq.

So my real question is. If I am building something that is serious and out there is the real world and it may turn out to require some complex coding, which way do I go? EDMX or DbContext API?

Is EDMX now old school? 

Comments / thoughts?

RuSs

Monday, 5 September 2011

A small update

Morning all,

Well it's been a while since I posted in my blog that i'm sure no one reads! I have finally got used to living in Melbourne and have started enjoying it more now that the weather is getting better.

I will hopefully be posting some interesting stuff on MVC up here is the next few weeks.
Here is a list of things I have looked at in the last few weeks.

  • MVC(3) - I have been trying to get around to getting up to date on MVC for years. Ever since I tried and failed to read Martin fowler's book on design patterns (http://martinfowler.com/eaaDev/uiArchs.html).
    Well finally I have got around to it and I love it. Combined with the Entity Framework edmx or code first it is such a great way to work. This is the way, for most sites, the web should be built. No hidden viewstate, no nightmare page load order and code that you have total granular control over. Awesome!!
  • Razor view engine - initially it looks dodgy but after a little playing around it's cleaner and easier to read than traditional asp.net forms. One thing I have learned about Razor is, if it looks messy and hard to read, then you probably have started putting business logic where it should not go.
  • Unit testing and TDD with MVC - Combined with Ninject and Moq this is easy. You can directly test your controllers. Compare this to ASP.NET web forms where your controller was, sort of, your code behind. You needed httpContext etc. Now you can test just your controller logic without other webby things clouding the test.
  • JQuery - ok so this is not new but im loving it so far.
  • NuGet - the NuGet package manager is quite cool. NuGet is a Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET Framework. When you add a library or tool, NuGet copies files to your solution and automatically makes whatever changes are needed in your project, such as adding references and changing your app.config or web.config file. When you remove a library, NuGet removes files and reverses whatever changes it made in your project so that no clutter is left.
    For example if you need to get the latest JQuery libraries into you solution you open Tools > library package manager > package manager console and type:

    PM> Update-Package jquery

    PM with auto update your JQuery to the correct version. Note that your references inside Views > Shared > _Layout.cshtml (for example) will not be auto updated.

Well, I know this is a bit of a lame post but it was more to get me back into the habit of writing on my blog. I hope to come up with some more interesting stuff soon.

RuSs

Wednesday, 8 June 2011

SQL Profiler - Being self-centered is a good thing (thanks Jeff Handley)

When I'm faced with app. debugging, especially procedures that take awhile to run, or require a series of steps in the application to fire off, I often use SQL Profiler to capture the SQL call.  Then I'll re-run the call directly in SQL Management Studio.  But SQL Profiler can bring back a lot of noise, making it tough to grab only what I need.

I finally created a custom trace template and set it to be my default.  It will only show me calls made from my local workstation to the development database. (we have a shared development database*)

This article will help you set up a personalised trace. For expample you can filter by Application Name or Host Name to reduce the noise in your trace.


Thanks
RuSs

Wednesday, 23 March 2011

Finding all stored procedures updated in the last (n) days

This was quite helpful:
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 30

Saturday, 15 January 2011

My new life in Melbourne

Morning, 


After 8 years in London I have decided enough is enough. I'm on the way to Melbourne to see what the future holds.
Im currently getting my CV ready and if anyone out there has any leads I can follow in Melbourne that would be great.
I'm currently in Sydney with my family and will head south in the next couple of weeks.


RuSs

Thursday, 11 November 2010

Re-map an SQL server login to a database login

Hello,


Sometimes users get un-mapped from the server to database login after a database restore.


Here is the command to fix it:
EXEC sp_change_users_login 'Auto_Fix', 'SRSUser'


RuSs

Wednesday, 10 November 2010

Workflow 3.5 and MOSS 2007 - This task is currently locked by a running workflow and cannot be edited.

Morning,


Today I had an interesting issue with my WF3.5 SharePoint workflow.
A user was attempting to action a SharePoint workflow task and was given the error:


This task is currently locked by a running workflow and cannot be edited.






I have seen this error a small number of times (5-10) amongst the 1000's of workflow instances that have passed through my production system.


I am always very careful with quiescing and always release a new workflow version the correct was using workflow.xml, feature.xml and stsadm.


There was a time a few weeks ago when we had to do an emergency bug fix as some of my business logic was not functioning as expected.


I know that I can never change an activity in my workflow without quiescing otherwise the serialization and deserialization (dyhydrate / re-hydrate) from the persistence store gets confused and hence an error like this occurs.


The funny thing is, I only changed code in a utility class and only the code inside an existing method (ie...method definition was not changed) so I thought that there was no need for quiescing. (no core workflow code was altered).


Anyway,just writing here incase anyone has an opinion on this. 


From now on I will quiesce no matter what the emergency is!!


RuSs

Tuesday, 19 October 2010

Workflow 4.0 Activity Designer

In this post i'm going to explain how to make a custom activity better visually. 
First of all I have a custom code activity called RequestManagerAction. It inherits from CodeActivity and overrides its Execute method. (I may do a post on code activities later).


The visual representation of code activity, by default, looks like this:
And by the end of this post it will look like this:
The first step is to create a new peoject for your activity designer. As we want to "design" RequestManagerAction I have created a new project called: RequestManagerActionDesignerLibrary. And inside this I add a new Activity Designer Item from the Workflow - installed templates called RequestManagerActionDesigner.xaml.


the initial view after opening RequestManagerActionDesigner.xaml is a split screen with the Xaml that represents the design in the bottom part of the screen and the actualy visual design in the top part.


In the bottom pane we can see the Xaml. First of all I want to set the Collapsible property to false as I don't want my designer to be collapsible. 


The 2nd taks is to add an ArgumentToExpressionConverter to my Xaml. This defines the mapping between arguments and expressions and provides the functionality to convert between these objects. Typically, this converter is used declaratively when using an ExpressionTextBox in a custom activity designer.




The next thing I want to do it sort out my layout. As my custom activity has 3 properties:


The main aim of what we are doing here is to show ExpressionTextBoxes for all 3 of these.
I will add a grid of 2 columns and 3 rows for our properties.




You can see that inside this grid we have some (3) collapsed TextBlock sections. I will explain these now.


Each TextBlock is for a property.
The first TextBlock is for the ExpenseRequest property of our custom activity:
You can see the obvious items marked out in the above picture.Note that the position inside the grid defined above is set by the Grid.Row and Grid.Column indexes which are zero(0) based.
You can also see that our expression text box is bound to ModelItem.SubmitExpenseRequest.


SubmitExpenseRequest is a class in my Contracts project that is part of my domain model:


The ModelItem represents the activity that that the designer is currently editing. This object sits between the visual elements that present an activity to the developer and the in-memory representation of the activity.


You can now see that we are well on the way to building our custom design:

I will now go ahead and add the other 2 ExpressionTextBoxes and the relevant properties.




You will notice the little smiley icon in the top left of the designer. To add this, I added the following xaml:


Now I am ready to associate my designer with the actual code activity that is already part of my workflow. If you remember it currently looks like this:
First I will add a reference to the project that my code activity is part of:


Once its referenced we can add an attribute to the top of our codeActivity class (Don't forget the System.ComponentModel import at the top!):


Once you have built the projects you will see the "RequestManagerAction" code activity in the toolbox. Drag this onto your workflow surface if it's not already there and you will see that the look of the activity is not just a small yellow box any more. Nice!! 



This is obviously more useful as we don't need to  use the properties pane to set the properties for our code activity, we can just type them straight into the workflow.

RuSs