Tuesday, December 31, 2013

Generate XML from the Class Template




   In this post we are going to see how to generate the xml file from a template class. To generate the xml file from the class we have to specify the class as serialize and column as xml attribute to generate the values as attribute in xml file.




output:

<?xml version="1.0" encoding="utf-8"?>
<PeopleInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Peoples>
    <Person Name="Rajesh" Email="rajhseg@gmail.com" StreetAddress="R.E St" AdditionNotes="Notes 1" Birthday="2002-01-01T11:01:08.3657823+05:30" />
    <Person Name="Suresh" Email="sdsfs@gmail.com" StreetAddress="RG St" AdditionNotes="Notes 2" Birthday="1990-01-01T11:01:08.3667824+05:30" />
    <Person Name="Krish" Email="krisg@gmail.com" StreetAddress="GW St" AdditionNotes="Notes 3" Birthday="1992-01-01T11:01:08.3667824+05:30" />
  </Peoples>
</PeopleInfo>




C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    [Serializable]
    public class Person
    {
        [XmlAttribute]
        public string Name
        {
            get;
            set;
        }
         
        [XmlAttribute]
        public string Email
        {
            get;
            set;
        }

        [XmlAttribute]
        public stringStreetAddress
        {
            get;
            set;
        }

        [XmlAttribute]
        public string AdditionNotes
        {
            get;
            set;
        }

        [XmlAttribute]
        public DateTimeBirthday
        {
            get;
            set;
        }
    }



    [Serializable]
    public class PeopleInfo
    {       
        public List<Person> Peoples { set; get; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Person> Peoples = new List<Person>();
            Peoples.Add(new Person() {Name="Rajesh",Email="rajhseg@gmail.com",
                 Birthday=DateTime.Now.AddYears(-12),
                 AdditionNotes="Notes 1",StreetAddress="R.E St" });
            Peoples.Add(new Person() { Name = "Suresh", Email = "sdsfs@gmail.com"
                 Birthday = DateTime.Now.AddYears(-24), 
                 AdditionNotes = "Notes 2", StreetAddress = "RG St" });
            Peoples.Add(new Person() { Name = "Krish", Email = "krisg@gmail.com"
                 Birthday = DateTime.Now.AddYears(-22), AdditionNotes = "Notes 3"
                 StreetAddress = "GW St" });

            PeopleInfo ert = newPeopleInfo() { Peoples = Peoples};
            XmlSerializer serialize = newXmlSerializer(typeof(PeopleInfo));
            TextWriter writer = newStreamWriter(@"D:\sample.xml", true);
            serialize.Serialize(writer, ert);
            Console.Read();
        }
    }
}



In this post you can learn how to generate xml file from a class template.



Monday, December 30, 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
    {
        #regionFactory Method
   
        /// <summary>
        /// Create a new Department object.
        /// </summary>
        /// <param name="id">Initial value of the ID property.</param>
        public static Department CreateDepartment(global::System.Int32id)
        {
            Department department = newDepartment();
            department.ID = id;
            return department;
        }

        #endregion
        #regionPrimitive 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 voidOnIDChanging(global::System.Int32 value);
        partial voidOnIDChanged();
   
        /// <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 voidOnNAMEChanging(global::System.String value);
        partial voidOnNAMEChanged();

        #endregion
   
        #regionNavigation 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>







Sunday, December 29, 2013

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 stringEmployeeName { 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 intDepartmentId { set; get; }
    }



C#:

        [HttpPost]
        [ActionName("Edit")]
        public ActionResultEdit_Post(int employeeId)
        {
            Employee emp = (newEmployeeDbContext()).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 voidPage_Load(object sender, EventArgs e)
        {

        }

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


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



            if (sourceUrl.Length > 0)
            {
            }
            else
            {
                throw newSystem.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.