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

Tuesday, November 22, 2016

IIS application pool recycles on each page load.



Problem:
I had applied DISA STIG to an IIS application.  Once this was done all page loads required new sessions.  This wiped out any session memory since this gets wiped when a page reloaded.




Why:
Culprit was application pool settings Virtual Memory Limit. 


 


This setting prevents an application from consuming all available memory for IIS which then would


Cause IIS to shut down and force a restart bringing down all websites on that instance of IIS.


The virtual memory limit was designed to prevent this by setting a threshold.  Once that threshold


Is reached the app pool automatically recycles wiping memory and thus preventing any danger of


Lockout due to excessive memory usage. 


 


Explanation:


This setting is was valid in IIS 7 when 64 bit OS'es were not always the norm.  In IIS 8.5 we are on 64 bit OS and ASP.Net does memory management much better.  Further complications are that ASP.Net's memory management can get into a "fight" with IIS over who is doing memory management.   This will only occur if you set the Virtual memory limit to something besides 0 (default).  This is exactly was the IIS 7 STIG prescribes.   End result is that the application pool session is constantly being recycled.  This means that a long running FSA session can be terminated during the middle of an operation.  If this occurs more than 5 times in 5 minutes then the app pool is automatically locked.



Solution:


The Virtual memory limit on the FSA application pool has been set to its default value 0.  This means that ASP.Net will manage memory inside the application.






Source:
https://technet.microsoft.com/en-us/library/cc732519(v=ws.10).aspx
http://blog.walteralmeida.com/2011/07/iis7-private-memory-limit-versus-virtual-memory-limit.html

How to enumerate fields in a pdf form?

Problem:
Needed to list all the fields in an existing pdf form.  This will then be used to populate the pdf fields from a web form.


Solution:


AcroFields af = ps.AcroFields;


foreach (var field in af.Fields) {
            Console.WriteLine("{0}, {1}", field.Key, field.Value);
        }




Source:
http://stackoverflow.com/questions/3041883/how-do-i-enumerate-all-the-fields-in-a-pdf-file-in-itextsharp

Pdf writer for a website.

Problem:
Needed to solve a common problem.  Need to prepopulate an Adobe Pdf form from a web form.
This is a pretty common tasks and several packages are available.


Solution:
I decided to go with itextsharp.  This seems like a popular choice and there were plenty of samples available.  The software will let you fill out an existing pdf form.  This presupposes that you have a completed Adobe form.  If you don't you can create it with this package or you can buy a copy of Adobe Acrobat Pro.




Source:
http://stackoverflow.com/questions/31584274/where-download-examples-of-itextsharp
https://sourceforge.net/projects/itextsharp/







Wednesday, October 12, 2016

What is Load User Profile in IIS 8.5?



Specifies whether IIS loads the user profile for an application pool identity. When set to True, IIS loads the user profile for the application pool identity. Set to False when you require IIS 6.0 behavior.


This is great for application isolation.  It also can have an impact on your application if you are using Active Directory to manage application access.  The Windows Cryptographic Service Provider will try to store or load a key for your certificate in the user store, and this will require a profile to be available; otherwise, a cryptographic context error will occur.


Note that the Load User Profile setting only applies to user accounts. Service Accounts like NETWORK SERVICE and ApplicationPoolIdentity have special handling.


Source

http://stackoverflow.com/questions/17149132/what-exactly-happens-when-i-set-loaduserprofile-of-iis-pool


https://technet.microsoft.com/en-us/library/cc745955.aspx

What is IIS application pool Idle Timeout Action?

Starting in IIS 8.5, the application pool idle process capability was extended.  In prior versions, the worker process  had an idle timeout property.  When the idle timeout was configured, a worker process will shut down after a specified period of inactivity, by default 20 minutes. 


What happened when that boundary was hit was that the worker process was terminated.  The session would be terminated.  This killed the session and the user would be forced to start over.  This is an issue for a customer who tends to have long web sessions.


The idle process capability provides the ability to override the default terminate behavior.  The property is either terminate (default) or suspend.  A suspended worker process remains alive but is paged-out to disk, reducing the system resources it consumes. When a user accesses the site again, the worker process wakes up from suspension and is quickly available. When an idle worker process is terminated, the worker process is shut down and the startup period will be longer when the site is subsequently accessed. The default behavior is to terminate the idle worker process, and the same behavior is used in the previous versions of IIS.


Source:

https://www.youtube.com/watch?v=hkizFsHDexA
https://nimitsharma.wordpress.com/2014/10/03/introducing-iis-application-pool-idle-timeout-action/

Tuesday, October 4, 2016

MVC Razor Syntax: Can't implicitly convert bool? to bool

Problem:

My model had several variables which were nullable Booleans.  My issue was how to bind them in the Razor syntax without getting an error.


I had tried
@Html.CheckBoxFor(model=>(bool) model.LengthConfinementLife)


which will compile but fails on a runtime error.


Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Solution:



@Html.CheckBox("LengthConfinementLife", Model.LengthConfinementLife?? false)
@Html.Label("LengthConfinementLife", "My Dates are Flexible")


Source:

http://stackoverflow.com/questions/6849774/mvc3-creating-checkbox-for-nullable-boolean