Monday 30 December 2013

View Engines Present in ASP.NET MVC

In this article we are going to see number of view engines present in the MVC. There are two types of View Engine

1. Razor View Engine
2 .Aspx View Engine

In Razor

  • Code can be done by start of @ 
  • vb and cs file are in the extension of cshtml and vbhtml
In Aspx

  • Code should be in between the <%:  %>
  • vb and cs file are in the same extension .aspx
In the project we can have both aspx and razor view files,We can also use third party view engines.

Map a MetadataType to the Entity Framework Model - ASP.NET MVC

In this article we are going to see how to map a MetadataType to the Model class for applying the additonal rules and conditions.In the following samples we are created the model using entity framework.

Model created by EntityFramwork :

[EdmEntityTypeAttribute(NamespaceName="EmployeeModel", Name="Department")]
    [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class Department : EntityObject
    {
        #region Factory Method
   
        /// <summary>
        /// Create a new Department object.
        /// </summary>
        /// <param name="id">Initial value of the ID property.</param>
        public static Department CreateDepartment(global::System.Int32 id)
        {
            Department department = new Department();
            department.ID = id;
            return department;
        }

        #endregion
        #region Primitive Properties
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
        [DataMemberAttribute()]
        public global::System.Int32 ID
        {
            get
            {
                return _ID;
            }
            set
            {
                if (_ID != value)
                {
                    OnIDChanging(value);
                    ReportPropertyChanging("ID");
                    _ID = StructuralObject.SetValidValue(value);
                    ReportPropertyChanged("ID");
                    OnIDChanged();
                }
            }
        }
        private global::System.Int32 _ID;
        partial void OnIDChanging(global::System.Int32 value);
        partial void OnIDChanged();
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String NAME
        {
            get
            {
                return _NAME;
            }
            set
            {
                OnNAMEChanging(value);
                ReportPropertyChanging("NAME");
                _NAME = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("NAME");
                OnNAMEChanged();
            }
        }
        private global::System.String _NAME;
        partial void OnNAMEChanging(global::System.String value);
        partial void OnNAMEChanged();

        #endregion
   
        #region Navigation Properties
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [XmlIgnoreAttribute()]
        [SoapIgnoreAttribute()]
        [DataMemberAttribute()]
        [EdmRelationshipNavigationPropertyAttribute("EmployeeModel", "FK__EMPTABLE__DEPTID__1A14E395", "EMPTABLE")]
        public EntityCollection<Employee> Employees
        {
            get
            {
                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Employee>("EmployeeModel.FK__EMPTABLE__DEPTID__1A14E395", "EMPTABLE");
            }
            set
            {
                if ((value != null))
                {
                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Employee>("EmployeeModel.FK__EMPTABLE__DEPTID__1A14E395", "EMPTABLE", value);
                }
            }
        }

        #endregion
    }
   
  


MetadataType:

[MetadataType(typeof(DepartmentMetadata))]
    public partial class Department
    {

    }

    public class DepartmentMetadata
    {
        [Display(Name="Department Name")]
        public string NAME { set; get; }
    }



In this we need to change the display name of a Property, so we can see how to do this .



HTML :

@model EmpApp.Models.Employee

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.NAME)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.NAME)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Department.NAME)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Department.NAME)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.COUNTRY)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.COUNTRY)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.MARRIED)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.MARRIED)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>







Bind a Model for form post using interface - ASP.NET MVC



In this article we are going to see how to bind a model values from the form post , by ignore the exclude properties for binding.

By passing the Interface type in update model ,it will update the particular properties which are present in Interface to the object

Interface:
public interface IEmployee
    {
        int EmployeeId{set;get;}

        string Country { set; get; }

        string Married { set; get; }

        int DepartmentId { set; get; }
    }



Employee Model:

    [Table("EMPTABLE")]
    public class Employee:IEmployee
    {
        [Column("ID")]       
        public int EmployeeId { set; get; }

        [Column("NAME")]
        [Required(ErrorMessage="Please Fill Employee Name")]       
        public string EmployeeName { set; get; }

        [Column("COUNTRY")]
        [Required(ErrorMessage="Please Fill the Country")]
        public string Country { set; get; }

        [Column("MARRIED")]
        [Required(ErrorMessage="Please Specify the Married y/n")]
        public string Married { set; get; }

        [Column("DEPTID")]
        [Required(ErrorMessage="Please specify the Department")]
        public int DepartmentId { set; get; }
    }



