Friday, November 30, 2012

MVC 3 to MVC 4 Project Upgrade Configuration Error __WebPagesVersion__.0.0

No comments:
I've seen a few posts on forums like Stack Overflow recently regarding issues when upgrading from an MVC3 to an MVC4 site regarding Web Pages version configuration. Whilst I haven't experienced the problem myself it revolves around web.configs


Presumably this is meant to be replaced by a version number but in some cases isn't and so the whole entry looks like so:


<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=__WebPagesVersion__.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

To fix the error simple replace the __WebPagesVersion__ with 2.0 so it looks like the following


<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

It's also worth running Find in files for this errant string and/or checking any other web.configs in your solution and ensuring that the Version reference is 2.0.0.0 and not 1.0.0.0 or ___WebPagesVersion___.


References:

http://stackoverflow.com/questions/13443152/configuration-error-while-using-areas-in-asp-net-mvc-4/13585812#13585812 


http://www.asp.net/whitepapers/mvc4-release-notes
Read More

Thursday, October 18, 2012

Empire Avenue: Week 1 - It Really is Social Media Rocket Fuel!

1 comment:
In my previous few blog posts I've been talking about my experience with www.EmpireAvenue.com . In effort to record and indeed share the experience I've created this post!

EAv (Empire Avenue) is part game, part social media, part marketing tool, bear with me and Ill try to explain as much as I know as simply as possible.

The Game

The game is based around a stock market idea but the stock is you - or in fact all the users signed up. Using a digital currency (Eaves) you get to buy or sell shares in whomever you choose. Each user gets "paid" in eaves each day depending on your social media interaction that day. The more social you are the more you earn. As shares are bought and sold and users' activity gets logged their share price moves up or down depending on how well they've done. When you own stock in someone else you'll also receive a dividend dependant upon their performance. Your stocks are held in a portfolio where you can track, watch and filter searching for sliders or gainers to buy and sell more shares in.

The Social Media

For the game to work like a real stock market you need a very large very active user base to keep things interesting. Fortunately EAv is bursting to the seams with all manner of social media fanatics - I was astounded at how active the user base was! For such a new system (only two years old) it seems to contain a huge number of heavy hitting social media, marketing, digital, entrepreneurial users who've all mastered klout and kredz and have clearly moved on. I've seen an extra 100 followers on Twitter and double the number of blog visits I get in just this one week. If you want the pulse of social media and marketing look here first and follow these people heavily.

The Marketing

OK so once you get to grips with the game, have a portfolio, followed/linked/friended/subscribed your shareholders and the people in whom you've bought shares its time to sit back, take a breather and look at missions. Once your share price hits 30 (day 2 or 3 if you're social) the ability to create Missions is unlocked. Missions allow you to "pay" users to undertake certain actions. Generally this centres around some form of social media action such as liking a page, retweeting a tweet or something of that nature. This is genius, for one thing, its easy and free (although you can pay real money for virtual eaves should you wish).

Getting social media interaction going on this basis with this user base creates a very positive feedback loop, it generates social media actions from the EAv community which in turn creates more eaves which helps share prices rise which increases dividend and portfolio value. Because this is social media Klout and Kredz will take notice and the halo effect will raise you scores there too - you become more influential. All of this makes you more visible, followable and likeable. And so this awesome whirlwind of interaction and payback unfold beautifully before you in real time.

Summary

I've thoroughly enjoyed my first week on EAv; I've learned a lot and got some awesome followers and followees on Twitter and seen my Klout score rise 3 points. Don't be shy have a go, get to grips with it and enjoy the ride!

If you enjoyed this blog post please use the side menu to share it, subscribe, like it and follow me on Twitter, buy some shares in me - and leave a comment! I'd be very much obliged! ;o)
Read More

Tuesday, October 16, 2012

ADO.NET + DataTables vs Dapper.NET Benchmarks

2 comments:
In my previous blog post I was looking at Dapper - basic insert and select operations versus an raw ADO.NET. In order to perform some basic speed tests (and compare lines of code written) I added a new page to my project called Benchmark.aspx with a single PlaceHolder control (called Container) to hold the results.

