Showing posts with label MVC 5. Show all posts
Showing posts with label MVC 5. Show all posts

Tuesday, November 29, 2016

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery' to type of 'System.Web.Mvc.SelectList'

Problem:

Had a solution using the Entity Framework which required a query modification. 


Solution was:
return new SelectList(db.Offices, "Office_ID", "Office_Name");


Changed too:


public class SecurityGroup
{

public string ADGroupSID { get; set; }
public string ADGroupName { get; set; }
public Guid Office_ID { get; set; }
public string ADUser { get; set; }

}


List<FCJC.Model.SecurityGroup> userOffice = theUser.GroupMembership.FindAll(g => ControllerHelper.GetAllOffices().Contains(g.Office_ID)).ToList();









var test = (from o in db.Offices

             join oa in db.OfficeADGroups on o.Office_ID equals oa.Office_ID
           where oa.ADGroup_SID.Equals(userOffice.Select(uo => uo.ADGroupSID).ToString())
select new
{
o.Office_ID,
o.Office_Name
}).AsEnumerable();

return new SelectList(test, "Office_ID", "Office_Name");


The problem did not arise until it ran.  The query compiled but since we are dealing with LINQ the query did not execute until runtime.  Then I received the following error:



Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType9`2[System.Guid,System.String]]' to type 'System.Web.Mvc.SelectList'

Solution:

The problem was the lack of support from Entity Framework.  It will only support primitive data types.  The query uses anonymous typing until it is executed.  This process then tries to resolve the data type.  This will not support the use of custom data types.  I tried a number of work arounds to include forcing the execution of the query and then applying a cast to the SelectListItem type.


Try 1 - Fail
 var test = (from o in db.Offices
  ().Select(o => o.Office_ID) on oa.Office_ID equals uo.Office_ID
                        select new
                        {
                            o.Office_ID,
                            o.Office_Name
                        }).AsEnumerable()
            .Where(o => o.Office_ID.Equals(userOffice.Select(uo => uo.Office_ID)))
         
            new SelectListItem
            {
                Value = x.Office_ID.ToString(),
                Text = x.Office_Name
            });


This will work in Linq to SQL but is not supported in the current version of Entity Framework (v6).
The inclusion of the userOffice LINQ subquery is not supported in EF which will only support constant values.  That ruled out any sort of variable or collection.


Got it finally!


Solution was to take the LINQ out and do a direct query:


   using (var ctx = new FCJCModel())
            {
                var sql = "select Office_ID,Office_Name,Address_ID,Archive,LastUpdatedDate,LastUpdatedUser from office where Office_ID in (" + ofcGuids.Replace("\"", "'") + ")";
                var kk = ctx.Offices.SqlQuery(sql).ToList();
                return new SelectList(kk, "Office_ID", "Office_Name");
            }






Source:

  1. http://stackoverflow.com/questions/15211362/only-primitive-types-or-enumeration-types-are-supported-in-this-context
  2. http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx

Wednesday, August 31, 2016

MVC multiple layouts

Issue:

Working an MVC project which required us to use different layouts.  I knew you could do it but was not sure of the syntax. 

Solution:

It turns out there are at least 4 ways to do this.  I only am mentioning the solution we used since it is what we needed.  Feel free to the Net Stuff blog for more details.

Set Layout by Returning from ActionResult

You can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application.




public ActionResult Index()
{
 SampleModel model = new SampleModel();
 //Any Logic
 return View("Index", "_WebmasterLayout", model);
}


Source:

http://www.dotnet-stuff.com/tutorials/aspnet-mvc/how-to-render-different-layout-in-asp-net-mvc

Wednesday, June 29, 2016

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

 Problem:

Working a dynamic linq issue.  Using the great helper class, Predicate Builder posted over on the O'Reilly site.  I had built out my query and it worked great against my EF generated class.  Then I started getting this error each time I ran the predicate builder against a data type of nullable Guid.  I searched around on line at some more in depth explanations.  But nothing seemed to really fit my problem.

Solution:

Then I took the simple advice given on stackoverflow.  I changed the following lines
 


var race = Guid.Parse(race_ID);
predicate = predicate.Or(l => l.Race_ID.Equals(race));


to


var race = Guid.Parse(race_ID);
predicate = predicate.Or(l => l.Race_ID==race);

C# interpreter at work here: 

"When == is used on an expression of type object, it'll resolve to System.Object.ReferenceEquals.
Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents). "


so we could also do




var race = Guid.Parse(race_ID);
predicate = predicate.Or(l => l.Race_ID.Value.Equals(race));

Source:

  1. http://www.albahari.com/nutshell/predicatebuilder.aspx
  2. http://stackoverflow.com/questions/4592432/linq-query-keeps-throwing-unable-to-create-a-constant-value-of-type-system-obje
  3. http://stackoverflow.com/questions/814878/c-sharp-difference-between-and-equals

Thursday, June 2, 2016

Unable to create a constant value of type 'System.Object'

Problem:

I had a class created using the EF tools.  It generated a field which was a nullable Guid.  The datatype declaration was:


Guid? Status_ID


Each time I ran my controller code to build out my query.  I ran the code


Guid? ms_ID = Guid.Parse(MilitaryStatus_ID);
predicate = predicate.Or(l => l.MilitaryStatus_ID.Equals(ms_ID));


This would always through the unknown system.object error.  It was driving me crazy.


Solution:

I did not have any issues against data types of Guid which lead me to think about the nullable operator.  This seemed to be the issue so I removed it for testing and was able to run the above code no problems.  Thus realized that the issue was Linq not dealing with the nullable condition of my variable correctly.  Thus the work around was  to use == instead of Equals operator.


Guid? ms_ID = Guid.Parse(MilitaryStatus_ID);
predicate = predicate.Or(l => l.MilitaryStatus_ID == ms_ID);



Source:

http://stackoverflow.com/questions/4592432/linq-query-keeps-throwing-unable-to-create-a-constant-value-of-type-system-obje

Tuesday, April 5, 2016

MVC 5 bootstrap template not running under IIS express 7 -- Take 2

Problem:

Posted this problem earlier and gave a solution which seemed to work. 


"I have been running MVC project using default bootstrap template.  It works fine when I deploy it to our staging server.  When I attempt to run it locally on my desktop none of the bootstrap files are working.  I get no branding.


I wracked my brain on this and thought it might be missing files.  Then hit f12 on the browser and saw several of these gems:"






My original solution did not get it right

Appears that the css and js files are being blocked in iis express.  I am running this site using SSL and ADFS trust.  This appears to be causing some issues with local file access.  I know that IIS express runs as the local user.  I still granted IUSR and IIS_USRS accounts full access to the folders where the site was running on my local box.  This appears to have resolved the issue.

The real issue is NOT IUSR access to the local project folders.  Stack overflow gave me a push in the right direction.  The line: "I have Anonymous Authentication and Forms Authentication disabled. ASP.NET Impersonation and Windows Authentication are both enabled." helped me recognize that in IIS Express I might need to check the solution properties.

Solution:

Closer inspection of the properties see image 1 shows that the Windows Auth is set ot disabled. 




Image 1


My particular application is using SSL and PKI authentication.  The project needs to enable windows auth for my images and scripts to be available to the application in IIS Express.  Image 2 shows the Windows Authentication


Image 2
Once you set the Windows Auth to Enabled this will grant permissions to images, scripts and styles.




Source:

  1. http://fetchmytip.blogspot.com/2016/03/systemsecuritycryptographycryptographic.html
  2. http://stackoverflow.com/questions/16902601/http-error-401-2-unauthorized-for-new-site-in-a-working-app-pool