C#:

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int employeeId)
        {
            Employee emp = (new EmployeeDbContext()).Employees.Single(x => x.EmployeeId == employeeId);
            TryUpdateModel<IEmployee>(emp);
            if (ModelState.IsValid)
            {
                BusLayer bl = new BusLayer();
                bl.Update(emp);
                return RedirectToAction("Details", new { id=emp.DepartmentId});
            }
            return View(emp);
        }




From this article you can learn how to bind the model values from the form post using the interface. which will help to ignore the unwanted values to bind in form post.

Play a Video File from the Web - ASP.NET

In this article we are going to see how to play a video file from the web or offline, for this we are creating a application which will take the input in from the text and Play the file.

We are creating a Literal control and assign the object value at run time while play.

HTML:
<form id="form1" runat="server">
    <div>
  <br />
  <br />
  <asp:literal id="Literal1" runat="server"></asp:literal>
  <br />
  <br />
  <asp:textbox id="InputText" runat="server" width="500px" height="50px" wrap="true"
            textmode="multiLine" readonly="false" >http://localhost:30687/Harivarasanam.mp4</asp:textbox>
  <br />
  <br />
  <asp:button id="Button1" runat="server" text="Play" onclick="Button1_Click" />
    </div>
    </form>



C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Player : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                string mySourceUrl = this.InputText.Text;
                bool isFullSize = false;
                this.Literal1.Text = this.GetWma(mySourceUrl, isFullSize);
            }
            catch (Exception ex)
            {
                this.Response.Write(ex.ToString());
            }
        }


        private string GetWma(string sourceUrl, bool isFullSize)
        {
            string newtag = "";
            sourceUrl = sourceUrl + "";
            sourceUrl = sourceUrl.Trim();



            if (sourceUrl.Length > 0)
            {
            }
            else
            {
                throw new System.ArgumentNullException("sourceUrl");
            }

            string myWidthAndHeight = "";



            if (isFullSize)
            {
                myWidthAndHeight = "";
            }
            else
            {
                myWidthAndHeight = "width='640' height='480'";
            }



            newtag = newtag + "<object classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' id='player' " + myWidthAndHeight + " standby='Please wait while the object is loaded...'>";
            newtag = newtag + "<param name='url' value='" + sourceUrl + "' />";
            newtag = newtag + "<param name='src' value='" + sourceUrl + "' />";
            newtag = newtag + "<param name='AutoStart' value='true' />";

/* -100 is fully left, 100 is fully right. */
newtag = newtag + "<param name='Balance' value='0' />";                    

/* Position in seconds when starting. */
newtag = newtag + "<param name='CurrentPosition' value='0' />";

/* Show play/stop/pause controls. */
 newtag = newtag + "<param name='showcontrols' value='true' />";

/* Allow right-click. */
newtag = newtag + "<param name='enablecontextmenu' value='true' />";

/* Start in full screen or not. */
             newtag = newtag + "<param name='fullscreen' value='" +                                                  isFullSize.ToString() + "' />";             

             newtag = newtag + "<param name='mute' value='false' />";
           
/* Number of times the content will play.*/
 newtag = newtag + "<param name='PlayCount' value='1' />";                 

/* 0.5=Slow, 1.0=Normal, 2.0=Fast*/
newtag = newtag + "<param name='rate' value='1.0' />";         

/* full, mini, custom, none, invisible */
newtag = newtag + "<param name='uimode' value='full' />";                  

/* Show or hide the name of the file.*/
newtag = newtag + "<param name='showdisplay' value='true' />";             

/* 0=lowest, 100=highest */
newtag = newtag + "<param name='volume' value='50' />";        
newtag = newtag + "</object>";  

            return newtag;
        }
    }
}


Output:


After Play





















From this article we can see how to play a video file from web or from the offline.

How to Exclude or Include the properties of Model while Binding in Form POST - ASP.NET MVC



In this article we are going to see how to Exclude or Include the Properties of Model while binding in form post, actually what is the need for explicit specify the properties to bind ? When we send a POST from the form it will bind the all values from the user request , so there is a scenario user can change the value of a read only value in POST Request , then the model will have a impact of changed one, To avoid this kind of things we are explicitly saying that thing kind of properties can be include or exclude from binding using a Attribute called Bind in the parameter.