The code and results below demonstrate that for large queries using Dapper can cut execution time by about four fifths (in my not very scientific tests). If you're thinking of using Dapper you can use/modify the code below to prove to yourself that it will be faster. This is basic boiler plate code that you can modify to perform your own analysis. Please excuse the inline SQL!

As a small aside Marc (the creator) says that in later builds of Dapper.NET you don't even have to open the connection - it will do it for you!

For more comprehensive and detailed benchmarks please see this post here


Results
Dapper inserts: 100, time taken: 00:00:00.4724731
Dapper inserts: 1000, time taken: 00:00:05.3936728
Dapper inserts: 10000, time taken: 00:00:15.3227475

ADO.NET inserts: 100, time taken: 00:00:00.0400515
ADO.NET inserts: 1000, time taken: 00:00:03.8124865
ADO.NET inserts: 10000, time taken: 00:00:18.4029055

Dapper Select: 10, time taken: 00:00:00.0164510
Dapper Select: 100, time taken: 00:00:00.0017245
Dapper Select: 1000, time taken: 00:00:00.0033249
Dapper Select: 10000, time taken: 00:00:00.0296995

DataTable Select: 10, time taken: 00:00:00.0008202
DataTable Select: 100, time taken: 00:00:00.0014142
DataTable Select: 1000, time taken: 00:00:00.0097499
DataTable Select: 10000, time taken: 00:00:00.1048403

Code:

