Dynamically Load Form in MVC Razor View Engine

One part of my project gives user the ability to create forms and render it dynamically. Here's how I render the  form definition from an XML container in Razor view engine.

The View
@model MyProject.Models.DynaForm
@using (Html.BeginForm("ViewForm","FormManagement"FormMethod.Post))  
{
   var sectionCollection = from s in Model.XmlForm.Descendants("section"select s;
   foreach(System.Xml.Linq.XElement section in sectionCollection) // get sections
   {
   var fieldCollection = from f in section.Descendants("field"select f; // get fields
   <fieldset>
     <legend>Section @(section.Attribute("id").Value)</legend>
     @foreach (System.Xml.Linq.XElement field in fieldCollection) // iterate over each field
        {
        <div>
          <div>@field.Attribute("name").Value</div>
         <div>@Html.TextBox(field.Attribute("name").Value, field.Value, new { @class = field.Attribute("inputtype").Value }) </div>
        </div>
        }
    </fieldset>
    }
  <input type="submit" name="submit" value="save" />
  <input type="submit" name="submit" value="cancel" />
}

The Controller
public class ViewFormController : Controller
{
    Models.DynaForm oWorkflow = new Models.DynaForm();
    public ActionResult ViewForm()
    {
        oDynaform.ID = 1;
        oDynaform.XmlForm = XDocument.Load(Server.MapPath("~/App_Data/myform.xml"));                 return View("ExecuteRequest", oWorkflow); // pass this to view for rendering
    }
 
    [HttpPost// POST handler
    public ActionResult ViewForm(string submit)
    {
        switch (submit)
        {
            case "save":
                // delegate sending to another controller action
                return (Save());
            case "cancel":
                // call another action to perform the cancellation
                return (CancelRequest());
            default:
                // If they've submitted the form without a submitButton, 
                // just return the view again.
                return (View());
        }
    }
 
    private ActionResult CancelRequest()
    {
        return (PartialView()); // return to same page
    }
 
    private ActionResult Save()
    {
        oDynaForm.ID = 2;
        return (PartialView("ViewForm", oDynaForm));    }
}



The XML field template.
<dynamicform name="yourform" id="1">
  <section id="1">
    <field type="text" name="First name" inputtype="textbox" />
    <field type="text" name="Last name" inputtype="textbox" />
    <field type="text" name="Email" inputtype="textbox" />
  </section>
  <section id="2">
    <field type="text" name="Other information" inputtype="textarea" >  Other info here </field>
  </section>
  <section id="3">
    <field type="text" name="Input 1" inputtype="textarea" />
    <field type="text" name="Input 2" inputtype="textarea" />
    <field type="text" name="Input 3" inputtype="textarea" />
  </section>
</dynamicform>

Upgrading .NET Framework of IIS Application Pool

You've just installed your new website in IIS server but it doesn't seems to render correctly or throwing an error and pointing you to this line in web.config

<compilation debug="true" targetframework="4.0">


Check your application pool, chances are, .NET Framework 4 is not yet installed. If your target framework is framework 2, then you can change that line to 2.0, as most IIS server default framework is using framework 2.0. Otherwise, you may need to install .NET framework 4. Follow that link to install  (http://www.microsoft.com/net/download/version-4).

After installation, run DOS in administrator mode, then dig to the specific framework directory and type the following (aspnet_regiis.exe -ir) as seen on this snapshot, to register and install it in IIS without affecting your IIS installation and current configuration.




Open up your IIS manager, then change your website application pool to corresponding framework version. In this case, it's .NET Framework v4.0.30319.

MVC and Entity Framework's Code First

I have a new web application project and decided to use MVC 4 and Entity Framework's Code First. I'll post here the problems encountered and how I fixed it.

MVC has option for automatic scaffolding when creating the CRUD functionality, but when I tried to execute it, I got the following error.

Invalid value for key 'attachdbfilename'.

I've searched the net for an hour and never found the solution. Though my connection string is working correctly, I decided to take a second look at the web.config and seen this peculiar line of setting. So I commented the LocalDBConnectionFactory and replaced with System.Data.Entity.Sql.ConnectionFactory instead so it will use the connection string on parameter. It fixed my problem.

<entityframework>
    <defaultconnectionfactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <!--<defaultconnectionfactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >-->
      <parameters>
        <parameter value="Data Source=USER-PC\SQLServer;Initial Catalog=MyDB;Integrated Security=True"></parameter>
      </parameters>
    </defaultconnectionfactory>
</entityframework>

Entity Framework has this inherent problem whenever it needs to check Model changes, and it won't drop/create the target table, when you want to save. The following error, where 'dbContext' is your defined DB Context.

Exploring LINQ


During the old days of .net programming from framework 1.1 to framework 2.0, there's no LINQ library yet, so I established my skills on all sorts of different syntaxes for querying SQL, parsing XML Xpath, Object enumeration. But the demand for LINQ is unavoidable. This abstracted library for querying all sort of objects, be it SQL, dataset, XML, objects, arrays, etc. is quite handy because it allows you to query using a standard query syntax for all types of objects.

The linq syntax is easier to practice using this tool called linqpad (www.linqpad.com). This allows you to execute queries from specified database and tables. For instance I want to...

Read all data from table
from O in ORDERs select O

It has also support for reading only a portion and in the middle of table (similar to MySQL limit statement)

(from O in ORDERs select O).Skip(100).Take(50)

Joining two tables whose order id equals orderdetails id, and select firstname and the item from orderdetails.

from o in Orders join od in OrderDetails on o.ID equals od.OrderID select new {o.Firstname,od.Item}

Source: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

RAD Tools for Web App Development

During my early years of programming in the 90s, every application needs to be coded manually and UI is text in appearance,  programmers are limited to make UI out from combination of ASCII based characters.  There are some attempts to make coding much simplier or at least much faster, one such RAD tool that exist is called Layout, it's the first WYSIWYG studio at that time, that could create true graphical UI and could run from DOS (has it's own graphics engine, and doesn't need windows OS).

Layout was the first 4th generation language at that time. Imagine, you could create an application without a single coding effort, by just creating a flowchart and specifying the flow of the application by connecting lines to each and every box, each box represents a functionality, and the source code will be generated for you in either Basic, C++ or Pascal. This is similar to Windows Workflow Foundation of .NET framework, but less complicated. I created a simple app that I named Food Costing for storing/creating a list of recipies, and computes capital and retail cost in no time, even converted a Clipper based IT Applicant Exam in just 2 days. There was one another contender called Magic but these didn't last long.

How to Download JDK in CentOS / RHEL and Auto Accept License Agreement

Recently as I was about to update a JDK on my Linux box (CentOS), the command wget couldn't get thru, it's receiving a 302 error. Browsing Oracle's download site, it has now a radio-button to accept / decline the License Agreement.

Here's a workaround to bypass that. Issue the following command (make sure you replace the correct version of the JDK you're downloading).


 wget --no-cookies --header "Cookie: gpw_e24=http%3A#2F#2Fwww.oracle.com" "http://download.oracle.com/otn-pub/java/jdk/7u5-b05/jdk-7u5-linux-x64.tar.gz"

Saving Objects for Later Debugging in .NET

One of the often challenge in debugging objects in .NET is the ability to start debugging in the middle of the running application, without the need to recreate all possible scenarios (be it data entry, API inputs ) just to arrive at the transformed data or derived object. This technique could also be used for requirements like persisting objects and saving it to database for later or whatever use.

I've written a small utility that saves object to disk, and later load it back to the target object. This tool simply serializes object on save and deserialize it on load.

Here's the snippet.

namespace Generics
{
   public class Serializer<T>
   {
       public static T Load(string strPathFile)
       {
          T oBj = default(T);
          System.Xml.Serialization.XmlSerializer objDeSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
          System.IO.TextReader reader = new System.IO.StreamReader(strPathFile);
          temp = (T)objDeSerializer.Deserialize(reader);
          reader.Close();
          return oBj;
       }

       public static void Save(string strPathFile, T oObject)
       {
          System.Xml.Serialization.XmlSerializer objSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
          System.IO.TextWriter writer = new System.IO.StreamWriter(strPathFile);
          objSerializer.Serialize(writer, oObject);
          writer.Close();
       }
   }
}

Make sure to put [Serializable] attribute on top of every class you want to get serialized.