Inside the Bind attribute we can pass the parameters Include , Exclude with value as string , Properties can be specify by the comma separated. while binding as parameter in the method we have to specify the control name, but for the Bind we have to specify the Property name of the Model.



        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post([Bind(Exclude = "Name", Include = "EmployeeId,Country,Married,DepartmentId")]Employee emp)
        {

            emp.EmployeeName = (new EmployeeDbContext()).Employees.Single(x=>x.EmployeeId==emp.EmployeeId).EmployeeName;

            if (ModelState.IsValid)
            {
                BusLayer bl = new BusLayer();
                bl.Update(emp);
                return RedirectToAction("Details", new { id=emp.DepartmentId});
            }
            return View(emp);
        }





From this article we can see how the values from the Form post are bind to the model instance of the input.


How to Get the Difference between the Two Days


In this post we can see how to get the difference between the two dates
DateTime dt1 = DateTime.Now;
            DateTime dt2 = DateTime.Now.AddDays(3).AddSeconds(34);
            System.Threading.Thread.Sleep(4000);
            TimeSpan span = dt2 - dt1;
          
            Console.WriteLine(" Days: " + span.Days +" Min: "+span.Minutes+" Sec: "+span.Seconds);
            Console.Read();



Output:

Days: 3 Min: 0 Sec: 34


Add the Span to the Date:

DateTime Sample = DateTime.Now.AddDays(4);
            Sample.Add(span);


From this post you can learn how to add the date and difference between the dates.

Sunday 29 December 2013

Update the Selected Properties of the Model in Form Post ASP.NET MVC

In this article we are going to see how to update the Model of selected properties in the Form Post , For that we  have to understand about UpdateModel method, this method is used to update the model type variable value with the form post value. When there is a null value in the required column then the error will raise to avoid error, try to use the TryUpdateModel  in this method when validate the posted value if any model validation error is there then it will return false.

Try to use ModelState.IsValid property to check that the Model doesn't have any validation error.There is a second parameter in which series of string array parameter can be passed which specifies the property names.


 Controller:

        [HttpGet]
        [ActionName("Edit")]
        public ActionResult Edit_Get(int id)
        {
            Employee emp = (new EmployeeDbContext()).Employees.Where(x => x.EmployeeId == id).FirstOrDefault();
            return View(emp);
        }

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id)
        {


            Employee emp = (new EmployeeDbContext()).Employees.Single(x=>x.EmployeeId==id);
            TryUpdateModel(emp,new string[]{"Country","Married","DepartmentId"});

            if (ModelState.IsValid)
            {
                BusLayer bl = new BusLayer();
                bl.Update(emp);
                return RedirectToAction("Details", new { id=emp.DepartmentId});
            }
            return View(emp);
        }

Model:

[Table("EMPTABLE")]
    public class Employee
    {
        [Column("ID")]       
        public int EmployeeId { set; get; }

        [Column("NAME")]
        [Required(ErrorMessage="Please Fill Employee Name")]       
        public string EmployeeName { set; get; }

        [Column("COUNTRY")]
        [Required(ErrorMessage="Please Fill the Country")]
        public string Country { set; get; }

        [Column("MARRIED")]
        [Required(ErrorMessage="Please Specify the Married y/n")]
        public string Married { set; get; }

        [Column("DEPTID")]
        [Required(ErrorMessage="Please specify the Department")]
        public int DepartmentId { set; get; }
    }


Business Layer:

public class BusLayer
    {
        public void Update(Employee emp)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeDbContext"].ConnectionString);
            con.Open();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
               
                cmd.CommandText = "EMP_Upd";
                cmd.Parameters.Add(new SqlParameter("@ID", emp.EmployeeId));
                cmd.Parameters.Add(new SqlParameter("@NAME", emp.EmployeeName));
                cmd.Parameters.Add(new SqlParameter("@DEPT", emp.DepartmentId));
                cmd.Parameters.Add(new SqlParameter("@COUNTRY", emp.Country));
                cmd.Parameters.Add(new SqlParameter("@MARRIED", emp.Married));
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }

        public void Create(string name, string country, string married, int departmentid)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeDbContext"].ConnectionString);
            con.Open();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "EMP_ADD";
                cmd.Parameters.Add(new SqlParameter("@NAME", name));
                cmd.Parameters.Add(new SqlParameter("@DEPT", departmentid));
                cmd.Parameters.Add(new SqlParameter("@COUNTRY", country));
                cmd.Parameters.Add(new SqlParameter("@MARRIED", married));
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }
    }


From this article you can learn how to bind  the selected Model properties for submit from a Form.