using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DapperSandbox
{
    public partial class BenchMark : System.Web.UI.Page
    {
        public class DapperUser
        {
            public Guid Id { get; set; }
            public string Firstname { get; set; }
            public string Surname { get; set; }
            public string Email { get; set; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RunDapperInsertBenchMark(100);
            RunDapperInsertBenchMark(1000);
            RunDapperInsertBenchMark(10000);

            RunAdoInsertBenchMark(100);
            RunAdoInsertBenchMark(1000);
            RunAdoInsertBenchMark(10000);

            RunDapperSelectBenchmark(100);
            RunDapperSelectBenchmark(1000);
            RunDapperSelectBenchmark(10000);

            RunDataTableSelectBenchmark(100);
            RunDataTableSelectBenchmark(1000);
            RunDataTableSelectBenchmark(10000);
        }

        private void RunDapperInsertBenchMark(int iterations)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < iterations; i++)
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
                {
                    connection.Open();
                    connection.Execute("UserInsert", new { Id = Guid.NewGuid(), Firstname = "First", Surname = "Second", Email = "Email" },
                        commandType: CommandType.StoredProcedure);
                }
            }
            stopwatch.Stop();
       Container.Controls.Add(new LiteralControl(string.Format("Dapper inserts: {0}, time taken: {1}
", iterations.ToString(), stopwatch.Elapsed)));
        }

        private void RunAdoInsertBenchMark(int iterations)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < iterations; i++)
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand("UserInsert", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@Id", Guid.NewGuid());
                        command.Parameters.AddWithValue("@Firstname", "First");
                        command.Parameters.AddWithValue("@Surname", "Second");
                        command.Parameters.AddWithValue("@Email", "Email");
                        command.ExecuteNonQuery();
                    }
                }
            }
            stopwatch.Stop();
       Container.Controls.Add(new LiteralControl(string.Format("ADO.NET inserts: {0}, time taken: {1}
", iterations.ToString(), stopwatch.Elapsed)));
        }

        private void RunDapperSelectBenchmark(int numberOfResults)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
            {
                connection.Open();
                var rows = connection.Query("SELECT TOP " + numberOfResults.ToString() + " * FROM dbo.[User]", commandType: CommandType.Text).ToList();
            }
            stopwatch.Stop();
            Container.Controls.Add(new LiteralControl(string.Format("Dapper Select: {0}, time taken: {1}
", numberOfResults.ToString(), stopwatch.Elapsed)));
        }

        private void RunDataTableSelectBenchmark(int numberOfResults)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            DataTable results = new DataTable();
            List user = new List();
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("SELECT TOP " + numberOfResults.ToString() + " * FROM dbo.[User]",connection))
                {
                    command.CommandType = CommandType.Text;
                    results.Load(command.ExecuteReader());
                    foreach (DataRow row in results.Rows)
                    {
                        user.Add(new DapperUser() { Id = Guid.Parse(row["id"].ToString()), Firstname = row["Firstname"].ToString(), Surname = row["Surname"].ToString(), Email = row["Email"].ToString() });
                    }
                }
            }
            stopwatch.Stop();
            Container.Controls.Add(new LiteralControl(string.Format("DataTable Select: {0}, time taken: {1}
", numberOfResults.ToString(), stopwatch.Elapsed)));
        }
    }
}
Read More

ADO.NET & Dapper.NET using C# & ASP.NET

No comments:
I posted my first question on StackOverflow the othe dayr. A question regarding best practise for high speed raw data access (Follow the link for the full blown version). In short however it centred around whether there was a faster way to access the data than executing a stored procedure and loading a DataTable with the ExecuteReader results.

At first most respondents (some with >5k scores) said that this was generally the fastest way and that everything I was doing was correct. However Marc Gravell  (A Microsoft MVP and Moderator of StackOverflow) kindly posted an awesome response! In order to increase the performance of StackOverflow he and Sam Saffron had developed a very small .NET ORM called Dapper.NET .

Essentially what this allows you to do is fire inline SQL or stored procedures from a IDBConnection type and return statically typed results! This is awesome if you just want to get data really fast and don't require the overhead of a DataTable that has functionality to manage relationships and track changes and such forth.

In the jQuery AJAX, Web 2+, ASP.NET MVC world this is more often than not what you're trying to acheive, very fast smallish selects/inserts and updates and whilst Entity Framework, LLBLGEN, NHibernate etc have their advantages sometimes they are waaaaaaay more than you need and can add unecessary complexity.  

Because Dapper.NET removes all this complex relationship management overhead it can outperform most data related operations compared to its heavier siblings. In short, its about as fast as you can get within the framework! Heres a small sample of code I wrote to add and return users from a database - this is ALL the code I had to write and notice the statically typed objects Im using - no nasty DataTable["SomeColumnName"] references - just POCO ;o)

Steps for setup:
Create a Blank Web Application (I chose WebForms for ease but MVC is equally applicable)
Create a Db
Add Db Connection String to Web.Config
Create UserInsert Stored Procedure
Create UserSelectAll Stored Procedure

Default.aspx.cs code:

using Dapper;
using System;

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DapperSandbox
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            BindUserResults();
        }

        public class DapperUser
        {
            public Guid Id { get; set; }
            public string Firstname { get; set; }
            public string Surname { get; set; }
            public string Email { get; set; }
        }

        private void BindUserResults()
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
            {
                connection.Open();
                var rows = connection.Query("UserSelectAll", commandType: CommandType.StoredProcedure).ToList(); 
                ResultsView.DataSource = rows;
                ResultsView.DataBind();
            }
        }

        public void Add_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
            {
                connection.Open();
                connection.Execute("UserInsert", new { Id = Guid.NewGuid(), Firstname = Firstname.Text, Surname = Surname.Text, Email = Email.Text },
                    commandType: CommandType.StoredProcedure);
            }
            BindUserResults();
        }
    }
}
Read More

Friday, October 12, 2012

Empire Avenue - Social Media Stock Market Game

1 comment:
So I happened across Empire Avenue yesterday - some two years after it went live (where have I been)?! After getting slight addicted to it yesterday and scratching the surface of some of its features I thought I'd write up some findings!

The purpose is evidently to "have fun" after all its a game. People "buy" stocks in your and you in others - depending on your Social Network reach and influence your stock goes up and down and you earn or lose Eaves (the virtual currency). So far so good fairly straight forward, but its not just a game is it?!

No its not JUST a game, the most intriguing feature for me, certainly for a Social Media Impact point of view is the Missions tab. This is where users (or businesses) can set up a reward scheme (payment in Eaves generally) for you taking some action. The actions are generally quite straight forward such as "Like my page" on Facebook or "Follow me on Twitter" or retweet such and such. Now whilst this isn't necessarily going to create long standing stalwart followers or indeed a sustained growth - it lends itself nicely to Brand/Product promotion endeavours.

If you need to "get the word out" setting up a mission and getting people to post and/or tweet about whatever it is will certainly have a halo effect and get your product/service in front of peoples eyes - and hopefully the more eyes see it the better the chance that they will convert to sales.

