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.

Node.js - Multithreaded Javascript Engine

Ever wondered how to implement multithreading in PHP? Natively, PHP can't do multithreading, only multiprocessing, but multiprocessing on a single resource in PHP is not robust solutions as it could encounter race condition, which is common problem in multithreading if the resource is not locked prior to being used. There are several techniques implementing multithreading in PHP but I'm only mentioning this particular lightweight framework. This is even simplier than ASP.NET inherent multithreading capabilities.

Node.js (http://nodejs.org) is a javascript framework that could even act as a small web server. It allows you to implement multithreading without the hassle of locking/unlocking resources. It could even allow you to design stateful web (equivalent to viewstate/session management). It's even best for designing scalable clustered web app (where several instance resides on same multi-core servers or different servers with load balancer).


No Symbols Loaded - Debugging Silverlight App in ASPX Page

I was once assigned to an ongoing silverlight project with Dynamic CRM integration with no technical documentation and was oriented only on the basics. Being an inquisitive person but couldn't get much help from the original team of developers (offshore), what I did was to examine the flow in debug mode. It's an expensive approach but leaves me no choice.

Fixing Too Many Connection Problem

My very first .Net project way back in year 2003 using Visual Studio 2003 (later switch to 2005, 2008 and 2010 as time went by), and using MySQL 4.1 (later migrated to MySQL 5.5) as the backend database, was faced with the same database connectivity problem, the application often would encounter this  "Too many connection.." error, when the database driver (MySQL.NET), after some prolong running, could not established database connection anymore.

I've fixed this by inserting the following code under the try/catch database connectivity error handler.
System.Data.SqlClient.SqlConnection.ClearAllPools();
The same line of code works in .NET default data driver ADO.NET hence MySQL.Net driver has adopted ADO.NET namespace for ease of using either SQL Server or MySQL database.

The nature of my application is multithreaded and demands for very fast database connection as each task per user has to spin each own background thread from the threadpool. But if your application is not very particular about database connection speed and would like each instance being destroyed immediately after closing the database connector, you can adjust it on IIS application settings or via the connection string by setting Pooling=false.

Reading Cookie from Other Website with Different Domain

By W3C rule, a web browser is not permitted to read cookies from different site with different domains. So how do we beat the challenge of reading cookies from other 3rd party site when let's say you were task to integrate it in your site and there are some needed parameters that are stored on 3rd party cookies which you need to read.

You'll need your Network Admin guy for this task or if you have access to CPanel or similar UI which allows your to assign subdomain alias (CNAME).

Single Login Session Between Websites

Single sign-on or login allows user to login from one site or another and authentication happens only once per active session. Without this mechanism, it would be annoying to the user whenever he wants to switch between website and prompted again to login.

In ASP.NET, to implement single sign-on or login between websites on same domain with different subdomain, do the following:

Where to Upload and Host CSS / Javascript - Fast and Free

There are a lot of free site that offers to host your script for free yet some have limited bandwidth and slow. But there's one without bandwidth limit and very fast, yet the feature is not obvious for hosting CSS and JAVA script.

Google has a lot of useful yet free applications, and one of that is Google Docs. It's a collaborative office applications where it allows you to do document editing online., but we're not going to use that feature, rather to host script file.

MS Access Export to Excel or CSV

Exporting data from Ms Access 2007 to Excel from code is just a one line statement using DoCmd.TransferSpreadsheet, but in CSV there's an inherent bug so I created my own export module. Plus a special function that saves file to disk, which I modified a bit to make it work on 64 bit machine.













Deploying CRM 4 Database Instance to Another Server

Our IT admin was once task to deploy an existing CRM 4 instance to another server for development purposes and he sought my help.

It's assume you have prior knowledge of SQL Server Management Studio, then do the following:
1) Backup the CRM database.
2) Install Microsoft SQL Server 2005 or 2008 on a new server
   2.a)- make sure SSRS feature checkbox is checked, this reporting services is required by CRM.
3) Install Dynamic CRM 4 to that same server.
4) Restore CRM database.

