Archive for category C#.net

Entity Framework “The data reader is incompatible with the specified complex type.”

I recently had this problem with a site I’m working on. I’m using Entity framework to access a bunch of legacy stored procedures, originally in MySQL but ported over to MSSQL. Having added the sprocs to EF and let it auto-generate it’s magic, I was shocked to find one of my calls throwing the following exception;

System.Data.EntityCommandExecutionException: The data reader is incompatible with the specified 'ChinookModel.GetVehicleDescFromModelId_Result1'. A member of the type, 'ivaluationid1', does not have a corresponding column in the data reader with the same name.
   at System.Data.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader storeDataReader, EdmMember member, EdmType currentType, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.CreateFunctionImportStructuralTypeColumnMap(DbDataReader storeDataReader, FunctionImportMapping mapping, EntitySet entitySet, StructuralType baseStructuralType)
   at System.Data.EntityClient.EntityCommandDefinition.FunctionColumnMapGenerator.System.Data.EntityClient.EntityCommandDefinition.IColumnMapGenerator.CreateColumnMap(DbDataReader reader)
   at System.Data.Objects.ObjectContext.CreateFunctionObjectResult[TElement](EntityCommand entityCommand, EntitySet entitySet, EdmType edmType, MergeOption mergeOption)
   at System.Data.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, MergeOption mergeOption, ObjectParameter[] parameters)
   at System.Data.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, ObjectParameter[] parameters)
   at Chinook.Model.ChinookEntities.GetVehicleDescFromModelId(Nullable`1 modelid) in C:\_Dev\Chinook\Source\Chinook.Model\Chinook.Designer.cs:line 160
   at Chinook.Model.GlassGuideDataProvider.GetVehicleFromModelId(Int32 ModelId) in C:\_Dev\Chinook\Source\Chinook.Model\GlassGuideDataProvider.cs:line 104
   at Chinook.Services.VehicleDataLookup.GetVehicleForRegistration(String reg) in C:\_Dev\Chinook\Source\Chinook\Services\VehicleDataLookup.asmx.cs:line 81

It seemed to be moaning that one of the columns in the complex type I set for it to use as the return type, doesn’t match to a column actually being returned, despite entity framework having auto generated that type itself! The cause was, as is generally the case, user error. Inspecting the sproc a bit closer I noticed one of the columns was being returned twice, using the same name. EF generated me a call with an iValuation and iValuation1 column, but failed to match iValuation1 because in reality both columns were simply called iValuation! So a simple, and kind of obvious fix, but worth noting to stop someone else loose a little more hair when they’re confonted with this error!

No Comments

Random Band Generator!

Just a quick post to mention that I’ve uploaded the Random Band Generator- just a bit of fun I boshed together built for a mate… check it out here.

No Comments

MVC strongly typed view returns a null model on post back

I recently ran into a problem where a form I had built (using the view creation dialogue) would always return a null model on post back.  The code was pretty simple;

        //
        // GET: /StockAdjustment/CreateForPart/{PartId}
        //[RequireRequestValue("id")]
        [Authorize(Roles = "Administrator")]
        public ActionResult CreateForPart(Guid id)
        {
            StockAdjustment sa = new StockAdjustment() {
                Part = parts_repo.GetPart(id)
            };

            return View(sa);
        }

        //
        // POST: /StockAdjustment/CreateForPart/{PartId}
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult CreateForPart(Guid id, StockAdjustment adjustment)
        {
            if (ModelState.IsValid)
            {
                adjustment.AddedBy = User.Identity.Name;
                adj_repo.Add(adjustment);
                adj_repo.Save();

                return RedirectToAction("Details", "Parts", new { Id = id });
            }
            else
            {
                adjustment.Part = parts_repo.GetPart(id);
                return View(adjustment);
            }
        }

The ModelState would always be invalid, despite the the fact that my data was all valid and fine. When I picked into the ModelState error using immediate mode I found the reported error;

ModelState.ToList()[0]
  {[id, System.Web.Mvc.ModelState]}
ModelState.ToList()[0].Value.Errors
  Count = 0
ModelState.ToList()[1].Value.Errors
Count = 1
    [0]: {System.Web.Mvc.ModelError}
ModelState.ToList()[1]
  {[adjustment, System.Web.Mvc.ModelState]}
ModelState.ToList()[1].Value.Errors[0]
{System.Web.Mvc.ModelError}
    ErrorMessage: ""
    Exception: {"The parameter conversion from type 'System.String' to type
    'SimplyModel.Models.StockAdjustment' failed because no type converter can convert between these types."}

So model state contained the ID which had no errors, and adjustment which has this weird type conversion error. After a bit of hunting around my code I realised the problem- StockAdjustment has a field called adjustment which is an integer, however on my post back handler, i told MVC that my model instance should be called adjustment- so it looks like the MVC binder has got confused and figured the form field “adjustment” must represent the entire StockAdjustment model- i simply changed the method signature to accept the model with another name, and it all started to work;

        //
        // POST: /StockAdjustment/CreateForPart/{PartId}
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult CreateForPart(Guid id, StockAdjustment a)
        {
            if (ModelState.IsValid)
            {
                a.AddedBy = User.Identity.Name;
                adj_repo.Add(a);
                adj_repo.Save();

                return RedirectToAction("Details", "Parts", new { Id = id });
            }
            else
            {
                a.Part = parts_repo.GetPart(id);
                return View(a);
            }
        }

6 Comments

C# Dynamic keyword, and how you can use it to help TDD!

Just done some reading on the new dynamic typing stuff in .net 4 and it occured to be you could use this to assist using TDD “Test First” approach, where you write code to test methods that you’ve not yet written.  Unless you stub the method, you get compile errors, however using dynamic, the compiler doesn’t evaluate your call until run time, so your test will actually compile and you will get the expected red cross until you’ve actually implemented your method.  Turns out I’ve been beaten to this conclusion though; check out this post on Peter Gfader’s blog

No Comments

Grabbing mashed .net Control ID’s using jQuery

I need to grab a bunch of controls from repeater items in .net – They are all prefixed with something like ctl00_Content_ctl00_rptLines_… and then the actual ID I set for the control- with dot net v4 you can set your own client Id’s so this isn’t a problem, but i’m using an older version. It’s easy enough to do partial matches with jQuery;

$("span[id$='_txtName']") // match the section at the end

// you can also match text at the start, or in anywhere in the string using the following
$("span[id^=text]")
$("span[id*=text]")

No Comments

Need to cause a full page post back from a specific control within a repeater, within update panel!

UpdatePanel and triggers from a repeater control – ASP.NET Forums.

No Comments

Telerik Sitefinity- Retrieving a page by it’s URL or GUID- or finding a page’s GUID from its URL!

I recently started work at my new job, and here we use Telerik Sitefinity as the CMS for some websites.  I was recently tasked with writing some code which involved supplying the end url for a page, and then matching this against the corresponding record in the CMS- after much searching I found nothing and eventually got a response from their support so figured i would blog it!

var url = "~/test2.aspx";

var Manager = new CmsManager();
int totalRows;
List conditions = new List();
CmsSiteMapNode node = (CmsSiteMapNode)SiteMap.Provider.FindSiteMapNode(url);

// here is the GUID for the page
var pageId = new Guid(node.Key);

conditions.Add(new CmsQueryCondition("ID", Nolics.ORMapper.Base.QueryCondition.EQ, pageId));
// and here is the page
var result = Manager.GetPages(0, 0, string.Empty, System.ComponentModel.ListSortDirection.Descending, conditions, out totalRows);

1 Comment

Uh Oh! Important: ASP.NET Security Vulnerability – ScottGu’s Blog

Important: ASP.NET Security Vulnerability – ScottGu’s Blog.

No Comments

Why ASMX web services are not an excuse anymore with WCF 4.0 – Pablo M. Cibraro (aka Cibrax)

Why ASMX web services are not an excuse anymore with WCF 4.0 – Pablo M. Cibraro (aka Cibrax).

No Comments

ASP.net File Uploads with NeatUpload

File Uploads are a fickle thing, and have been.. well.. always. ASP.net has it’s own default max file size, IIS is also put under strain while processing large files and trapping excpetions when file’s are too large, or providing progress bars during the process is a fiddly process.

I’ve recently started using NeatUpload which is an HttpModule which takes care of uploads, streaming the data straight to storage on the file system, or sql- taking a load off of IIS and also offering progress bars!

It’s a fairly old project, which has only recently gone up on codeplex- check it out!

,

No Comments