In summary Empire Avenue is Fun but it definitely has potential as a bona-fide marketing tool/technique in the right circumstances.

In a completely un scientific test I noted that on the day I joined EA my blog got twice the hits it does on any other normal day - whether this is sustained or not is unknown - its only been 24 hours after all!

Further info can be found here:
http://en.wikipedia.org/wiki/Empire_Avenue
Read More

Thursday, October 11, 2012

Empire Avenue {EAV:d546ce401f8dfec8}

2 comments:
{EAV:d546ce401f8dfec8}

This is a verification blog post for Empire Avenue - an exciting and interesting new take on Social Networking; I only joined today and Im quite smitten - Ill write a proper post all about it when I've got to grips with it a bit more!
Read More

Wednesday, October 10, 2012

ASP.NET MVC 4 & jQuery Mobile

No comments:

Whilst doing my usual round of research I have discovered that within the Developer Preview release of ASP.NET MVC 4 they have included two interesting features. Firstly Adaptive Rendering by Browser and the Mobile Application project type.

The first of these allows the developer to provide different Views depending on the relevant (mobile) browser. The Mobile project type is specifically geared toward creating mobile web apps. Further to this the mobile functionality is provided out-of-the-box by inclusion of the jQuery Mobile 1.0.1 framework.

What does this mean?:

As Microsoft are backing both jQuery and jQuery mobile by including them in its development platform by default and indeed contributing significant enhancements to the jQuery project (See Data Validators and jQuery Validation plugin). I believe that we should follow suit and any efforts toward learning/providing mobile web app functionality should be focused primarily on the jQuery Mobile framework. A list of graded browser support for the platform can be found at the following location:

http://jquerymobile.com/gbs/

What does this mean for Native iOS and Andriod Apps?

Actually not  a lot, native apps will still need to be created in either XCode 4 (iOS) or eclipse (Andriod) or indeed using PhoneGap on a mac – there may be other options going forward – VSNomad or indeed the C# compiler for Mac (Which made such an impression Ive forgotten its name) but PhoneGap seems to be the most mature environment for Cross-Platform native apps for the time being.

Interestingly if the “App” doesn’t require any native functionality (Turning on the camera flash for instance) then it would be feasible to create a “shell” native app n phone gap that simply includes the browser control as a full screen view and points at the URI for the Web App. This essentially would create a “hard coded” browser pointing to the URI of choice. In turn this means that the Web App part could be build within visual studio (or any other IDE for that matter) and a native app could be created very quickly to point at the online resource.

Read More

MVC 4, Signal R & Web API Dual Start Up Projects!

No comments:
For a while now I've been using Visual Studio 2012 and investigating it's new features (which are many) as well as looking at the new project types and other offerings such as the new project templates and new technologies like Signal R. I decided that the best way to get a handle on all of this was to create a sample solution using as much of it all together as possible. My idea was to have a solution with a couple of projects, I'd use MVC 4 with Signal R for the Web UI and a Web API project as my Service/Data layer. To that end I set about creating the solution with two projects. At this point I was a stuck - how do I run both the Web UI front end and the Web API service layer at the same time - traditionally you only have 1 start up project!

This is where Visual Studio 2012 with IIS Express comes in handy - you can set Multiple Start up projects really simply. In essence all you have to do is right click on each project in turn - go to the web tab of the properties page and ensure both projects are using IIS Express and using different ports. Then right click on the solution node then click Properties. Select the Common Properties node then Start up Project. Click the radio button that says Multiple Start up projects and use the Grid to select the start up action of each project within the solution. With that done all you need do is hit F5 and both projects will start-up (and debug if desired) and you're ready to go!


Read More

Wednesday, June 20, 2012

Visual Studio & IIS Express : Add static content mime types like ".WebM"

No comments:
I took over a project the other day which had cause to use video in WebM format. Cassini (bless it) flatly refused to do anything at all with the file and one of the requirements was to take some action after the video finished playing. Not wanting to code this "blind" I decided it was about time to upgrade to IIS Express (I already had Visual Studio sp1 installed but not from the Web Platform Installer). I went off and downloaded the executable and followed the following instructions to set it up.

IIS Express Download:
http://www.microsoft.com/en-us/download/details.aspx?id=1038