Rapid UI Wireframe Prototyping with Evolus Pencil

In desktop or web application development, some users could effectively narrate how they want the application's UI usability would look like, but some requires to see a glimpse of a UI prototype before they could finally agree at least initially to the laid out UI. There are variety of tools to do this, and there's one tool that became one of my favorite named Evolus Pencil (http://pencil.evolus.vn/en-US/Home.aspx). Ironic that it was built on Javascript but the homepage was created in asp.net.


Evolus' Pencil allows you to create rapid UI prototype. The simplicity of this tool is what caught me and the sketchy appearance, which mimic the appearance of hand-drawn UI. This could also be used to prototype flowchart, or even touchscreen/pad apps.

There are many UI wireframe prototyping available, some even are interactive but I have covered only this one, being used most often.

ReactOS a free OS replacement for Windows XP/2003

Aside from the corporate world, if there's any other reason why I'm sticking to Windows OS, is that most of my best favorite games on PC runs on Windows, and neither I would sacrifice game performance thru the use of emulators just to run games in other OS.

If only all game developers have supported OpenGL, users would have a variety of OS to run games, but then it seems DirectX has dominated as the graphics API of choice for game development, it's because it forces developers to choose it, to support newer releases of Windows OS. DirectX 11 will only run under Windows Vista, 7 and 8.

This is the sad part, goodbye to DirectX 10 which would only run under Windows XP/ME edition. If you have newer games that only could run under DirectX 11, you are obliged to upgrade your Windows OS as well.

But wait, there are bunch of geeks developing a so called ReactOS (www.reactos.org), a substitute to Windows dominance, it's neither Linux or other emulated OS. It's a Windows OS built based on Windows XP and Windows 2003 architecture. It aims to support all Windows Applications that runs on previous version of Windows, including the support for DirectX of any version. Hopefully it will succeed if we users support it.

Spread the word!

Hiding Footer, Navigation Bar, Logo - Customizing Blogpost

Sometimes you want greater control over a ready made template in blogspot for personal choice. Here's a compiled tip how you could customize and override it by using the power of CSS. There are some other non CSS hack like commenting out some code but sometimes it becomes non-workable so I've choosen only CSS technique as it seamlessly work across different browsers.

Before you go any further,  it's best to copy and paste your blogspot html in a notepad editor, this is to avoid accidental messing of template/html, in my case I use notepad++, then do the code change from there, and copy/paste the entire content from notepad back to blogspot html editor.

Edit your blog HTML (under template, click edit template/html) and insert the following line of code on the template, just right above this excerpt of code "/* Variable definitions ... "

Don't Judge Linux by its Cover

During my college years in the 90s, we were taught all about DOS (Disk Operating System). Typing commands from the console is fun, and I even love doing batch programming, but then Windows came and it appealed to many, because of its intuitive user interface. No doubt, Windows dominated the personal computers, and most of my programming careers were centered on Windows OS.

Recently Linux is fast becoming one of the well known OS, though it appealed mostly to techno savy users because it has no intuitive interface pleasing to the general public. It's just like DOS where you have to type every command at the console. It didn't caught much of the common users attention until a friendly GUI or Windows like interface have proliferated like Ubuntu, and CentOS to name a few.

Reverse Proxy Using Nginx to Serve Static Files Faster

Reverse Proxy
A proxy in common usage, is a stand-in for a web-browser. When a web browser requests access to a web resource, the web resource needs some idea of where it should send the answer. In reverse, the proxy stands-in for the web server. In such a case, the true location of the web server (whose content is being served) is hidden, from the standpoint of the client making the request.

The common solutions found on web is to point all traffic to NGINX and route traffic to APACHE if it's not static files, but with our case, we don't want to change the current configuration of existing APACHE installation and settings as much as possible. The safe technique will be used to serve static contents like images from another server using a much lighter web server application name NGINX. The rest of the page would remain served via APACHE.

I've done this prototype in 64 Bit Red Hat Linux, some command may vary in other Linux distro.