Installation and Setup Instructions:
http://blogs.msdn.com/b/webdevtools/archive/2011/03/14/enabling-iis-express-support-in-vs-2010-sp1.aspx

WebM File Format Details (See naming section):
http://www.webmproject.org/code/specs/container/

Once this was completed I simply had to navigate to the installation directory and run the following command and presto everything worked! My advice, drop Cassini and use IIS Express immediately!

Installation directory:

C:\Program Files (x86)\IIS Express

Command to enabled WebM:
appcmd set config /section:staticContent /+[fileExtension='.webm',mimeType='video/webm']
Read More

Wednesday, May 16, 2012

Which property caused "System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." exception?

No comments:


Sometimes when using ASP.NET MVC 3 / 4 with Entity Framework it can be difficult to see exactly which property is causing issues when db.SaveChanges() is called.

If you wrap the db.SaveChanges() in an appropriate try {} catch {} block whilst debugging (see below) each property in conflict will be written to your debug console which is much more helpful in finding and resolving the problem!

Don't forget to remove the try catch block after your debugging session though otherwise exceptions will be swallowed and disappear in a live environment which will then hinder further debugging efforts!

[Authorize(Roles = "SomeRole")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string SomethingsName)
    if (ModelState.IsValid)
    {
        db.Something.Add(new Something()
        {
            Id = Guid.NewGuid()
            ,
            Name = SomethingsName
        });
        try
        {
            db.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Debug.WriteLine("Property: {0} Error: {1}",
                               validationError.PropertyName,validationError.ErrorMessage);                 }
            }
        }
    }
    return RedirectToAction("Index");




Read More

Monday, April 23, 2012

ASP.NET MVC 3 Generating an ActionLink in the controller - Html.ActionLink Equivalent

No comments:
Generating routing links is extremely easy in MVC 3 using @Html.ActionLink(linkText,action,controller) when you're using Razor views this is great. However sometimes you need to generate the link within the controller - at which point you do not have direct access to the Html helper.

In these instances such as creating links for a wysiwyg editor or adding a link into an email it is preferable to have the system generate it with the appropriate protocol http/https and/or a port number if you're running locally. To this end I did some digging and put together the following little code snippet which does eactly that!

I thought I'd share it here to save me having to look it up again in the future!


            string absoluteAction = string.Format("{0}://{1}{2}",
                                                  Url.RequestContext.HttpContext.Request.Url.Scheme,
                                                  Url.RequestContext.HttpContext.Request.Url.Authority,
                                                  Url.Action("ActionName", "ControllerName", new {Id = "Data"}));
Read More

Wednesday, April 18, 2012

MVC 3 ModelState Validation after Postback - Page.Validate() equivalent

No comments:
I've been tinkering with MVC 3 for a while now and I have to say I'm extremely impressed - it is a joy to work with as are its supporting technologies Entity Framework, ASP.NET Routing and Razor view engines to name a few.

However I've been working on WebForms for so long that I'm finding more than a few stumbling blocks as I grapple my way up the learning curve. One such hurdle was "How do I re-validate a model after its been posted back to the server". The scenario being I want a user to type a plain text password into a form which is required but not persisted - I used [NotMapped] DataAnnotation attribute in the model definition to get this bit done.

Following that on postback I need to create a Salt (required and persisted) and a PasswordHash (required and persisted). Trouble was, I originally had the Salt and Hash properties within my if (ModelState.IsValid) statement.

The Model was at this point invalid because no password hash or salt had been created yet. "Easy" I thought simply elevate the property assignments above the if condition. No luck (but along the right lines) as the properties were now filled but I needed to Re-Validate the model, no Page.Validate() to rely upon at this point so I did some digging. As it turns out you simply need to call two methods (below) and they are roughly equivalent to what a WebForms guy would consider to be Page.Validate().


p.Salt = CreateSalt(36);
p.PasswordHash = GenerateSaltedHash(UTF8.GetBytes(p.Password), p.Salt);
ModelState.Clear();
TryValidateModel(model);
if (ModelState.IsValid)
{
p.Id = Guid.NewGuid();
db.People.Add(p);
db.SaveChanges();
return RedirectToAction("Index");  
}
return View(person);


Read More

Saturday, March 03, 2012

Grow your sector knowledge using Twitter and Conferences

No comments:
Hello again!

I've been following Microsoft development for years now and the advent of twitter gave me a brilliant insight into Microsoft developers thoughts and keeps me abreast of current feeling about technology by those developing it. For years i used Google Reader and added blogs and such forth to achieve the same result but it was must less immediate and much more in-depth.

This week has been a great week on twitter for me keeping up with what's going on at the MVP Conference (still not quite made it to MVP myself but that's all part of my life time goals plan ... ). OK so here a really obvious tip that only just occurred to m,e (stupid) if I hit the #mvp12 link in twitter and then hit the people link - presto a complete list of everyone who was at MVP and who is also on twitter - amazing - all the people i need to follow in one place:

https://twitter.com/#!/search/users/%23mvp12

I went through and more than quadrupled the amount of people I followed BUT hopefully this will give me an excellent view into what's happening going forward!

The same technique should work for any industry and any conference so if you're not sure who to follow and who's making noise in your industry target a conference and away you go!
Read More

Wednesday, February 29, 2012

ASP.NET Location Node in web.config

No comments:
Just a quick one today! This has probably been around for a while now but yesterday I had good cause to use this handy piece of functionality!

The location tag within the web config file of your asp.net 4 website allows you to specify a location tag with a path attribute and set "web.config" style setting for just that single location! This is particularly handy if you need to set request upload limits or request validation settings for a particular page that handles file uploads or downloads.

Here is an example which allows for the upload of very large files and allows a URL Encoded filename (with some very odd characters) to be downloaded


  
  <location path="somefolder/download-resource-page.aspx" allowOverride="false">
    <system.web>
      <httpRuntime requestValidationMode="2.0" executionTimeout="3600" maxRequestLength="1048576" requestPathInvalidCharacters="" />
      <pages validateRequest="false" />
    </system.web>
  </location>



This location section should be placed within the <configuration> tags!
Read More

Thursday, February 16, 2012

ASP.NET Entity Framework 4.3 - What's my Id???

No comments:
Whilst working on a simple data access layer using Sql Ce 4, POCO C# and using the Repository Pattern it occurred to me that when implementing a SaveChanges method that there was no real effective way to prevent a subsequent developer coming along and instantiating a new instasnce of some entity, directly setting the Id property and calling SaveChanges! I thought about nesting the entity within the repository and changing access levels on classes and properties but nothing really worked.

At this point I figured that there are much smarter people out there that have already solved this problem - I'll just have a look and see how they did it (A good view when standing on the shoulders of giants!).

I fired up visual studio, hit nuget for EF 4.3 updated everything, wrote a very contrived example waited for an exception at which point I'd delve into the code and possibly with a little reflection work out what was going on.

Sadly that's not what happened. I discovered that if you instantiate an instance of an entity manually populate its Id and call save changes it simply quietly adds it to the db with the next available identity and carries on!

Although this may well never actually happen in the real world I thought it was interesting none the less.

If I'm being a complete idiot here please do let me know!

- Class1.cs

namespace FactoryPatternSandbox.Core
{
    public class TestContext : DbContext
    {
        public TestContext()
            : base("name=conn")
        {
 
        }
 
        public DbSet<ExampleItem> ExampleItemSet {getset;}
        
    }
 
    public class ExampleItem
    {
        public int Id { getset; }
        public string Text { getset; }
    }
}

Default.aspx
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (Core.TestContext context = new Core.TestContext())
            {
                Core.ExampleItem example = new Core.ExampleItem();
                // Set Id to a random hard coded int
                example.Id = 1234;
                // Set arbitrary text value
                example.Text = DateTime.Now.ToString();
                // Add to context with Id 1234
                context.ExampleItemSet.Add(example);
                // output Id to Literal (Output = 1234)
                something.Text = example.Id.ToString();
                context.SaveChanges();
// At this point the Id *should* have been added to the DB as 1234
// or thrown an exception e.g. CannotAssignIdToNewEntityException()
// However checking the DB the item has been added with the next
// available Id as per a normal INSERT INTO with an IDENTITY column specification
// But its not actually told us (via an exception) that the Id value
// has indeed changed so when we call for our random hard coded int
// it throws an exception saying there are no items in the collection.
Core.ExampleItem exampleFromDb = context.ExampleItemSet.Where(l => l.Id == 1234).Single();
 
            }
        }
    }
Read More

Monday, January 09, 2012

Manage multiple updates to Data using C#, TSQL and OPENXML in SQL Server

4 comments:
I'd like to share this little technique I've been using for quite a while, especially to receive feedback and validation on whether or not this is a good idea!

I've used this technique with great success in the past in production systems which require a a "grid" of check-boxes and a single "update" button. This kind of thing usually occurs when you have any X can be related to any Y in a many to many kind of relationship. It comes in especially handy when mapping Users to Roles or that kind of thing. Though it can easily be adapted to manage multiple updates of anything in ONE database hit.

Traditionally this kind of code ends up hitting the database either once per cell in the grid or once per row in the grid because SQL Server doesn't allow arrays of things to be sent to a stored procedure. Database hits are expensive and generally less is better.

My technique leverage's SQL Servers ability to access XML data using the OPENXML keyword. When the grid of check-boxes is submitted we gather together the form collection elements (those check-boxes that have been ticked) and create an XML snippet of the results. This is then passed to SQL Server as a single input representing a set of information. OPENXML is then used inside the stored procedure to convert the XML into a temporary table which is then interrogated and used to update the relationship information that the check box represents.

Below is a link to a visual studio 2010 project that you can download , it contains all the source code for the project please feel free to download and try it for yourself - if you find it useful or have an idea of how it could be improved please leave a comment at the bottom of this page.

I have used MVC 3 and SQL Server as a simple container for the project but the technique is equally valid for any type of project Classic ASP, ASP.NET Web-forms included, so long as the RDBMS supports XML the technique will be valid.

I will refrain from a long explanation here as the code is simply one model, controller and view and the database contains just three tables and two stored procedures. If you'd like some more detail please leave a comment at the bottom of the page and Ill update as soon as possible. If I get a lot of feedback then I will flesh out the method some more in a series of posts.

I do hope you find this useful and would love to hear from you!

Project files can be downloaded here  and unpacked using   7zip

Read More

Thursday, January 05, 2012

disqus.com for @blogger @blogspot comments - really rather good!

No comments:
Having not made a new years resolution at the time I have decided that it should be "use my blog more often". I'm doing quite well this year so far but to be honest its quite tricky fitting it in "out of hours" what with the twins, learning guitar and Skyrim being released but we can but try!

This post centres around the ease with which I managed to sign up for and integrate Disqus comments into this very blog. It turns out that to replace the (fairly basic) standard Blogger comments with Disqus is REALLY straightforward. Simply a case of signing up to Disqus pointing it at your blog and clicking the appropriate options.

Disqus accounts are free (though there are paid for versions) and it adds a social edge and more integrated experience if you're a Blogger or a commenter. I original was looking to integrate LiveFyre but it didn't seem to offer the kind of seamless integration and ease for which I was looking (I may be wrong but Disqus just made it so easy!).

Anyway if you're looking for "comments on social steroids) I would definitely recommend it if you're serious about building communities around your content!

http://disqus.com

http://www.livefyre.com/
One last word on LiveFyre if you're looking for something a bit different it works just like other comments managers however it also include live chat as a first-class feature which, when you see it, really is quite impressive!
Read More

Wednesday, January 04, 2012

Kodak ESP 5250 All-in-One Colour Ink-jet - Printer / copier / scanner

No comments:
Having bought Kodak Camera's for both myself and my mother in law I decided to give the following printer a try when it came time to replace an older Epson model that got damaged in a house move a while ago. I have to say it is astounding for the price. B&W printing is both fast and sharp whilst the colour prints are beautiful even on normal paper! Let alone its excellent Wi-Fi facilities, combine that with its excellent cloud printing software (sadly this model does not support it natively but the software works very well indeed) its an all round winner!

Kodak also do iPhone, iPad and Andriod apps for printing directly from your smart devices for free which also "just work" - usually printers (at least for me) are a nightmare but setting all this up was a breeze!

Kodak ESP 5250 All-in-One Colour Ink-jet - Printer / copier / scanner:

'via Blog this'
Read More